Created

Embed URL

HTTPS clone URL

SSH clone URL

You can clone with HTTPS or SSH.

Download Gist

Ruby AES encryption test with lib openssl

View aes_test.rb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60
#!/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
Something went wrong with that request. Please try again.