Skip to content

Instantly share code, notes, and snippets.

@RyanS

RyanS/encrypt.js Secret

Created August 25, 2011 21:05
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save RyanS/799d6021890f34734470 to your computer and use it in GitHub Desktop.
Save RyanS/799d6021890f34734470 to your computer and use it in GitHub Desktop.
encryption woes2
var crypto = require('crypto');
var SimpleEncrypt = (function () {
function cipher(mode, key, iv, data) {
var encipher = crypto[mode]('aes-256-cbc', key, iv),
encoded = encipher.update(data);
encoded += encipher.final();
return encoded;
}
function encrypt(key, iv, data) {
return cipher('createCipheriv', key, iv, data);
}
function decrypt(key, iv, data) {
return cipher('createDecipheriv', key, iv, data);
}
function b64enc(data) {
var b = new Buffer(data, 'binary');
return b.toString('base64');
}
return {
encrypt: encrypt,
decrypt: decrypt,
b64enc: b64enc
};
}());
var cryptkey = crypto.createHash('sha256').update('Nixnogen').digest(),
iv = 'a2xhcgAAAAAAAAAA',
buf = "Here is some data for the coding", // 32 chars
enc = SimpleEncrypt.encrypt(cryptkey, iv, buf);
dec = SimpleEncrypt.decrypt(cryptkey, iv, enc);
console.warn("Encoded length: ", enc.length);
console.warn("Encoded in Base64:", SimpleEncrypt.b64enc(enc));
console.warn("Decoded:", dec);
//What the string will look like coming from ruby base64 encoded
//console.log(decode(cryptkey, iv, (new Buffer(process.argv[2], 'base64'))));
//console.log(process);
#!/usr/bin/env ruby
# -*- coding: utf-8 -*-
require 'base64'
require 'digest'
require 'openssl'
module SimpleEncrypt
def self.cipher(mode, key, iv, data)
cipher = OpenSSL::Cipher.new('AES-256-CBC').send(mode)
cipher.key = key
cipher.iv = iv
encrypted = ''
encrypted << cipher.update(data)
encrypted << cipher.final
encrypted
end
def self.encrypt(key, iv, data)
cipher(:encrypt, key, iv, data)
end
def self.decrypt(key, iv, data)
cipher(:decrypt, key, iv, data)
end
def self.b64enc(data)
Base64.encode64(data).gsub(/\n/, '')
end
end
cryptkey = Digest::SHA256.digest('Nixnogen')
iv = 'a2xhcgAAAAAAAAAA'
buf = "Here is some data for the coding" # 32 chars
enc = SimpleEncrypt.encrypt(cryptkey, iv, buf)
dec = SimpleEncrypt.decrypt(cryptkey, iv, enc)
#p `node encrypt.js #{SimpleEncrypt.b64enc(enc)}`
puts "Encoded length: #{enc.length}"
puts "Encoded in Base64: " + SimpleEncrypt.b64enc(enc)
puts "Decoded data: " + dec
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment