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 (
data: IJsonRpcRequest | IJsonRpcResponseSuccess | IJsonRpcResponseError,
key: ArrayBuffer
): Promise {
const _key: Buffer = convertArrayBufferToBuffer(key)
const ivArrayBuffer: ArrayBuffer = await generateKey(128)
const iv: Buffer = convertArrayBufferToBuffer(ivArrayBuffer)
const ivHex: string = convertBufferToHex(iv, true)
const contentString: string = JSON.stringify(data)
const content: Buffer = convertUtf8ToBuffer(contentString)
const cipherText: Buffer = await aesCbcEncrypt(content, _key, iv)
const cipherTextHex: string = convertBufferToHex(cipherText, true)
const unsigned: Buffer = concatBuffers(cipherText, iv)
const hmac: Buffer = await createHmac(unsigned, _key)
const hmacHex: string = convertBufferToHex(hmac, true)
return {
export async function encrypt (
data: IJsonRpcRequest | IJsonRpcResponseSuccess | IJsonRpcResponseError,
key: ArrayBuffer
): Promise {
const _key: Buffer = convertArrayBufferToBuffer(key)
const ivArrayBuffer: ArrayBuffer = await generateKey(128)
const iv: Buffer = convertArrayBufferToBuffer(ivArrayBuffer)
const ivHex: string = convertBufferToHex(iv, true)
const contentString: string = JSON.stringify(data)
const content: Buffer = convertUtf8ToBuffer(contentString)
const cipherText: Buffer = await aesCbcEncrypt(content, _key, iv)
const cipherTextHex: string = convertBufferToHex(cipherText, true)
const unsigned: Buffer = concatBuffers(cipherText, iv)
const hmac: Buffer = await createHmac(unsigned, _key)
const hmacHex: string = convertBufferToHex(hmac, true)
return {
data: cipherTextHex,
hmac: hmacHex,
iv: ivHex
export async function decrypt (
payload: IEncryptionPayload,
key: ArrayBuffer
): Promise<
IJsonRpcRequest | IJsonRpcResponseSuccess | IJsonRpcResponseError | null
> {
const _key: Buffer = convertArrayBufferToBuffer(key)
if (!_key) {
throw new Error('Missing key: required for decryption')
}
const verified: boolean = await verifyHmac(payload, _key)
if (!verified) {
return null
}
const cipherText: Buffer = convertHexToBuffer(payload.data)
const iv: Buffer = convertHexToBuffer(payload.iv)
const buffer: Buffer = await aesCbcDecrypt(cipherText, _key, iv)
const utf8: string = convertBufferToUtf8(buffer)
let data: IJsonRpcRequest
try {