[英]Cipher a string using crypto-js with hex encoding to make it url friendly
I am using crypto-js
by brix . 我使用的
crypto-js
的糖度 。 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? 如何让我的ENC(串)返回一个
Hex
值,它是URL友好吗?
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
. 这将获取加密的
base64
字符串,并将返回解密的纯文本和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. 最终结果采用
base64
字符串,使其成为hexadecimal
并返回解密的字符串。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.