Skip to content

Instantly share code, notes, and snippets.

@pipethedev
Last active June 11, 2022 11:34
Show Gist options
  • Save pipethedev/176f6e46d4052cc346458edd8c857907 to your computer and use it in GitHub Desktop.
Save pipethedev/176f6e46d4052cc346458edd8c857907 to your computer and use it in GitHub Desktop.
Node js laravel like encryption
import CryptoJS from "crypto-js";
class LaravelEncrypt{
public key: string;
constructor(key: string){
this.key = key;
}
public encrypt(data: string): string{
let iv : any = CryptoJS.lib.WordArray.random(16),
key = CryptoJS.enc.Base64.parse(this.key);
let options = {
iv: iv,
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7
};
let encrypted: any = CryptoJS.AES.encrypt(data, key, options);
encrypted = encrypted.toString();
iv = CryptoJS.enc.Base64.stringify(iv);
let result : any = {
iv: iv,
value: encrypted,
mac: CryptoJS.HmacSHA256(iv + encrypted, key).toString()
}
result = JSON.stringify(result);
result = CryptoJS.enc.Utf8.parse(result);
return CryptoJS.enc.Base64.stringify(result);
}
}
export default LaravelEncrypt;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment