cal/lib/crypto.ts
Femi Odugbesan 65366b7c5b
cal-101-caldav-integration (#419)
* add generic calendar icon for caldav

* module for symmetric encrypt/decrypt

* caldav integration

* use Radix dialog

* Move caldav components to /caldav

* remove duplicate cancel button, unused function

* ensure app can connect to caldav server before adding

* fix calendar clients can possibly return null

* fix: add caldav dialog does not close when submitted

* safely attempt all caldav operations

* clarify variable name, fix typo

* use common helper for stripping html

* remove usage of request lib until "completed"

* add types and usage comments to crypto lib

* add encryption key to example env file
2021-08-14 20:53:59 -05:00

43 lines
1.3 KiB
TypeScript

import crypto 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;
};