Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
export function vaultFromHexString(organizationVaultSecret: string, dataHexString: string): Vault {
// The nonce/salt is prepended to the actual ciphertext:
const dataBuffer = Buffer.from(dataHexString, "hex");
const nonceBuffer = dataBuffer.slice(0, sodium.crypto_secretbox_NONCEBYTES);
const cipherBuffer = dataBuffer.slice(sodium.crypto_secretbox_NONCEBYTES);
const keyBuffer = toKeyBuffer(organizationVaultSecret);
const plaintextBuffer = Buffer.alloc(cipherBuffer.length - sodium.crypto_secretbox_MACBYTES);
if (!sodium.crypto_secretbox_open_easy(plaintextBuffer, cipherBuffer, nonceBuffer, keyBuffer)) {
throw Error("Vault decryption failed!");
}
const vaultString = plaintextBuffer.toString();
const vault: Vault = JSON.parse(vaultString);
return vault;
}
export function decrypt(
organizationSecret: string,
hexEncodedCiphertext: string,
): Result.Type {
// The nonce/salt is prepended to the actual ciphertext:
const dataBuffer = Buffer.from(hexEncodedCiphertext, "hex");
const nonceBuffer = dataBuffer.slice(0, sodium.crypto_secretbox_NONCEBYTES);
const cipherBuffer = dataBuffer.slice(sodium.crypto_secretbox_NONCEBYTES);
const keyBuffer = toKeyBuffer(organizationSecret);
const plaintextBuffer = Buffer.alloc(cipherBuffer.length - sodium.crypto_secretbox_MACBYTES);
if (!sodium.crypto_secretbox_open_easy(plaintextBuffer, cipherBuffer, nonceBuffer, keyBuffer)) {
return new DecryptionFailed();
}
return plaintextBuffer.toString();
}
next()
return
}
const cipher = Buffer.from(cyphertextB64, 'base64')
const nonce = Buffer.from(nonceB64, 'base64')
if (cipher.length < sodium.crypto_secretbox_MACBYTES) {
// not long enough
request.session = new Session({})
next()
return
}
const msg = Buffer.allocUnsafe(cipher.length - sodium.crypto_secretbox_MACBYTES)
if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, key)) {
// unable to decrypt
request.session = new Session({})
next()
return
}
request.session = new Session(JSON.parse(msg))
next()
})
exports.decrypt = function (cipher, nonce, key) {
if (cipher.length < sodium.crypto_secretbox_MACBYTES) return null
var msg = Buffer.alloc(cipher.length - sodium.crypto_secretbox_MACBYTES)
if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, key)) return null
return msg
}
exports.decrypt = function (cipher, nonce, key) {
if (cipher.length < sodium.crypto_secretbox_MACBYTES) return null
var msg = new Buffer(cipher.length - sodium.crypto_secretbox_MACBYTES)
if (!sodium.crypto_secretbox_open_easy(msg, cipher, nonce, key)) return null
return msg
}