Skip to content

Instantly share code, notes, and snippets.

@andersonbosa
Forked from ericchen/gist:3081968
Created September 20, 2022 16:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andersonbosa/d0f0d7cb102b5dcfcf14c692827be8f3 to your computer and use it in GitHub Desktop.
Save andersonbosa/d0f0d7cb102b5dcfcf14c692827be8f3 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