I am using crypto-js
by brix. I have this function below that handles the encryption of a plain text.
import CryptoJS from 'crypto-js'
import AES from 'crypto-js/aes'
const SECRET = 'I am batman'
const plainText = 'This is Sparta!'
export function enc(plainText){
// returns something like this U2FsdGVkX184He5Rp991JYAiCSdTwfZs8T3kJUk3zAc=
// but with random `/` and I dont want that
// I want it to be Hex but .toString(CryptoJs.enc.Hex)
// is not working, it just returns an '' empty string
// it's a string, I checked using typeof
return AES.encrypt(plainText, SECRET).toString();
}
How do I make the enc(string) to return a Hex
value which is url friendly?
CryptoJS is a growing collection of standard and secure cryptographic algorithms implemented in JavaScript using best practices and patterns. They are fast, and they have a consistent and simple interface.
Crypto is a module in Node. js which deals with an algorithm that performs data encryption and decryption. This is used for security purpose like user authentication where storing the password in Database in the encrypted form. Crypto module provides set of classes like hash, HMAC, cipher, decipher, sign, and verify.
crypto is built into Node. js, so it doesn't require rigorous implementation process and configurations. Unlike other modules, you don't need to install Crypto before you use it in your Node. js application.
You would likely want to do:
export function dec(cipherText){
var bytes = CryptoJS.AES.decrypt(cipherText, SECRET);
var hex = bytes.toString(CryptoJS.enc.Hex);
var plain = bytes.toString(CryptoJS.enc.Utf8);
return [hex, plain];
}
This takes the encrypted base64
string and will return the decrypted plaintext and hexadecimal
.
EDIT: In regards to your comment and edited question:
const SECRET = 'I am batman'
function enc(plainText){
var b64 = CryptoJS.AES.encrypt(plainText, SECRET).toString();
var e64 = CryptoJS.enc.Base64.parse(b64);
var eHex = e64.toString(CryptoJS.enc.Hex);
return eHex;
}
function dec(cipherText){
var reb64 = CryptoJS.enc.Hex.parse(cipherText);
var bytes = reb64.toString(CryptoJS.enc.Base64);
var decrypt = CryptoJS.AES.decrypt(bytes, SECRET);
var plain = decrypt.toString(CryptoJS.enc.Utf8);
return plain;
}
The end result takes the base64
string, makes it hexadecimal
and returns the decrypted string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With