Last active
November 23, 2018 21:06
-
-
Save Jmzp/fcc065904d8b2f588f347a8fef74d46b to your computer and use it in GitHub Desktop.
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
class AESCrypto | |
# @!attribute cipher | |
# @return [OpenSSL::Cipher] the cipher object used to encrypt and decrypt | |
# @!attribute iv | |
# @return [String] the initialization vector used for the cipher object | |
# @!attribute key | |
# @return [String] the key used for the cipher object | |
require 'openssl' | |
require 'base64' | |
def initialize(iv = '', key = '', length = '128', mode = :CBC) | |
@cipher = OpenSSL::Cipher::AES.new(length, mode) | |
@iv = iv != '' ? iv : @cipher.random_iv | |
@key = key != '' ? hex_to_bin(key) : hex_to_bin(@cipher.random_key) | |
end | |
# @param data [String] the data to be encrypt | |
# @return [Base64 String] the string in base64 encrypted | |
def encrypt(data) | |
@cipher.encrypt | |
@cipher.iv = @iv | |
@cipher.key = @key | |
Base64.encode64(@iv + @cipher.update(data) + @cipher.final) | |
end | |
# @param data [Base64 String] the string in base64 that will be decrypt | |
# @return [String] the string decrypted | |
def decrypt(data) | |
data = Base64.decode64(data) | |
@iv = data[0...16] | |
data = data[16...data.length] | |
@cipher.decrypt | |
@cipher.iv = @iv | |
@cipher.key = @key | |
@cipher.update(data) + @cipher.final | |
end | |
private | |
# @param s [String] the data to be converted to binary | |
# @return [String] the data converted to binary | |
def hex_to_bin(s) | |
s.scan(/../).map { |x| x.hex.chr }.join | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment