使用带有十六进制编码的crypto-js加密字符串以使其对URL友好

CEN*_*EDE 3 javascript encryption cryptojs

我使用crypto-js糖度。我在下面有处理纯文本加密的功能。

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();
}
Run Code Online (Sandbox Code Playgroud)

我如何使enc(string)返回一个HexURL友好的值?

l'L*_*L'l 6

您可能想做:

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];
}
Run Code Online (Sandbox Code Playgroud)

这将获取加密的base64字符串,并将返回解密的明文和hexadecimal

编辑:关于您的评论和编辑的问题:

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;
}
Run Code Online (Sandbox Code Playgroud)

最终结果将base64字符串取回,hexadecimal并返回解密后的字符串。