使用带有十六进制编码的crypto-js密码字符串,使其对网址友好

时间:2017-06-23 06:36:35

标签: javascript encryption cryptojs

我在brix使用public class MedicineList implements Parcelable { @SerializedName("medicineList") private List<Medicine > medicine; // Getter setter can go here } 。我在下面有这个函数来处理纯文本的加密。

crypto-js

如何让enc(字符串)返回一个友好的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(); } 值?

1 个答案:

答案 0 :(得分:3)

您可能想要这样做:

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];
}

这会使用加密的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;
}

这需要加密的base64字符串并使其成为十六进制,它也会解密它。