Package detail

@digitalbazaar/minimal-cipher

digitalbazaar2.1kBSD-3-Clause6.0.0

Minimal encryption/decryption JWE library.

cipher, encryption, decryption, jwe

readme

Minimal Cipher (@digitalbazaar/minimal-cipher)

Minimal encryption/decryption JWE library, secure algs only, browser-compatible.

Table of Contents

Security

TBD

Background

Every version of this library will only offer at most two algorithms for encryption/decryption: a recommended algorithm and a FIPS-compliant algorithm. The encryption API will expect the user to specify "recommended" or "fips" as the version of the algorithm to use, defaulting to "recommended".

In the event that the FIPS-compliant algorithm is the same as the recommended one in a given version of this library, then that particular version will use the same algorithm regardless of the user specified "version".

This version of the library will use "XChaCha20-Poly1305" as the "recommended" version and 256-bit "AES-GCM" as the FIPS-compliant version.

Note: XSalsa20-Poly1305 is an AE (Authenticated Encryption) algorithm, not an AEAD (Authenticated Encryption and Associated Data) algorithm, making it incompatible with the current requirements for a JWE (JOSE Web Encryption) protected clear text header.

This library's API requires an interface for Key Encryption Key (KEKs). This enables key material that is protected from exfiltration to be used via HSM/SSM APIs, including Web KMS (TODO: citation needed).

Install

  • Node.js 14+ required.
  • Streams API required. Older browsers and Node.js <18 must use a polyfill.
  • Web Crypto API required. Older browsers and Node.js 14 must use a polyfill.

To install locally (for development):

git clone https://github.com/digitalbazaar/minimal-cipher.git
cd minimal-cipher
npm install

Usage

Pick a Cipher interface (recommended or fips) and create an instance:

import {Cipher} from '@digitalbazaar/minimal-cipher';

const cipher = new Cipher(); // by default {version: 'recommended'}

Encrypting

To encrypt something (to create a cipher, serialized as a JWE JSON document), you will need:

  • Some data to encrypt (a string, an object, a stream)
  • Keys (called Key Agreement Keys, or KAKs for short)

