Class: AES::AES

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key, opts = {}) ⇒ AES

Returns a new instance of AES.



43
44
45
46
47
48
49
# File 'lib/aes/aes.rb', line 43

def initialize(key, opts={})
  merge_options opts
  @cipher = nil
  @key    = key
  @iv   ||= random_iv
  self
end

Instance Attribute Details

#cipherObject (readonly)

Returns the value of attribute cipher.



39
40
41
# File 'lib/aes/aes.rb', line 39

def cipher
  @cipher
end

#cipher_textObject (readonly)

Returns the value of attribute cipher_text.



40
41
42
# File 'lib/aes/aes.rb', line 40

def cipher_text
  @cipher_text
end

#ivObject (readonly)

Returns the value of attribute iv.



38
39
40
# File 'lib/aes/aes.rb', line 38

def iv
  @iv
end

#keyObject (readonly)

Returns the value of attribute key.



37
38
39
# File 'lib/aes/aes.rb', line 37

def key
  @key
end

#optionsObject (readonly)

Returns the value of attribute options.



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

def options
  @options
end

#plain_textObject (readonly)

Returns the value of attribute plain_text.



41
42
43
# File 'lib/aes/aes.rb', line 41

def plain_text
  @plain_text
end

Instance Method Details

#decrypt(cipher_text) ⇒ Object

Decrypts



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/aes/aes.rb', line 66

def decrypt(cipher_text)
  @cipher_text = cipher_text
  _setup(:decrypt)
  case @options[:format]
  when :base_64
    ctext = b64_d(@cipher_text)
  else
    ctext = @cipher_text
  end
  @cipher.iv  = ctext[0]
  @plain_text = @cipher.update(ctext[1]) + @cipher.final 
end

#encrypt(plain_text) ⇒ Object

Encrypts



52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/aes/aes.rb', line 52

def encrypt(plain_text)
  @plain_text = plain_text
  _setup(:encrypt)
  @cipher.iv  = @iv
  case @options[:format]
  when :base_64
    @cipher_text = b64_e(@iv) << "$" << b64_e(_encrypt)
  else
    @cipher_text = [@iv, _encrypt]
  end
  @cipher_text
end

#random_ivObject

Generate a random initialization vector



80
81
82
83
# File 'lib/aes/aes.rb', line 80

def random_iv
  _setup(:encrypt)
  @cipher.random_iv
end

#random_key(length = 256) ⇒ Object

Generate a random key



86
87
88
# File 'lib/aes/aes.rb', line 86

def random_key(length=256)
  _random_seed.unpack('H*')[0][0..((length/8)-1)]
end