Maxwin
Maxwin

Reputation: 178

nodejs cipher ubuntu not working as expected

I wrote a data encrypt tool, it works on mac os, but not on ubuntu. The following code shows the difference.

var crypto = require('crypto');

var k = '1234567890123456';
var v = '1234567890123456';
var alg = 'AES-128-CBC';


var buf = new Buffer('Hello world!');
console.log(buf);

var cipher = crypto.createCipheriv(alg, k, v);
var result = cipher.update(buf);
result += cipher.final();
buf = new Buffer(result, 'binary');
console.log(buf);

var decipher = crypto.createDecipheriv(alg, k, v);
decipher.setAutoPadding(auto_padding=false);
result = decipher.update(buf);
result += decipher.final();
buf = new Buffer(result, 'binary');

console.log(buf);
console.log(buf.toString());

outputs, on mac:

<Buffer 48 65 6c 6c 6f 20 77 6f 72 6c 64 21>
<Buffer 17 0e 2d 73 94 bf d4 24 95 b3 a7 49 73 58 5e 3f>
<Buffer 48 65 6c 6c 6f 20 77 6f 72 6c 64 21 04 04 04 04>
Hello world!

ubuntu:

<Buffer 48 65 6c 6c 6f 20 77 6f 72 6c 64 21>
<Buffer 17 0e 2d 73 fd fd fd 24 fd fd fd 49 73 58 5e 3f>
<Buffer 05 6d 69 fd fd 1b 49 62 60 39 fd 68 fd fd fd>
mi��Ib`9�h���

any idea? thx

Upvotes: 4

Views: 278

Answers (1)

robertklep
robertklep

Reputation: 203514

Node 0.10.0 introduced some internal changes to the crypto module which might break existing code.

With the following fix (as suggested by http://nodejs.org/api/crypto.html#crypto_recent_api_changes) it works on my Debian machine:

var crypto = require('crypto');
crypto.DEFAULT_ENCODING = 'binary';
...

(thanks to @user568109 for making me read the page!)

The aforementioned page also makes suggestions to permanently fix your code, as setting crypto.DEFAULT_ENCODING is considered to be a temporary measure.

Upvotes: 3

Related Questions