Dav*_*ham 5 javascript encryption aes ecb cryptojs
目标:使用 AES-128、ECB、0 填充进行加密和解密的简单CryptoJS 示例。
请参阅下面我的可运行示例。
输入文本是“US0378331005-USD-US-en”,它被加密(希望 AES-128 包含上述所有内容),然后解密(这不起作用)
text: US0378331005-USD-US-en
key: 11A1764225B11AA1
key length: 16
encrypted 951422f8ac8354acf23fbc
decrypted a5126fa0fc3cb4c39a4f3e637be98a73
Run Code Online (Sandbox Code Playgroud)
text: US0378331005-USD-US-en
key: 11A1764225B11AA1
key length: 16
encrypted 951422f8ac8354acf23fbc
decrypted a5126fa0fc3cb4c39a4f3e637be98a73
Run Code Online (Sandbox Code Playgroud)
var text = 'US0378331005-USD-US-en';
var key = '11A1764225B11AA1'; // to ensure AES-128 this has to be 16 bit
console.log('text:', text);
console.log('key:', key);
console.log('key length:', key.length );
text = CryptoJS.enc.Hex.parse(text);
key = CryptoJS.enc.Hex.parse(key);
var iv = CryptoJS.enc.Hex.parse("00000000000000000000000000000000");
var encrypted = CryptoJS.AES.encrypt(text, key, { iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding });
encrypted = encrypted.ciphertext.toString(CryptoJS.enc.Hex);
console.log('encrypted', encrypted);
var decrypted = CryptoJS.AES.decrypt(encrypted, key, {iv: iv, mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding });
console.log('decrypted', decrypted.toString() );Run Code Online (Sandbox Code Playgroud)
您的代码中有几个错误:
CryptoJS.pad.ZeroPadding。请注意,PKCS#7 填充(默认)更可靠。CryptoJS.AES.decrypt()需要一个CipherParams对象,但在当前代码中传递的是十六进制编码的密文。CipherParams从十六进制编码的密文创建一个对象并传递它,或者传递 Base64 编码的密文,CryptoJS 将其隐式转换为对象CipherParams。固定代码:
var text = 'US0378331005-USD-US-en';
var key = '11A1764225B11AA1';
console.log('text:', text);
console.log('key:', key);
console.log('key length:', key.length );
// Fix: Use the Utf8 encoder
text = CryptoJS.enc.Utf8.parse(text);
// Fix: Use the Utf8 encoder (or apply in combination with the hex encoder a 32 hex digit key for AES-128)
key = CryptoJS.enc.Utf8.parse(key);
// Fix: Apply padding (e.g. Zero padding). Note that PKCS#7 padding is more reliable and that ECB is insecure
var encrypted = CryptoJS.AES.encrypt(text, key, { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.ZeroPadding });
encrypted = encrypted.ciphertext.toString(CryptoJS.enc.Hex);
console.log('encrypted', encrypted);
// Fix: Pass a CipherParams object (or the Base64 encoded ciphertext)
var decrypted = CryptoJS.AES.decrypt({ciphertext: CryptoJS.enc.Hex.parse(encrypted)}, key, {mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.ZeroPadding });
// Fix: Utf8 decode the decrypted data
console.log('decrypted', decrypted.toString(CryptoJS.enc.Utf8)); Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/crypto-js/4.1.1/crypto-js.min.js"></script>Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
14283 次 |
| 最近记录: |