Reputation: 1247
I'm decrypting messages from Firebase
that is being sent to a Firebase function
.
I'm quite new with encryption. But i'm using AES-256
, with a static IV
(i'm aware that not having a random iv isn't the best solution).
but i'm getting the correct results on both Android
and iOS
but not in node.js
.
The message is Base64 encoded
this is my code:
const crypto = require('crypto');
const cryptoKey = "MyEncryptionKey1MyEncryptionKey1";
const text = "Cidor8Ph7pZqPw0x2AwIKw=="
let messageToDecrypt = new Buffer(text, "utf8")
let key = new Buffer(cryptoKey, "utf8");
var decipher = crypto.createCipheriv('aes-256-cbc', key, iv);
var decoded = decipher.update(messageToDecrypt,'base64','utf-8');
decoded += decipher.final('utf-8');
text = decoded
console.log(decoded
The code compiles and runs, but it gives me a mumbo-jumbo answer that looks similar to this �ŴC�p�-Q�)�1H&�8pD}5�i��ǁ�g
Any ideas on how to improve this code?
Upvotes: 1
Views: 3417
Reputation: 26877
What immediately jumps out to me is that you aren't creating your messageToDecrypt
Buffer correctly. You are writing:
const text = "Cidor8Ph7pZqPw0x2AwIKw=="
let messageToDecrypt = new Buffer(text, "utf8")
Which means, make a Buffer, the text I'm giving you is utf8 encoded. It isn't utf8 encoded, it is base64 encoded.
So you should use:
const text = "Cidor8Ph7pZqPw0x2AwIKw=="
let messageToDecrypt = Buffer.from(text, "base64")
Consider the difference in Buffers that the encoding makes:
> Buffer.from(text, "utf8");
<Buffer 43 69 64 6f 72 38 50 68 37 70 5a 71 50 77 30 78 32 41 77 49 4b 77 3d 3d>
> Buffer.from(text, "base64");
<Buffer 0a 27 68 af c3 e1 ee 96 6a 3f 0d 31 d8 0c 08 2b>
Upvotes: 5