Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export async function encrypt (
cmm: KeyringWebCrypto|WebCryptoMaterialsManager,
plaintext: Uint8Array,
{ suiteId, encryptionContext = {}, frameLength = FRAME_LENGTH }: EncryptInput = {}
): Promise {
/* Precondition: The frameLength must be less than the maximum frame size for browser encryption. */
needs(frameLength > 0 && Maximum.FRAME_SIZE >= frameLength, `frameLength out of bounds: 0 > frameLength >= ${Maximum.FRAME_SIZE}`)
const backend = await getWebCryptoBackend()
if (!backend) throw new Error('No supported crypto backend')
/* If the cmm is a Keyring, wrap it with WebCryptoDefaultCryptographicMaterialsManager. */
cmm = cmm instanceof KeyringWebCrypto
? new WebCryptoDefaultCryptographicMaterialsManager(cmm)
: cmm
// Subtle Crypto functions are all one-shot so all the plaintext needs to be available.
const plaintextLength = plaintext.byteLength
const suite = suiteId ? new WebCryptoAlgorithmSuite(suiteId) : new WebCryptoAlgorithmSuite(AlgorithmSuiteIdentifier.ALG_AES256_GCM_IV12_TAG16_HKDF_SHA384_ECDSA_P384)
const encryptionRequest: WebCryptoEncryptionRequest = {
suite,
encryptionContext,
export function encryptStream (
cmm: KeyringNode|NodeMaterialsManager,
op: EncryptStreamInput = {}
): Duplex {
const { suiteId, encryptionContext = {}, frameLength = FRAME_LENGTH, plaintextLength } = op
/* Precondition: The frameLength must be less than the maximum frame size Node.js stream. */
needs(frameLength > 0 && Maximum.FRAME_SIZE >= frameLength, `frameLength out of bounds: 0 > frameLength >= ${Maximum.FRAME_SIZE}`)
/* If the cmm is a Keyring, wrap it with NodeDefaultCryptographicMaterialsManager. */
cmm = cmm instanceof KeyringNode
? new NodeDefaultCryptographicMaterialsManager(cmm)
: cmm
const suite = suiteId && new NodeAlgorithmSuite(suiteId)
const wrappingStream = new Duplexify()
cmm.getEncryptionMaterials({ suite, encryptionContext, plaintextLength })
.then(async (material) => {
const { dispose, getSigner } = getEncryptHelper(material)
const { getCipher, messageHeader, rawHeader } = getEncryptionInfo(material, frameLength)