Class: SecureJwt::JwtTokenImpl

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

Instance Method Summary collapse

Constructor Details

#initialize(signing_key, options = {}) ⇒ JwtTokenImpl

Returns a new instance of JwtTokenImpl.



31
32
33
34
35
36
37
38
39
40
# File 'lib/secure_jwt.rb', line 31

def initialize(signing_key, options = {})
  @jwt_algorithm = options[:signing_algorithm] || DEFAULT_ALGORITHMS[:jwt]
  @jwt_algorithm = nil unless signing_key

  @signing_key = signing_key

  @data_algorithm = options[:data_algorithm] || DEFAULT_ALGORITHMS[:data]

  @master_key = options[:master_key] || SecureJwt.config.master_key || "none"
end

Instance Method Details

#decrypt(jwt_token, options = {}, &data_key_decryptor) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/secure_jwt.rb', line 63

def decrypt(jwt_token, options = {}, &data_key_decryptor)
  clear!
  unformatted_payload, header = decode_jwt jwt_token

  decrypted_data_key = decrypt_data_key header[:data_key], &data_key_decryptor rescue SecureRandom.random_bytes(12)
  
  ret = decrypt_payload unformatted_payload, {
    data_key: decrypted_data_key,
    iv: header[:iv],
    auth_tag: header[:tag],
    auth_data: options[:auth_data] || ""
  }

  first_error ? raise(first_error) : ret
end

#encrypt(payload, options = {}, &data_key_encryptor) ⇒ Object



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/secure_jwt.rb', line 42

def encrypt(payload, options = {}, &data_key_encryptor)
  clear!

  data_key = generate_data_key &data_key_encryptor
  iv = SecureRandom.random_bytes 12
  encrypted_payload, auth_tag = encrypt_payload payload, {
    key: data_key[:plain], 
    iv: iv,
    auth_data: options[:auth_data] || ""
  }

  ret = encode_jwt encrypted_payload, {
    data_key: data_key[:encrypted],
    iv: iv,
    auth_tag: auth_tag,
    expires: options[:expires]&.to_i
  }

  first_error ? raise(first_error) : ret
end