Build with the Virtru Developer Hub

It's Your Data. Protect It. Control It. Everywhere.

Try the Demo          Learn More     

How to Encrypt a File

Encrypting and protecting a file is easy with the Virtru SDK. Provided the authentication is done (see see How to Add Authentication, you can encrypt a file with just a few lines of code:

Behind the Scenes

Click here to follow the encryption lifecycle.

<!DOCTYPE html>
<html>
<head>
    <title>Virtru SDK for JavaScript - Sample Application</title>
    <link href="https://sdk.virtru.com/js/latest/auth-widget/index.css" rel="stylesheet"/>
    <script src="https://sdk.virtru.com/js/latest/auth-widget/index.js"></script>
    <script src="https://sdk.virtru.com/js/latest/virtru-sdk.min.js"></script>
</head>

<body>
  <div id="virtru-auth-widget-mount"></div>
  <script type="text/javascript">
    async function afterAuth(email) {
      // Run all client code from here. 
      // This will only be called when the user is successfully authenticated.
      const client = new Virtru.Client({email});
      const yourString = prompt('Type a sting to encrypt: ', 'Hello, world!');
      const encryptParams = new Virtru.EncryptParamsBuilder()
        .withStringSource(yourString)
        .withDisplayFilename('hello.txt')
        .build();
      ct = await client.encrypt(encryptParams);
      await ct.toFile('hello.html');
    }
    // Set up the auth widget.
    Virtru.AuthWidget('virtru-auth-widget-mount', {afterAuth});
  </script>
</body>
</html>
const Virtru = require('virtru-sdk');

async function run(){
  const email = 'alice@example1.com;
  const appId = '12345678-1234-1234-1234-123456789012';
  const client = new Virtru.Client({email, appId});
  const encryptParams = new Virtru.EncryptParamsBuilder()
    .withStringSource('Hello, world!')
    .withDisplayFilename('hello.txt')
    .build();
  ct = await client.encrypt(encryptParams);
  await ct.toFile('hello.html');
}
run().then(() => console.log('Created my first encrypted file!'));
# two authentication methods are supported: 
# (a) HMAC sent by your Virtru Rep (b) AppId Token that you can download from Virtru Dashboard.

from virtru_tdf3_python import Client, Policy, EncryptFileParam

# encrypt the file and apply the policy on tdf file and also decrypt.

# authenticate via HMAC and create a client for 'alice@example1.com'.
# You can get your org's HMAC token/secret by contacting your Virtru Rep.
client = Client(owner="alice@example1.com",
                api_key="12345678-1234-1234-1234-123456789012@tokens.virtru.com",
                secret="someSecret==")

# Here is how to authenticate using appId copied from Virtru Dashboard and create client 
# client = Client(owner = "alice@example.com",
#                app_id = "fc877a03-7b0b-4a1f-9b9a-cab94b5d9351")

# create a simple policy and share with bob@example2.com
policy = Policy()
policy.share_with_users(["bob@example2.com"])

# create the encrypt params with simple policy
param = EncryptFileParam(in_file_path="/tmp/sample.docx",
                         out_file_path="/tmp/sample.docx.html")
param.set_policy(policy)

# encrypt the file.
client.encrypt_file(encrypt_file_param=param)

# 'sample.docx.html' is encrypted and protected file. The keys and policy for
# the file have been sync'd with Virtru Key Management Infrastructure. This file
# is ready to be shared via trusted and untrusted channels. Only bob@example2.com # can decrypt this file.
#include <virtru_client.h>
// two authentication methods are supported: 
// (a) HMAC sent by your Virtru Rep (b) AppId Token that you can download from Virtru Dashboard.

// Auth using HMAC and create an instance of Virtru client.
// You can get your org's HMAC token/secret by contacting your Virtru Rep.
Client client {"alice@example.com", // Owner
               "12345678-1234-1234-1234-123456789012@tokens.example.com", // token
               "somesecret="}; // secret

// Here is how to authenticate using appId copied from Virtru Dashboard and create client 
// Client client {"bob@example.com", "12345678-1234-1234-1234-123456789012"};

// Create a simple policy and share with bob@example.com
Policy policy;
policy.shareWithUsers({"bob@example.com"});

// Create the encrypt params with simple policy
EncryptFileParam param {"sample.docx", "sample.docx.html"};
param.setPolicy(policy);

client.encryptFile(param);

// 'sample.docx.html' is encrypted and protected file. The keys and policy for
// the file have been sync'd with Virtru Key Management Infrastructure. This file
// is ready to be shared via trusted and untrusted channels. Only bob@example2.com # can decrypt this file.

File Formats

An encrypted file could be encoded in one of the two ways:

  • A zip file with .tdf extension.
  • A html file with .html extension. This is default behavior for SDKs.

While both provide same protections, there are some key differences when it comes to user experience:

Zip Format
HTML Format

File Sizes

Any file size

For file sizes less than 100 MB. (Some browsers don't handle files larger than this very well)

User Experience with Virtru's Secure Reader

The recipient of the file can drag and drop the file into Secure Reader to decrypt

The recipient of the file can double click on the file to be redirected to Secure Reader to decrypt. This offers better User Experience.

Generating Zip Encoded .tdf Files During Encryption

Virtru SDKs by default generate HTML encoded file. That means, sample.docx file would become sample.docx.html. However, you can also generate Zip encoded files so that sample.docx file would become sample.docx.tdf. The following snippet shows how to generate .tdf files.


// ..
// auth and client generation code goes here
// ..
const encryptParams = new Virtru.EncryptParamsBuilder()
  .withFileSource("/tmp/drivers-license.png")
  .withUsersWithAccess(["bob@example2.com"]) 
  .withZipFormat() // Generate TDF in zip format
  .build();
const stream = await client.encrypt(encryptParams);

// Write the ciphertext in Zip format to a local file with .tdf extension.
await stream.toFile("/tmp/drivers-license.png.tdf");
# ...
# client and auth code goes here.
# ...

# Set protocol to zip
client.set_protocol(Protocol.Zip)

# create the encrypt params with simple policy
param = EncryptFileParam(in_file_path="/tmp/sample.docx",
                         out_file_path="/tmp/sample.docx.html")
param.set_policy(policy)

# encrypt the file.
client.encrypt_file(encrypt_file_param=param)

# This will write the ciphertext in Zip format to a local file with .tdf extension.

// ...
// client and auth code goes here.
// ...

// Create the encrypt params with simple policy
EncryptFileParam param {"sample.docx", "sample.docx.tdf"};
param.setPolicy(policy);

// Set protocol to zip
client.setProtocol(Protocol::Zip);

// encrypt the file.
client.encryptFile(param);

Want to Add Expiration or a Watermark?

Encryption: Full Lifecycle

The Virtru SDK does a lot of things behind the scenes for you to encrypt and protect your data. The following diagram describes the flow:

Protecting a file and sending the policy and key materials to Virtru

Protecting a file and sending the policy and key materials to Virtru

Step 1: First, the client needs an authentication token from Virtru's Entity Attribute Service. See Add Authentication step for more details.

Step 2: Up next, invoking the client.encrypt() encrypts and protects the data into a TDF formatted file. This file stays local to the environment where encryption takes place (browser, end user device or server).

Step 3 and Step 4: The client.encrypt() also pushes the encrypted key material and corresponding policy materials to Virtru Key Management Infrastructure for safe keeping.

How to Encrypt a File


Suggested Edits are limited on API Reference Pages

You can only suggest edits to Markdown body content, but not to the API spec.