import { compactDecrypt, CompactEncrypt } from 'jose';
import { uuidv4 } from 'lib0/random';
const encrypt = async (target: object, securityKey: string) => {
// securityKey is a 64 character Hexadecimal string, change it to a byte array
const key = Buffer.from(securityKey, 'hex');
const keyInUint8Array = new Uint8Array(key);
const payload = JSON.stringify(target);
const payloadAsUint8Array = new TextEncoder().encode(payload);
const encryption = new CompactEncrypt(payloadAsUint8Array);
const encrypted = await encryption
.setProtectedHeader({
alg: 'dir',
enc: 'A256GCM',
iat: new Date().toISOString(),
nonce: uuidv4(),
})
.encrypt(keyInUint8Array);
return encrypted;
};
const decrypt = async (encrypted: string, securityKey: string) => {
const key = Buffer.from(securityKey, 'hex');
const keyInUint8Array = new Uint8Array(key);
const decryption = await compactDecrypt(encrypted, keyInUint8Array);
const plainTextInUint8Array = decryption.plaintext;
// decode the plain text from Uint8Array to string in utf-8
const plainText = new TextDecoder().decode(plainTextInUint8Array);
return JSON.parse(plainText) as object;
};
export { encrypt, decrypt };