AES-256-CBC encryption - ruby vs node

しばらく前にハマったのでメモ。


$ ruby -v
ruby 2.0.0p451 .....

$ node -v
v0.10.25

Ruby

require 'openssl'
require 'digest'
require 'base64'

def encode(cryptkey, iv, cleardata)
    cipher = OpenSSL::Cipher.new('AES-256-CBC')
    cipher.encrypt
    cipher.key = cryptkey
    cipher.iv  = iv

    encrypted = ''
    encrypted << cipher.update(cleardata)
    encrypted << cipher.final
    Base64.strict_encode64(encrypted)
end

encode w/ Ruby

data = 'The quick brown fox jumps over the lazy dog'
cryptkey = Digest::SHA256.digest('012345678901234567')
iv = '0a1b2c3d4e5f6g7h'
x = encode(cryptkey, iv, data)

=> "SWozLQpQiz2itvbl1PomOPBTvxMmIE6rl4gZlerajsnJrhAfvp6jj5MBSlu+8fle"

Node.js

var crypto = require('crypto');

b64dec = function(data) {
  buf = new Buffer(data, 'base64');
  return buf.toString('binary')
};

decode = function(encrypted_64, cryptkey, iv) {
    var cryptkey = crypto.createHash('sha256').update(cryptkey).digest(),
        decipher = crypto.createDecipheriv('aes-256-cbc', cryptkey, iv),
        decoded  = decipher.update(b64dec(encrypted_64));

    return Buffer.concat([decoded, decipher.final()]);
}

decode w/ Node.js

decode('SWozLQpQiz2itvbl1PomOPBTvxMmIE6rl4gZlerajsnJrhAfvp6jj5MBSlu+8fle',
    '012345678901234567','0a1b2c3d4e5f6g7h').toString()

'The quick brown fox jumps over the lazy dog'








Pages

Powered by Movable Type 4.23-en

About this Entry

This page contains a single entry by Shaolin published on May 15, 2014 12:00 AM.

あいぽんの位置情報がバカになった was the previous entry in this blog.

(test) is the next entry in this blog.

Find recent content on the main index or look in the archives to find all content.