[英]Cipher a string using crypto-js with hex encoding to make it url friendly
我使用的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();
}
如何讓我的ENC(串)返回一個Hex
值,它是URL友好嗎?
你可能想做:
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
字符串,使其成為hexadecimal
並返回解密的字符串。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.