(You'll also need a keyResolver, more about that later.)

First, assemble your Key Agreement public keys (you'll be encrypting with them, and the intended recipient will use the corresponding private keys to decrypt).

Put together a list of recipients (essentially, you're listing the ids of public/private key pairs that will be used to encrypt/decrypt the message):

// Retrieve them from config, a ledger, registry or back channel
const keyAgreementKey = await fetchFromSomewhere();

// or derive them from an existing Ed25519 signing key
import {X25519KeyAgreementKey2020} from '@digitalbazaar/x25519-key-agreement-key-2020';
import {Ed25519VerificationKey2020} from '@digitalbazaar/ed25519-verification-key-2020';
const keyPair = await Ed25519VerificationKey2020.generate();

const keyAgreementKey = X25519KeyPair.fromEd25519VerificationKey2020({keyPair});
// If the source key pair didn't have a controller set, don't forget to set one:
keyAgreementKey.controller = did; // The controller's DID
keyAgreementKey.id = `${did}#${keyAgreementKey.fingerprint()}`;

// or derive them from an authentication key extracted from DID Document
const didDoc = await veresDriver.get({did});
const authnKey = didDoc.getVerificationMethod({proofPurpose: 'authentication'});
const edKeyPair = await Ed25519VerificationKey2020.from(authnKey);
const keyPair = X25519KeyPair.fromEd25519VerificationKey2020({keyPair});

const recipient = {
  header: {
    kid: keyAgreementKey.id,
    alg: 'ECDH-ES+A256KW'
  }
}

const recipients = [recipient];

You'll also need a keyResolver. Notice that recipients lists only key IDs, not the keys themselves. A keyResolver is a function that accepts a key ID and resolves to the public key corresponding to it.

Some example resolvers:

// Basic hardcoded key resolver; you already have the key material
const publicKeyNode = {
  '@context': 'https://w3id.org/security/suites/x25519-2020/v1',
  id: keyAgreementKey.id,
  type: 'X25519KeyAgreementKey2020',
  publicKeyMultibase: keyAgreementKey.publicKeyMultibase
};
const keyResolver = async () => publicKeyNode;
// A more advanced resolver based on DID doc authentication keys
const keyResolver = async ({id}) => {
  // Use veres driver to fetch the authn key directly
  const keyPair = await Ed25519VerificationKey2020.from(await veresDriver.get({did: id}));
  // Convert authn key to key agreement key
  return X25519KeyPair.fromEd25519VerificationKey2020({keyPair});
}
// Using did-veres-one driver as a resolver for did:v1:nym: DID keys
// TODO: Implement this
// Using the did:key method driver as a key resolver

Create the JWE:

// To encrypt a string or a Uint8Array
const data = 'plain text';
const jweDoc = await cipher.encrypt({data, recipients, keyResolver});

// To encrypt an object
const obj = {key: 'value'};
const jweDoc = await cipher.encryptObject({obj, recipients, keyResolver});

Decrypting

Decrypt a JWE JSON Document, using a private keyAgreementKey:

const data = await cipher.decrypt({jwe, keyAgreementKey});

const object = await cipher.decryptObject({jwe, keyAgreementKey});

TODO: Describe the required KEK API: // id, algorithm, wrapKey({unwrappedKey}), and unwrapKey({wrappedKey})

Contribute

See the contribute file!

PRs accepted.

If editing the README, please conform to the standard-readme specification.

Commercial Support

Commercial support for this library is available upon request from Digital Bazaar: support@digitalbazaar.com

License

New BSD License (3-clause) © Digital Bazaar

changelog

minimal-cipher ChangeLog

6.0.0 - 2023-11-05

Changed

  • BREAKING: Require node >= 18.
  • BREAKING: Use P-256 curve elliptic keys for key agreement instead of X25519 when using the fips-compliant version.
  • Use @noble/curves to provide X25519 implementation. This lib is often used in other libs that are combined with this one and it has been through a comprehensive security audit. Additional benefits include speed and tree-shaking capabilities.

5.1.1 - 2022-08-14

Fixed

  • Fix chacha bug.

5.1.0 - 2022-07-31

Added

  • Use platform-specific native APIs where possible to implement ChaCha20-Poly1305 and XChaCha20-Poly1305.

5.0.0 - 2022-06-06

Changed

  • BREAKING: Convert to module (ESM).
  • BREAKING: Require Node.js >=14.
  • BREAKING: Use globalThis for browser crypto and streams.
  • BREAKING: Require Web Crypto API. Older browsers and Node.js 14 users need to install an appropriate polyfill.
  • BREAKING: Require Streams API. Older browsers and Node.js <18 users need to install an appropriate polyfill.
  • Update dependencies.
  • Lint module.

4.0.2 - 2021-09-17

Fixed

  • Fix parameters passed to key wrap/unwrapping functions in aeskw.js. The key usage param for the key to be wrapped/unwrapped was inconsistent and not accepted on certain browsers (Firefox). A previous commit conflated the key usage field for the key to be wrapped with the key wrapping key itself and this has been corrected and commented to help avoid future problems.

4.0.1 - 2021-08-18

Fixed

  • Pin web-streams-polyfill@3.0.x. This has been done because version 3.1+ of the polyfill have added checks to force the same version of the polyfill to be used across all code that uses the ReadableStream API. This means that the polyfill does not just polyfill an interface such that it is compatible with other libraries; those libraries must all know about each other and use the exact same implementation. Hopefully, this will be fixed in a later version of the polyfill.

4.0.0 - 2021-07-22

Changed

  • BREAKING: Upgrade to @digitalbazaar/x25519-verification-key-2020 v2.0, which changes the key serialization format to multicodec (in addition to multibase).

3.0.0 - 2021-04-01

Changed

  • BREAKING: Update KEY_TYPE to X25519KeyAgreementKey2020.

2.0.0 - 2021-03-12

Changed

Purpose and Upgrade Instructions

There no API changes to minimal-cipher itself (aside from the rename of its npm package to @digitalbazaar/minimal-cipher), so upgrading from 1.4.x to 2.0.0 only involves making sure that the keys being used for key agreement are generated using the newer crypto-ld v4 method (see minimal-cipher README for examples).

1.4.1 - 2021-03-11

Changed

  • JSDOC comments in Cipher.js.
  • Upgraded eslint to ^7.0.0.
  • Upgraded eslint-plugin-jsdoc to ^37.0.0.
  • Refactored creating recipients.

Fixed

  • decrypt helper function in test suite to be able to handle multiple chunks.

Added

  • new helper function createUnencryptedStream in test suite.
  • better jsdoc comments to help clarify test suite functions.
  • chunkSize tests for decrypt.

1.4.0 - 2020-08-20

Changed

  • Use Node.js crypto.diffieHellman for computing DH secret when available.

1.3.0 - 2020-03-18

Added

  • Add validation of parameters in DecryptTransformer constructor.

1.2.0 - 2020-01-28

Changed

  • Update dependencies.
  • Use base58-universal.

1.1.0 - 2019-12-17

Added

  • Use XChaCha20Poly1305 (instead of ChaCha20Poly1305) for the recommended encryption algorithm. Backwards compatibility support for decrypting ChaCha20Poly1305 is provided, but encryption will now only use XChaCha20Poly1305.

1.0.1 - 2019-08-02

Fixed

  • Ensure exported key is wrapped in a Uint8Array.

1.0.0 - 2019-08-02

0.1.0 - 2019-08-02

Added

  • Add core files.

  • See git history for changes previous to this release.