class ActiveSupport::MessageEncryptor
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.
Public Class Methods
Given a cipher, returns the key length of the cipher to help generate the key of desired size
# 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
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
# File lib/messagesodium.rb, line 21 def initialize(secret, *_signature_key_or_options) @box = RbNaCl::SimpleBox.from_secret_key(secret) end
Public Instance Methods
Decrypt the message, and check the auth tag in the process.
# 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 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
# File lib/messagesodium.rb, line 30 def encrypt_and_sign(value) Base64.urlsafe_encode64(@box.encrypt(::JSON.dump(value))) end