Class: ActiveSupport::MessageEncryptor

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

Overview

MessageEncryptor is a simple way to encrypt values which get stored somewhere you don’t trust.

The cipher text and initialization vector are base64 encoded and returned to you.

Defined Under Namespace

Classes: InvalidMessage

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(secret, *_signature_key_or_options) ⇒ MessageEncryptor

Uses “secret” as a libsodium Simplebox initialiser Secret must be 32 bytes (256-bit) long The options and signature fields are unused as lidsodium does not require a second key for an HMAC. However we need to retain them as they exist in the original function



21
22
23
# File 'lib/messagesodium.rb', line 21

def initialize(secret, *_signature_key_or_options)
  @box = RbNaCl::SimpleBox.from_secret_key(secret)
end

Class Method Details

.key_len(_cipher = nil) ⇒ Object

Given a cipher, returns the key length of the cipher to help generate the key of desired size



46
47
48
49
# File 'lib/messagesodium.rb', line 46

def self.key_len(_cipher = nil)
  # Ignore the cipher - libsodium knows what it's doing.
  RbNaCl::SecretBox.key_bytes
end

Instance Method Details

#decrypt_and_verify(value) ⇒ Object

Decrypt the message, and check the auth tag in the process.



35
36
37
38
39
40
41
42
# File 'lib/messagesodium.rb', line 35

def decrypt_and_verify(value)
  ::JSON.parse(
    @box.decrypt(
      Base64.urlsafe_decode64(value)),
    symbolize_names: true)
rescue RbNaCl::CryptoError
  raise InvalidMessage
end

#encrypt_and_sign(value) ⇒ Object

Encrypt and authenticate using libsodium XSalsa20/Poly1305 Serialise with JSON.dump Returns base64(random nonce + cipher + auth tag) URLSafe encoding means it doesn’t have to be mangled further to become a cookie



30
31
32
# File 'lib/messagesodium.rb', line 30

def encrypt_and_sign(value)
  Base64.urlsafe_encode64(@box.encrypt(::JSON.dump(value)))
end