Module: EncryptionAccessor::AESCrypt

Extended by:
AESCrypt
Included in:
AESCrypt
Defined in:
lib/encryption_accessor/aes_crypt.rb

Constant Summary collapse

ALGORITHM =
"AES-256-CBC"
SECRET =
"add-your-way-eliasonmedia-02-10-2011"
ENCODE_DIRECTIVE =
'H*'

Instance Method Summary collapse

Instance Method Details

#decrypt(encrypted_data, key = SECRET, iv = nil, cipher_type = ALGORITHM) ⇒ Object

ALGORITHM = “AES-256-ECB” Decrypts a block of data (encrypted_data) given an encryption key and an initialization vector (iv). Keys, iv’s, and the data returned are all binary strings. Cipher_type should be “AES-256-CBC”, “AES-256-ECB”, or any of the cipher types supported by OpenSSL. Pass nil for the iv if the encryption type doesn’t use iv’s (like ECB). :return: => String :arg: encrypted_data => String :arg: key => String :arg: iv => String :arg: cipher_type => String



26
27
28
29
30
31
32
# File 'lib/encryption_accessor/aes_crypt.rb', line 26

def decrypt(encrypted_data, key = SECRET, iv = nil, cipher_type = ALGORITHM)
    aes = OpenSSL::Cipher::Cipher.new(cipher_type)
    aes.decrypt
    aes.key = key
    aes.iv = iv if iv != nil
    aes.update([encrypted_data].pack(ENCODE_DIRECTIVE)) + aes.final
end

#encrypt(data, key = SECRET, iv = nil, cipher_type = ALGORITHM) ⇒ Object

Encrypts a block of data given an encryption key and an initialization vector (iv). Keys, iv’s, and the data returned are all binary strings. Cipher_type should be “AES-256-CBC”, “AES-256-ECB”, or any of the cipher types supported by OpenSSL.

Pass nil for the iv if the encryption type doesn’t use iv’s (like ECB). :return: => String :arg: data => String :arg: key => String :arg: iv => String :arg: cipher_type => String



45
46
47
48
49
50
51
# File 'lib/encryption_accessor/aes_crypt.rb', line 45

def encrypt(data, key = SECRET, iv = nil, cipher_type = ALGORITHM)
    aes = OpenSSL::Cipher::Cipher.new(cipher_type)
    aes.encrypt
    aes.key = key
    aes.iv = iv if iv != nil
    (aes.update(data) + aes.final).unpack(ENCODE_DIRECTIVE)[0]
end