Reputation: 154
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);
}
Where $this->secret is a 32-bit aes key and $data is the string I want to encrypt.
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');
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.
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.
Upvotes: 1
Views: 2149
Reputation: 154
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!
Best Regards
Upvotes: 0