Created
March 22, 2013 11:17
-
-
Save mkarliner/5220560 to your computer and use it in GitHub Desktop.
Using OpenSSL with Ruby to do AES encryption
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# This module for using AES encryption with ruby from | |
# http://www.brentsowers.com/2007/12/aes-encryption-and-decryption-in-ruby.html | |
require 'openssl' | |
require "base64" | |
module AESCrypt | |
# Decrypts a block of data (encrypted_data) given an encryption key | |
# and an initialization vector (iv). Keys, iv's, and the data | |
# returned are all binary strings. Cipher_type should be | |
# "AES-256-CBC", "AES-256-ECB", or any of the cipher types | |
# supported by OpenSSL. Pass nil for the iv if the encryption type | |
# doesn't use iv's (like ECB). | |
#:return: => String | |
#:arg: encrypted_data => String | |
#:arg: key => String | |
#:arg: iv => String | |
#:arg: cipher_type => String | |
def AESCrypt.decrypt(encrypted_data, key, iv, cipher_type) | |
aes = OpenSSL::Cipher::Cipher.new(cipher_type) | |
aes.decrypt | |
aes.key = key | |
aes.iv = iv if iv != nil | |
aes.update(encrypted_data) + aes.final | |
end | |
# Encrypts a block of data given an encryption key and an | |
# initialization vector (iv). Keys, iv's, and the data returned | |
# are all binary strings. Cipher_type should be "AES-256-CBC", | |
# "AES-256-ECB", or any of the cipher types supported by OpenSSL. | |
# Pass nil for the iv if the encryption type doesn't use iv's (like | |
# ECB). | |
#:return: => String | |
#:arg: data => String | |
#:arg: key => String | |
#:arg: iv => String | |
#:arg: cipher_type => String | |
def AESCrypt.encrypt(data, key, iv, cipher_type) | |
aes = OpenSSL::Cipher::Cipher.new(cipher_type) | |
aes.encrypt | |
aes.key = key | |
aes.iv = iv if iv != nil | |
aes.update(data) + aes.final | |
end | |
end | |
# Here is an example of using the module above with the | |
# test vectors from http://www.inconteam.com/software-development/41-encryption/55-aes-test-vectors | |
puts "TEST VECTOR " | |
key = "603deb1015ca71be2b73aef0857d77811f352c073b6108d72d9810a30914dff4" | |
test_vector = "6bc1bee22e409f96e93d7e117393172a" | |
puts "Key length #{key.length} (#{key})" | |
puts "Test Vector: #{test_vector}" | |
binary_test_vector = test_vector.unpack('a2'*32).map{|x| x.hex}.pack('c'*32) | |
binary_key = key.unpack('a2'*32).map{|x| x.hex}.pack('c'*32) | |
x = AESCrypt.encrypt(binary_test_vector, binary_key, nil, "AES-256-ECB") | |
e = x.unpack("C" * 32).map{|x| sprintf("%02x", x)}.pack('A2'*32) | |
puts e.inspect | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment