PHP中的AES-256-CBC加密和Node.js中的解密 [英] AES-256-CBC encryption in PHP and decryption in Node.js
问题描述
我的问题是,我编码一个字符串在PHP与m_crypt模块在aes-256-cbc与base64像这样:
my problem is that I encode a string in PHP with the m_crypt module in aes-256-cbc with base64 like this:
function encrypt($data) {
if(32 !== strlen($this->secret)) $this->secret = hash('SHA256', $this->secret, true);
$padding = 16 - (strlen($data) % 16);
$data .= str_repeat(chr($padding), $padding);
$encrypt = mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $this->secret, $data, MCRYPT_MODE_CBC, str_repeat("\0", 16));
return base64_encode($encrypt);
}
其中$ this-> secret是32位aes键和$ data是我要加密的字符串。
Where $this->secret is a 32-bit aes key and $data is the string I want to encrypt.
这工作正常,文本是加密的,并发送到服务器没有任何问题(我检查了两次!),现在我想使用Node.JS解码这整个东西像这样:
This works fine, the text is encrypted and send to the server without any problems (I checked that twice!) and now i want to decode this whole thing with Node.JS like this:
var decipher = Core.crypto.createDecipher('aes-256-cbc', rows[0]['sessionkey']);
decipher.update(body.user, 'base64', 'utf8');
var user = decipher.final('utf8');
其中Core.crypto是Node.JS中普通加密模块的require调用,rows [0 ] ['sessionkey']是用于通过mysql请求加密的密钥,body.user是通过post请求发送的PHP加密字符串。
Where Core.crypto is the require call of the normal crypto module in Node.JS, rows[0]['sessionkey'] is the key used for encryption recived via mysql request and body.user is the PHP encrypted string send via post request.
工作正常,除了这个小的decypt的东西...我搜索google和一切,并尝试了示例代码,但似乎有些事情与我的代码是不正确的。
As I mentioned, everything works fine, except for this little decypt thing... i searched google and everything and tried sample code, but it seems that something with my code is not right.
推荐答案
Ok我想出了自己。我忘记在Node.js中解密消息时设置iv,工作代码如下所示:
Ok I figured it out myself. I forgot to set the iv when decrypting the message in Node.js, the working code looks like this:
var key = new Buffer(rows[0]['sessionkey'], 'binary');
function decipher(key, data) {
var decipher = Core.crypto.createDecipheriv('aes-256-cbc', key.toString('binary'), str_repeat('\0', 16));
decipher.update(data, 'base64', 'utf8');
return decipher.final('utf8');
}
我希望这将有助于未来的任何人!
I hope this will help anyone in the future!
最好的问候
这篇关于PHP中的AES-256-CBC加密和Node.js中的解密的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!