Class: Paseto::V2::Local::Key
- Inherits:
-
Object
- Object
- Paseto::V2::Local::Key
- Defined in:
- lib/paseto/local.rb
Overview
Encryption key
Class Method Summary collapse
Instance Method Summary collapse
- #decrypt(token, footer = nil) ⇒ Object
- #encode64 ⇒ Object
- #encrypt(message, footer = EMPTY_FOOTER) ⇒ Object
-
#initialize(key) ⇒ Key
constructor
A new instance of Key.
Constructor Details
#initialize(key) ⇒ Key
Returns a new instance of Key.
22 23 24 25 |
# File 'lib/paseto/local.rb', line 22 def initialize(key) @key = key @aead = RbNaCl::AEAD::XChaCha20Poly1305IETF.new(key) end |
Class Method Details
.decode64(encoded_key) ⇒ Object
18 19 20 |
# File 'lib/paseto/local.rb', line 18 def self.decode64(encoded_key) new(Paseto.decode64(encoded_key)) end |
.generate ⇒ Object
14 15 16 |
# File 'lib/paseto/local.rb', line 14 def self.generate new(RbNaCl::Random.random_bytes(RbNaCl::AEAD::XChaCha20Poly1305IETF.key_bytes)) end |
Instance Method Details
#decrypt(token, footer = nil) ⇒ Object
41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/paseto/local.rb', line 41 def decrypt(token, = nil) ||= token. if token.is_a? Paseto::Token ||= EMPTY_FOOTER parsed = Paseto.verify_token(token, HEADER, ) nonce = parsed.payload[0, NONCE_BYTES] ciphertext = parsed.payload[NONCE_BYTES..-1] raise BadMessageError, 'Unable to process message' if nonce.nil? || ciphertext.nil? begin data = additional_data(nonce, ) @aead.decrypt(nonce, ciphertext, data) rescue RbNaCl::LengthError raise NonceError, 'Invalid nonce' rescue RbNaCl::CryptoError raise AuthenticationError, 'Token signature invalid' rescue StandardError raise TokenError, 'Unable to process message' end end |
#encode64 ⇒ Object
27 28 29 |
# File 'lib/paseto/local.rb', line 27 def encode64 Paseto.encode64(@key) end |
#encrypt(message, footer = EMPTY_FOOTER) ⇒ Object
31 32 33 34 35 36 37 38 39 |
# File 'lib/paseto/local.rb', line 31 def encrypt(, = EMPTY_FOOTER) # Make a nonce: A single-use value never repeated under the same key nonce = generate_nonce() # Encrypt a message with the AEAD ciphertext = @aead.encrypt(nonce, , additional_data(nonce, )) Paseto::Token.new(HEADER, nonce + ciphertext, ). end |