mirror of
https://github.com/formbricks/formbricks.git
synced 2026-04-21 03:03:25 -05:00
66408fdccc
Co-authored-by: Matthias Nannt <mail@matthiasnannt.com>
61 lines
2.2 KiB
TypeScript
61 lines
2.2 KiB
TypeScript
import crypto from "crypto";
|
|
import { createHash, createCipheriv, createDecipheriv } from "crypto";
|
|
|
|
const ALGORITHM = "aes256";
|
|
const INPUT_ENCODING = "utf8";
|
|
const OUTPUT_ENCODING = "hex";
|
|
const IV_LENGTH = 16; // AES blocksize
|
|
|
|
/**
|
|
*
|
|
* @param text Value to be encrypted
|
|
* @param key Key used to encrypt value must be 32 bytes for AES256 encryption algorithm
|
|
*
|
|
* @returns Encrypted value using key
|
|
*/
|
|
export const symmetricEncrypt = function (text: string, key: string) {
|
|
const _key = Buffer.from(key, "latin1");
|
|
const iv = crypto.randomBytes(IV_LENGTH);
|
|
|
|
const cipher = crypto.createCipheriv(ALGORITHM, _key, iv);
|
|
let ciphered = cipher.update(text, INPUT_ENCODING, OUTPUT_ENCODING);
|
|
ciphered += cipher.final(OUTPUT_ENCODING);
|
|
const ciphertext = iv.toString(OUTPUT_ENCODING) + ":" + ciphered;
|
|
|
|
return ciphertext;
|
|
};
|
|
|
|
/**
|
|
*
|
|
* @param text Value to decrypt
|
|
* @param key Key used to decrypt value must be 32 bytes for AES256 encryption algorithm
|
|
*/
|
|
export const symmetricDecrypt = function (text: string, key: string) {
|
|
const _key = Buffer.from(key, "latin1");
|
|
|
|
const components = text.split(":");
|
|
const iv_from_ciphertext = Buffer.from(components.shift() || "", OUTPUT_ENCODING);
|
|
const decipher = crypto.createDecipheriv(ALGORITHM, _key, iv_from_ciphertext);
|
|
let deciphered = decipher.update(components.join(":"), OUTPUT_ENCODING, INPUT_ENCODING);
|
|
deciphered += decipher.final(INPUT_ENCODING);
|
|
|
|
return deciphered;
|
|
};
|
|
|
|
export const getHash = (key: string): string => createHash("sha256").update(key).digest("hex");
|
|
|
|
// create an aes128 encryption function
|
|
export const encryptAES128 = (encryptionKey: string, data: string): string => {
|
|
const cipher = createCipheriv("aes-128-ecb", Buffer.from(encryptionKey, "base64"), "");
|
|
let encrypted = cipher.update(data, "utf-8", "hex");
|
|
encrypted += cipher.final("hex");
|
|
return encrypted;
|
|
};
|
|
// create an aes128 decryption function
|
|
export const decryptAES128 = (encryptionKey: string, data: string): string => {
|
|
const cipher = createDecipheriv("aes-128-ecb", Buffer.from(encryptionKey, "base64"), "");
|
|
let decrypted = cipher.update(data, "hex", "utf-8");
|
|
decrypted += cipher.final("utf-8");
|
|
return decrypted;
|
|
};
|