2015-11-07 61 views
1

我想学习的JavaScript和我正在学习一个教程,我想我输入正确的一切,但由于某种原因我使用cypto-js库加密的字符串不能未加密正确。我没有收到错误,但未加密的字符串不正确。我使用的是Macintosh和“crypto-js”:“^ 3.1.5”。JavaScript的加密库不能加密和解密一个简单的例子程序中的字符串

这是我的示例代码。

var crypto = require('crypto-js'); 

var secretMessage = 'I hid the chips under the couch.'; 
var secretKey = '123abc'; 

var encryptedMessage = crypto.AES.encrypt(secretMessage, secretKey); 
console.log('encryptedMessage: ' + encryptedMessage); 

var bytes = crypto.AES.decrypt(encryptedMessage, secretKey); 
var decryptedMessage = bytes.toString(crypto.enc.utf8); 
console.log('decrpt2: ' + decryptedMessage); 

这里是我得到

$ node example-encryption.js 
    encryptedMessage: U2FsdGVkX180KTEpMiLEjZDSAkhNkmbBuRa9RXFwCgx6gA/PUFr+KOIv6Gr6TgIYrkfUu3F+OM/kRJ3sTTgsfg== 
    decrpt2: 49206869642074686520636869707320756e6465722074686520636f7563682e 

能有人帮的结果?

感谢, 格雷格

+0

呃,它是'crypto.enc.Utf8'而不是'crypto.enc.utf8'。你传递的是未定义的,这会导致默认编码,即Hex。 –

+1

我很好奇,为什么不使用内置的'crypto'模块? – mscdex

+0

一个字母变化产生了差异。谢谢。 –

回答

1

有你的代码的几个问题,其中主要是,你需要提供正确长度的密钥,你还需要一个cipherParams对象传递给解密()方法而不是密文本身。

下面是一些代码,工程和,加分,一般与OpenSSL的二进制文件和PHP库在大多数系统中compatibable:

var CryptoJS = require('crypto-js'); 

var secretMessage = 'I hid the chips under the couch.'; 
var secretKey = 'b52b4f45b6e9337b57869d7cb718c693'; 

var encryptedMessage = CryptoJS.AES.encrypt(secretMessage, CryptoJS.enc.Hex.parse(secretKey), 
         { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding }); 

console.log('encryptedMessage: ' + encryptedMessage.ciphertext); 

cipherParams = CryptoJS.lib.CipherParams.create(
       {ciphertext: CryptoJS.enc.Hex.parse(encryptedMessage.ciphertext.toString())}); 

var bytes = CryptoJS.AES.decrypt(cipherParams,CryptoJS.enc.Hex.parse(secretKey), 
      { mode: CryptoJS.mode.ECB, padding: CryptoJS.pad.NoPadding }); 

console.log('Decrypted:' + bytes.toString(CryptoJS.enc.Utf8)); 

没有Initiatlization矢量,因为我们使用的是欧洲央行,而不是CBC。如果你想要一些安全的东西,那么每个消息都要随机使用CBC。