Setting up CipherSweet at Run-Time

Select Your Backend

First, you'll need to decide if you have any strict operational requirements for your encryption. This mostly boils down to whether or not you need all encryption to be FIPS 140-2 compliant or not, in which case, you'll need to use the FIPSCrypto backend.

If you aren't sure, the answer is that you probably don't, and feel free to use BoringCrypto instead.

const FIPSCrypto = require('ciphersweet-js').FIPSCrypto;
const BoringCrypto = require('ciphersweet-js').BoringCrypto;

let fips = new FIPSCrypto(); // Use only FIPS 140-2 algorithms
let boring = new BoringCrypto(); // Uses libsodium

Define your Key Provider

After you choose your backend, you'll need a KeyProvider. We provide a few out-of-the-box, but we also provide an interface that can be used to integrate with any key management service in your code.

The simplest example of this is the StringProvider, which accepts a string containing your encryption key:

const StringProvider = require('ciphersweet-js').StringProvider;

let provider = new StringProvider(
    // Example key, chosen randomly, hex-encoded:
    '4e1c44f87b4cdf21808762970b356891db180a9dd9850e7baf2a79ff3ab8a2fc'
);

You can pass a raw binary string, hex-encoded string, or base64url-encoded string to the StringProvider constructor, provided the decoded key is 256 bits.

Attempting to pass a key of an invalid size (i.e. not 256-bit) will result in a CryptoOperationException being thrown. The recommended way to generate a key is:

const sodium = require('sodium-native');
let keyMaterial = Buffer.alloc(32, 0);
sodium.randombytes_buf(keyMaterial);

console.log(keyMaterial.toString('hex'));

Start Your Engines

Once you have these two, you can actually start the engine (CipherSweet). Building on the previous code example:

const {StringProvider, CipherSweet} = require('ciphersweet-js');

let provider = new StringProvider(
    // Example key, chosen randomly, hex-encoded:
    '4e1c44f87b4cdf21808762970b356891db180a9dd9850e7baf2a79ff3ab8a2fc'
);
let engine = new CipherSweet(provider);

If you want to use FIPSCrypto instead of BoringCrypto, you just need to pass it as the second argument of the CipherSweet constructor. The default is BoringCrypto.

Note: In earlier versions of CipherSweet, the default was ModernCrypto.

const {FIPSCrypto, StringProvider, CipherSweet} = require('ciphersweet-js');

let provider = new StringProvider(
    // Example key, chosen randomly, hex-encoded:
    '4e1c44f87b4cdf21808762970b356891db180a9dd9850e7baf2a79ff3ab8a2fc'
);
let engine = new CipherSweet(provider, new FIPSCrypto());

Next: Basic CipherSweet Usage