Crypto

The Crypto object provides utility methods for generating encryption keys and constructing CipherParams for use with encrypted channels. Access it via the Crypto property of a Rest client instance.

JavaScript

1

const crypto = Ably.Rest.Crypto;

Get default cipher params

Crypto.getDefaultParams(params: CipherParamOptions): CipherParams

Obtains a CipherParams object using the values passed in (which must be a subset of CipherParams fields that at a minimum includes a key), filling in any unspecified fields with default values, and checks that the result is valid and self-consistent.

You will rarely need to call this yourself, since the SDK will handle it for you if you specify cipher params when obtaining a channel (as in the getting started example).

JavaScript

1

2

3

const cipherParams = Ably.Rest.Crypto.getDefaultParams({ key: '<key>' });
const channelOpts = { cipher: cipherParams };
const channel = rest.channels.get('all-gas-ion', channelOpts);

Parameters

The Crypto.getDefaultParams() method takes the following parameters:

paramsrequiredCipherParamOptions
The cipher params that you want to specify. It must at a minimum include a key, which should be either binary (ArrayBuffer or Uint8Array) or a base64-encoded String.

Returns

CipherParams

Returns a complete CipherParams object. Throws an exception if the params are invalid or inconsistent.

keyunknown
The private key used for encryption and decryption. Do not set this value directly; pass a key to getDefaultParams() instead.
algorithmString
The name of the algorithm in the default system provider, or the lower-cased version of it; for example aes or AES. Default: AES.
keyLengthNumber
The key length in bits of the cipher. Either 128 or 256. Default: 256.
modeString
The cipher mode. Default: CBC.

Generate a random key

Crypto.generateRandomKey(keyLength?: number): Promise<CipherKey>

Generates a randomly-generated binary key of the specified key length. The returned key can be used directly as the key field of a CipherParams object or in a channel's cipher options.

You will rarely need to call this yourself, since the SDK will handle key generation for you when encryption is configured on a channel.

JavaScript

1

2

const key = await Ably.Rest.Crypto.generateRandomKey(256);
const channel = rest.channels.get('all-gas-ion', { cipher: { key } });

Parameters

The Crypto.generateRandomKey() method takes the following parameters:

keyLengthoptionalNumber
The length of key to generate, in bits. For AES this should be either 128 or 256. Default: 256.

Returns

Promise<CipherKey>

Returns a promise. The promise is fulfilled with the generated binary key (an ArrayBuffer in the browser, a Buffer in Node.js), or rejected with an ErrorInfo object.