Skip to content

Instantly share code, notes, and snippets.

@ericchen
Created July 10, 2012 08:10
Show Gist options
  • Star 8 You must be signed in to star a gist
  • Fork 4 You must be signed in to fork a gist
  • Save ericchen/3081968 to your computer and use it in GitHub Desktop.
Save ericchen/3081968 to your computer and use it in GitHub Desktop.
ruby openssl AES encrypt and decrypt
require 'base64'
require 'digest'
require 'openssl'
module AESCrypt
def AESCrypt.encrypt(password, iv, cleardata)
cipher = OpenSSL::Cipher.new('AES-256-CBC')
cipher.encrypt # set cipher to be encryption mode
cipher.key = password
cipher.iv = iv
encrypted = ''
encrypted << cipher.update(cleardata)
encrypted << cipher.final
AESCrypt.b64enc(encrypted)
end
def AESCrypt.decrypt(password, iv, secretdata)
secretdata = Base64::decode64(secretdata)
decipher = OpenSSL::Cipher::Cipher.new('aes-256-cbc')
decipher.decrypt
decipher.key = password
decipher.iv = iv if iv != nil
decipher.update(secretdata) + decipher.final
end
def AESCrypt.b64enc(data)
Base64.encode64(data).gsub(/\n/, '')
end
end
password = Digest::SHA256.digest('Nixnogen')
iv = 'a2xhcgAAAAAAAAAA'
buf = "Here is some data for the encrypt" # 32 chars
enc = AESCrypt.encrypt(password, iv, buf)
dec = AESCrypt.decrypt(password, iv, enc)
puts "encrypt length: #{enc.length}"
puts "encrypt in Base64: " + enc
puts "decrypt all: " + dec
@pmallesham
Copy link

How to encrypt data with AES 256 ECB PKCS5Padding

@GuyPaddock
Copy link

This does not appear to be ECB -- it looks like it's CBC. Can you confirm?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment