24 lines
881 B
TypeScript
24 lines
881 B
TypeScript
import CryptoJS from 'crypto-js'
|
|
|
|
const encryptionPrefix = 'contexted|'
|
|
const salt = 'salt'
|
|
|
|
export const calculateClientKey = (passphrase: string): ClientKey => {
|
|
return CryptoJS.PBKDF2(passphrase, salt, { keySize: 256 / 32 }).toString()
|
|
}
|
|
|
|
export const decrypt = (encryptedMessage: string, key: string): string => {
|
|
const decryptedMessage = CryptoJS.AES.decrypt(encryptedMessage, key).toString(CryptoJS.enc.Utf8)
|
|
if (!decryptedMessage.startsWith(encryptionPrefix))
|
|
throw new Error("Message doesn't have valid encryption")
|
|
return decryptedMessage.substring(encryptionPrefix.length)
|
|
}
|
|
|
|
export const encrypt = (unencryptedMessage: string, key: string): string => {
|
|
return CryptoJS.AES.encrypt(encryptionPrefix + unencryptedMessage, key).toString()
|
|
}
|
|
|
|
export const generateEncryptionKey = () => {
|
|
return CryptoJS.lib.WordArray.random(16).toString(CryptoJS.enc.Hex)
|
|
}
|