class Paseto::V2::Local::Key

Encryption key

Public Class Methods

decode64(encoded_key) click to toggle source
# File lib/paseto/local.rb, line 18
def self.decode64(encoded_key)
  new(Paseto.decode64(encoded_key))
end
decode_hex(encoded_key) click to toggle source
# File lib/paseto/local.rb, line 22
def self.decode_hex(encoded_key)
  new(Paseto.decode_hex(encoded_key))
end
generate() click to toggle source
# File lib/paseto/local.rb, line 14
def self.generate
  new(RbNaCl::Random.random_bytes(RbNaCl::AEAD::XChaCha20Poly1305IETF.key_bytes))
end
new(key) click to toggle source
# File lib/paseto/local.rb, line 26
def initialize(key)
  @key = key
  @aead = RbNaCl::AEAD::XChaCha20Poly1305IETF.new(key)
end

Public Instance Methods

decrypt(token, footer = nil) click to toggle source
# File lib/paseto/local.rb, line 49
def decrypt(token, footer = nil)
  footer ||= token.footer if token.is_a? Paseto::Token
  footer ||= EMPTY_FOOTER

  parsed = Paseto.verify_token(token, HEADER, footer)

  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, footer)
    @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() click to toggle source
# File lib/paseto/local.rb, line 31
def encode64
  Paseto.encode64(@key)
end
encode_hex() click to toggle source
# File lib/paseto/local.rb, line 35
def encode_hex
  Paseto.encode_hex(@key)
end
encrypt(message, footer = EMPTY_FOOTER) click to toggle source
# File lib/paseto/local.rb, line 39
def encrypt(message, footer = EMPTY_FOOTER)
  # Make a nonce: A single-use value never repeated under the same key
  nonce = generate_nonce(message)

  # Encrypt a message with the AEAD
  ciphertext = @aead.encrypt(nonce, message, additional_data(nonce, footer))

  Paseto::Token.new(HEADER, nonce + ciphertext, footer).to_message
end

Private Instance Methods

additional_data(nonce, footer) click to toggle source
# File lib/paseto/local.rb, line 84
def additional_data(nonce, footer)
  Paseto.pre_auth_encode(HEADER + '.', nonce, footer)
end
generate_nonce(message) click to toggle source
# File lib/paseto/local.rb, line 78
def generate_nonce(message)
  RbNaCl::Hash::Blake2b.digest(message,
                               key: generate_nonce_key,
                               digest_size: NONCE_BYTES)
end
generate_nonce_key() click to toggle source
# File lib/paseto/local.rb, line 74
def generate_nonce_key
  RbNaCl::Random.random_bytes(NONCE_BYTES)
end