I'm trying to decrypt a file encrypted with openssl using CryptoJS 3.1.5.
Everything works fine if I encrypt and decrypt using CryptoJS, same goes for OpenSSL in shell, but when I try to mix CryptoJS with OpenSSL everything goes wrong.
The file is created using this command:
openssl enc -aes-256-cbc -in file.txt -out file.enc -k password
and I try to decrypt like this:
fs.readFile('file.enc', function(err, data) {
var decrypted = CryptoJS.AES.decrypt(
data.toString(),
"password",
{ mode : CryptoJS.mode.CBC }
);
console.log(decrypted.toString(CryptoJS.enc.Utf8));
});
// Give me this err: Uncaught Error: Malformed UTF-8 data
And in the other way, I do :
fs.readFile('file.txt', function(err, data) {
var encrypted = CryptoJS.AES.encrypt(
data.toString(),
"password",
{ mode : CryptoJS.mode.CBC });
fs.writeFile('file.enc', encrypted);
});
And then in Shell:
openssl enc -d -aes-256-cbc -in file.enc -out file2.txt -k password
// Give me this err: bad magic number
Am I missing something obvious ?
For the record, this is how I decrypt openssl file.
//openssl enc -aes-256-cbc -in file.txt -out file.enc -k password
fs.readFile('file.enc', function(err, data) {
var salt = data.toString("hex", 8, 16),
enc = data.toString("hex", 16, data.length),
derivedParams = CryptoJS.kdf.OpenSSL.execute(
password,
256/32,
128/32,
CryptoJS.enc.Hex.parse(salt)
),
cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext : CryptoJS.enc.Hex.parse(enc)
}),
decrypted = CryptoJS.AES.decrypt(
cipherParams,
derivedParams.key,
{ iv : derivedParams.iv }
);
console.log(hex2a(decrypted.toString())); // result is in hexa
});
And this is how I encrypt to make it work with OpenSSL
fs.readFile('file.txt', function(err, data) {
var encrypted = CryptoJS.AES.encrypt(data.toString(), password);
buff = new Buffer(encrypted.toString(), "base64");
fs.writeFile('file.enc', buff);
});
// openssl enc -d -aes-256-cbc -in file.enc -out file2.txt -k password
Hope it'll help someone :)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With