Class: EasyCipher::Cipher

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

Overview

The cipher class

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key = nil, iv = nil) ⇒ Cipher

Create a new cipher instance.

Parameters:

  • key (String) (defaults to: nil)

    A 256bit random key, or nil.

  • iv (String) (defaults to: nil)

    An initialization vector, or nil.



11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/easy_cipher/cipher.rb', line 11

def initialize(key = nil, iv = nil)
  if (key && !iv) || (!key && iv)
    raise ArgumentError, "Must supply key AND iv, or neither."
  end

  @key = key
  @iv = iv

  @encryptor = ::OpenSSL::Cipher::AES256.new(:CBC)
  @encryptor.encrypt

  if @key
    @encryptor.key = @key
  else
    @key = @encryptor.random_key
  end

  if @iv
    @encryptor.iv = @iv
  else
    @iv = @encryptor.random_iv
  end

  @decryptor = ::OpenSSL::Cipher::AES256.new(:CBC)
  @decryptor.decrypt
  @decryptor.key = @key
  @decryptor.iv = @iv
end

Instance Attribute Details

#ivObject (readonly)

Returns the value of attribute iv.



6
7
8
# File 'lib/easy_cipher/cipher.rb', line 6

def iv
  @iv
end

#keyObject (readonly)

Returns the value of attribute key.



6
7
8
# File 'lib/easy_cipher/cipher.rb', line 6

def key
  @key
end

Class Method Details

.new64(key, iv) ⇒ Object

Create a new cipher instance.

Parameters:

  • key (String)

    A 256bit random key, base64 encoded.

  • iv (String)

    An initialization vector, base64 encoded.



43
44
45
# File 'lib/easy_cipher/cipher.rb', line 43

def self.new64(key, iv)
  return self.new(Base64.decode64(key), Base64.decode64(iv))
end

Instance Method Details

#decrypt(encrypted_data) ⇒ String

Decrypt the given data.

Parameters:

  • encrypted_data (String)

    Base64 representation of the encrypted data.

Returns:

  • (String)

    The decrypted data.



68
69
70
# File 'lib/easy_cipher/cipher.rb', line 68

def decrypt(encrypted_data)
  return decrypt_line(Base64.decode64(encrypted_data))
end

#encrypt(data) ⇒ String

Encrypt the given data.

Parameters:

  • data (String)

    The data to encrypt

Returns:

  • (String)

    Base64 representation of the encrypted data.



60
61
62
# File 'lib/easy_cipher/cipher.rb', line 60

def encrypt(data)
  return Base64.encode64(encrypt_line(data, true))
end

#iv64Object

Return the iv in base64 (e.g. to store in string fields)



53
54
55
# File 'lib/easy_cipher/cipher.rb', line 53

def iv64
  return Base64.encode64(@iv)
end

#key64Object

Return the key in base64 (e.g. to store in string fields)



48
49
50
# File 'lib/easy_cipher/cipher.rb', line 48

def key64
  return Base64.encode64(@key)
end