Skip to content

Instantly share code, notes, and snippets.

@Teepheh-Git
Created August 16, 2023 10:29
Show Gist options
  • Save Teepheh-Git/d285db7da950787d875bd27fc5965cfc to your computer and use it in GitHub Desktop.
Save Teepheh-Git/d285db7da950787d875bd27fc5965cfc to your computer and use it in GitHub Desktop.
import crypto from 'crypto';
export function getAesSecretKey() {
return crypto.randomBytes(16).toString('base64'); // Generate a 128-bit AES secret key (16 bytes) and convert it to Base64
}
export function getDecryptedSecretKey(key, privateKey) {
const privateKeyBuffer = Buffer.from(privateKey, 'base64');
const decryptedKeyBuffer = crypto.privateDecrypt(
privateKeyBuffer,
Buffer.from(key, 'base64'),
);
return decryptedKeyBuffer.toString('base64');
}
export function decryptBodyWithSecretKey(decryptedKey, encryptedTextString) {
const iv = Buffer.from(decryptedKey, 'base64');
const secretKey = Buffer.from(decryptedKey, 'base64');
const decipher = crypto.createDecipheriv('aes-128-cbc', secretKey, iv);
let decryptedBody = decipher.update(encryptedTextString, 'base64', 'utf-8');
decryptedBody += decipher.final('utf-8');
return decryptedBody;
}
export function encryptKey(aesKey, publicKey) {
const publicKeyBuffer = Buffer.from(publicKey, 'base64');
const encryptedKeyBuffer = crypto.publicEncrypt(
publicKeyBuffer,
Buffer.from(aesKey, 'base64'),
);
return encryptedKeyBuffer.toString('base64');
}
export function encryptBody(data, aesKey) {
const iv = crypto.randomBytes(16);
const secretKey = Buffer.from(aesKey, 'base64');
const cipher = crypto.createCipheriv('aes-128-cbc', secretKey, iv);
let encryptedBody = cipher.update(data, 'utf-8', 'base64');
encryptedBody += cipher.final('base64');
return encryptedBody;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment