Create a gist now

Instantly share code, notes, and snippets.

Ruby AES encryption test with lib openssl
#!/usr/bin/env ruby
# encoding: UTF-8
require 'rubygems'
begin
require 'bundler/setup'
rescue LoadError
end
require 'digest/sha1'
require 'openssl'
require 'base64'
class AES
Type = "AES-256-CBC"
def initialize(pass, cipher_type=Type)
@aes = ::OpenSSL::Cipher::Cipher.new(cipher_type)
@aes.padding = 1
#NOTE: a2*32 is for 256bit AES, change to 16 for 128...
@key = Digest::SHA1.hexdigest(pass).unpack('a2'*32).map{|x|x.hex}.pack('c'*32)
#@key = Digest::SHA256.digest(pass)
@password = pass
end
def encrypt(data)
@aes.encrypt
@aes.key = @key
@aes.update(data) + @aes.final
end
def decrypt(data)
@aes.decrypt
@aes.key = @key
@aes.update(data) + @aes.final
rescue OpenSSL::Cipher::CipherError
raise PasswordInvalid, "Password incorrect!"
end
class PasswordInvalid < Exception
def initialize(s); s; end
end
end
pass = "test"
aes = AES.new(pass)
plain = "hello world"
puts "plain: #{plain.inspect}"
encstr = aes.encrypt(plain)
puts "encrypted: #{encstr.inspect}"
aes = AES.new(pass)
begin
decrypted = aes.decrypt(encstr)
puts "decrypted: #{decrypted.inspect}"
rescue AES::PasswordInvalid
puts "ERROR: password is invalid"
rescue NoMethodError
puts "ERROR: encrypted data was invalid"
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment