Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save GregNing/5eeb3e48915ac164471770ecc9b9001c to your computer and use it in GitHub Desktop.
Save GregNing/5eeb3e48915ac164471770ecc9b9001c 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment