May 2014 Archives

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 Archive

This page is an archive of entries from May 2014 listed from newest to oldest.

November 2013 is the previous archive.

January 2015 is the next archive.

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