I have some PHP code that produces some ciphertext as follows:
<?php
$data = '12345678123456781234567812345678123456781234567812345678123456781234567812345678';
$ciphertext = mcrypt_encrypt('rijndael-128', 'M02cnQ51Ji97vwT4', $data, 'ecb');
echo base64_encode($ciphertext);
?>
Produces:
6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=
I know that ECB is not the best mode to use in for this type of data, but I am not the one encrypting it.
The trouble I am having is with node-crypto trying to decrypt this. My node script is as follows:
var crypto = require("crypto");
var data = "6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=";
var out = '';
var decipher = crypto.createDecipher("aes-256-ecb", "M02cnQ51Ji97vwT4");
decipher.setAutoPadding(false); //this needs to be set otherwise i get an error:06065064:bad decrypt
out += decipher.update(data, "base64", "ascii");
out += decipher.final("ascii");
console.log(out);
Produces:
"3i<1pzV7A
vnE"3i<1pzV7A
vnE"3i<1pzV7A
vnE"3i<1pzV7A
vnE"3i<1pzV7A
vnE
I can't tell what has gone wrong here, the repeating pattern of the original data is recovered but it is not correct. I have had trouble finding what equivalent "rijndael-128" has in openssl, and it seems that it must be 'aes-256-ecb', and an IV isn't needed as it is ECB. How can I get these two libraries to work together?
Thanks, J
https://github.com/tugrul/node-mcrypt
var mcrypt = require('mcrypt');
var bfEcb = new mcrypt.MCrypt('rijndael-128', 'ecb');
bfEcb.open('M02cnQ51Ji97vwT4');
var ciphertext = new Buffer('6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=', 'base64');
var plaintext = bfEcb.decrypt(ciphertext);
console.log(plaintext.toString());
Try this:
var crypto = require("crypto");
var data = "6tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Tq0nruhoXVfXZf8UThqEt06tJ67oaF1X12X/FE4ahLdOrSeu6GhdV9dl/xROGoS3Q=";
var out = '';
var decipher = crypto.createDecipheriv("aes-256-ecb", "M02cnQ51Ji97vwT4", '');
out += decipher.update(data, "base64");
out += decipher.final();
console.log(out);
Changing createDecipher(...) to createDecipheriv (notice iv at the end) with empty third parameter (so called initialization vector) do the trick in my case. And in this case remove setAutoPadding(false).