Created
July 10, 2012 08:10
-
-
Save chensoren/3081968 to your computer and use it in GitHub Desktop.
ruby openssl AES encrypt and decrypt
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
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
How to encrypt data with AES 256 ECB PKCS5Padding