Class: Envcrypt::Envcrypter

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key: ENV['ENVCRYPT_KEY']) ⇒ Envcrypter

Public: Initialize an Envcrypter object

key - A string representing the key to be used for encryption

and decryption (default: ENV['ENVCRYPT_KEY'])


20
21
22
23
24
# File 'lib/envcrypt/envcrypt.rb', line 20

def initialize(key: ENV['ENVCRYPT_KEY'])
  @key = key == nil ? generate_key : key
  @de_cipher = nil
  @en_cipher = nil
end

Instance Attribute Details

#keyObject (readonly)

Public: Returns the key used to encrypt/decrypt secrets



14
15
16
# File 'lib/envcrypt/envcrypt.rb', line 14

def key
  @key
end

Instance Method Details

#decrypt(encrypted) ⇒ Object

Public: Decrypts a secret

secret - the encrypted string to be decrypted

Returns the plain text decrypted string



52
53
54
55
56
# File 'lib/envcrypt/envcrypt.rb', line 52

def decrypt(encrypted)
  cipher = create_cipher(:decrypt)
  plaintxt = cipher.update Base64.decode64(encrypted)
  plaintxt << cipher.final
end

#encrypt(secret) ⇒ Object

Public: Encrypts a secret

secret - the secret string to be encrypted

Returns the encrypted string



39
40
41
42
43
44
45
# File 'lib/envcrypt/envcrypt.rb', line 39

def encrypt(secret)
  cipher = create_cipher(:encrypt)

  encrypted = cipher.update secret
  encrypted << cipher.final
  Base64.encode64(encrypted).chomp
end

#generate_keyObject

Public: Generates a random key

Returns the key



29
30
31
# File 'lib/envcrypt/envcrypt.rb', line 29

def generate_key
  @key = "#{SecureRandom.base64}$#{SecureRandom.base64(32)}$#{SecureRandom.base64}"
end