Skip to content

Instantly share code, notes, and snippets.

@quangtt-rks
Forked from ericchen/gist:3081968
Created October 11, 2017 09:16
Show Gist options
  • Save quangtt-rks/edd92249b41fd1e0b957b20d7771c2a8 to your computer and use it in GitHub Desktop.
Save quangtt-rks/edd92249b41fd1e0b957b20d7771c2a8 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