Class: Paseto::V2::Local::Key

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

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(key) ⇒ Key

Returns a new instance of Key.



18
19
20
21
# File 'lib/paseto/local.rb', line 18

def initialize(key)
  @key = key
  @aead = RbNaCl::AEAD::XChaCha20Poly1305IETF.new(key)
end

Class Method Details

.decode64(encoded_key) ⇒ Object



14
15
16
# File 'lib/paseto/local.rb', line 14

def self.decode64(encoded_key)
  new(Paseto.decode64(encoded_key))
end

.generateObject



10
11
12
# File 'lib/paseto/local.rb', line 10

def self.generate
  new(RbNaCl::Random.random_bytes(RbNaCl::AEAD::XChaCha20Poly1305IETF.key_bytes))
end

Instance Method Details

#decrypt(token, footer = nil) ⇒ Object

Raises:

  • (BadMessageError)


37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/paseto/local.rb', line 37

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.new('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
    raise TokenError, 'Unable to process message'
  end
end

#encode64Object



23
24
25
# File 'lib/paseto/local.rb', line 23

def encode64
  Paseto.encode64(@key)
end

#encrypt(message, footer = EMPTY_FOOTER) ⇒ Object



27
28
29
30
31
32
33
34
35
# File 'lib/paseto/local.rb', line 27

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