Function: decryptByKey()
decryptByKey(
encrypted,keys):Buffer
Decrypt data encrypted by encryptByKey (or Crypt.encrypt) with one of the keys, tried in order: list the current key and the previous ones during a key rotation. The authentication tag is checked before anything is returned, so changed data is never decrypted.
Parameters
encrypted
string
The encrypted data, base64url as encryptByKey returns it.
keys
string | Uint8Array<ArrayBufferLike> | (string | Uint8Array<ArrayBufferLike>)[]
The key, or the keys to try: strings (used as their UTF-8 bytes) or bytes, none empty.
Returns
Buffer
The decrypted bytes (call .toString('utf8') for a string).
Throws
When no key decrypts the data, or it was changed, truncated or not produced by encryptByKey (data encrypted by encryptByPassword included).
Throws
When a key is empty.
Example
typescript
import {decryptByKey, DecryptionFailedException} from 'lakutata/security'
declare const encrypted: string
declare const currentKey: string
declare const previousKey: string
try {
//The new key first, the previous one while old data remains
const secret: string = decryptByKey(encrypted, [currentKey, previousKey]).toString('utf8')
console.log(secret)
} catch (error) {
if (error instanceof DecryptionFailedException) console.log('Changed, or encrypted with an unknown key')
}