Class: SimpleEncryptor

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

Overview

Simple class to crypt / decrypt strings (url-safe version)

Examples:

@secret_key  = 'foobarfoobarfoobarfoobarfoobarfo'
@iv          = 'foobarfoobarfoob'
secret       = SimpleEncryptor.encrypt('Bond, James Bond', @secret_key, @iv)
message      = SimpleEncryptor.decrypt(secret, @secret_key, @iv)

See Also:

Constant Summary collapse

VERSION =

Current lib version

'0.0.3'
ENCRYPTION_TYPE =

Encryption type to use (set as a constant since changing it without changing code is unlikely)

'aes-256-cbc'

Class Method Summary collapse

Class Method Details

.decrypt(encrypted_secret, key) ⇒ String

Static method to decrypt a message

Parameters:

  • encrypted_secret (String)

    the encrypted massage to decrypt (url-safe, Base64)

  • key (String)

    secret key to decrypt message with (32 bytes)

Returns:

  • (String)

    decrypted message



51
52
53
54
55
56
57
58
59
60
# File 'lib/simple_encryptor.rb', line 51

def self.decrypt(encrypted_secret, key)
  encrypted_secret = Base64.urlsafe_decode64(encrypted_secret)

  cipher = OpenSSL::Cipher.new(ENCRYPTION_TYPE).decrypt

  cipher.key = key
  cipher.iv  = encrypted_secret.slice!(0, cipher.iv_len) # initialisation vector

  cipher.update(encrypted_secret) + cipher.final
end

.encrypt(secret, key, _ = "\0") ⇒ String

Static method to encrypt a message

Parameters:

  • secret (String)

    the massage to encrypt

  • key (String)

    secret key to encrypt message with (32 bytes)

Returns:

  • (String)

    encrypted message (url-safe, Base64)



33
34
35
36
37
38
39
40
41
42
43
# File 'lib/simple_encryptor.rb', line 33

def self.encrypt(secret, key, _ = "\0")
  cipher = OpenSSL::Cipher.new(ENCRYPTION_TYPE).encrypt

  cipher.key = key
  iv = cipher.random_iv # initialisation vector

  encrypted = cipher.update(secret) + cipher.final
  encrypted = iv + encrypted

  Base64.urlsafe_encode64(encrypted, padding: false)
end