Skip to content

Function: encryptByKey() ​

encryptByKey(data, key): string

Encrypt data with a secret key, using AES-256-GCM (authenticated encryption): the output is confidential and tamper-proof. Each call derives a fresh key from the key and a random 16-byte salt (HKDF-sha256) and uses a random 12-byte IV, so encrypting the same data twice gives different outputs. The Crypt provider does the same with configured keys and key rotation.

The key must be random (see generateSecret): its derivation is fast, so a password used as a key is open to brute force; use encryptByPassword for passwords. The function refuses an empty key, but does not check the key's length or strength otherwise.

Parameters ​

data ​

string | Uint8Array<ArrayBufferLike>

The data to encrypt: a string (encrypted as its UTF-8 bytes) or bytes.

key ​

string | Uint8Array<ArrayBufferLike>

The secret key: a string (used as its UTF-8 bytes, not decoded from base64) or bytes, not empty; 32 random bytes recommended.

Returns ​

string

The encrypted data, base64url encoded without padding: 1 version byte, the salt, the IV, a 16-byte authentication tag and the ciphertext (45 bytes more than the data, before base64url).

Throws ​

When the key is empty.

Example ​

typescript
import {decryptByKey, encryptByKey, generateSecret} from 'lakutata/security'

const key: string = process.env.CRYPT_KEY ?? generateSecret()
const encrypted: string = encryptByKey('card ending 4242', key)
console.log(decryptByKey(encrypted, key).toString('utf8'))

Released under the MIT License.