Class: Gibberish::AES

Inherits:
Object
  • Object
show all
Defined in:
lib/gibberish/aes.rb

Overview

Handles AES encryption and decryption in a way that is compatible with OpenSSL.

Defaults to 256-bit CBC encryption, ideally you should leave it this way

Basic Usage

Encrypting

cipher = Gibberish::AES.new('p4ssw0rd')
cipher.encrypt("some secret text")
#=> "U2FsdGVkX1/D7z2azGmmQELbMNJV/n9T/9j2iBPy2AM=\n"

Decrypting

cipher = Gibberish::AES.new('p4ssw0rd')
cipher.decrypt(""U2FsdGVkX1/D7z2azGmmQELbMNJV/n9T/9j2iBPy2AM=\n"")
#=> "some secret text"

OpenSSL Interop

echo "U2FsdGVkX1/D7z2azGmmQELbMNJV/n9T/9j2iBPy2AM=\n" | openssl enc -d -aes-256-cbc -a -k p4ssw0rd

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (AES) initialize(password, size = 256)

Initialize with the password

Parameters:

  • (String) password
  • (Integer) size (defaults to: 256)


34
35
36
37
38
# File 'lib/gibberish/aes.rb', line 34

def initialize(password, size=256)
  @password = password
  @size = size
  @cipher = OpenSSL::Cipher::Cipher.new("aes-#{size}-cbc")
end

Instance Attribute Details

- (Object) cipher (readonly)

Returns the value of attribute cipher



28
29
30
# File 'lib/gibberish/aes.rb', line 28

def cipher
  @cipher
end

- (Object) password (readonly)

Returns the value of attribute password



28
29
30
# File 'lib/gibberish/aes.rb', line 28

def password
  @password
end

- (Object) size (readonly)

Returns the value of attribute size



28
29
30
# File 'lib/gibberish/aes.rb', line 28

def size
  @size
end

Instance Method Details

- (Object) decrypt(data, opts = {}) Also known as: dec, d



54
55
56
57
58
59
60
# File 'lib/gibberish/aes.rb', line 54

def decrypt(data, opts={})
  data = Base64.decode64(data)
  salt = data[8..15]
  data = data[16..-1]
  setup_cipher(:decrypt, salt)
  cipher.update(data) + cipher.final
end

- (Object) encrypt(data, opts = {}) Also known as: enc, e



40
41
42
43
44
45
46
47
48
49
50
# File 'lib/gibberish/aes.rb', line 40

def encrypt(data, opts={})
  salt = generate_salt
  setup_cipher(:encrypt, salt)
  e = cipher.update(data) + cipher.final
  e = "Salted__#{salt}#{e}" #OpenSSL compatible
  if opts[:binary]
    e
  else
    Base64.encode64(e)
  end
end