本文介绍了使用带有十六进制编码的crypto-js加密字符串以使其对URL友好的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 brix crypto-js / a>。我下面有处理纯文本加密的函数。

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();
}

如何使enc(string)返回十六进制值是否适合网址?

How do I make the enc(string) to return a Hex value which is url friendly?

推荐答案

您可能想这样做:

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 字符串,并返回解密的纯文本和十六进制

This takes the encrypted base64 string and will return the decrypted plaintext and hexadecimal.

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

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

最终结果采用 base64 字符串,使其为十六进制,并返回解密后的字符串。

The end result takes the base64 string, makes it hexadecimal and returns the decrypted string.

这篇关于使用带有十六进制编码的crypto-js加密字符串以使其对URL友好的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!