forked from jwt/ruby-jwt
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsignature.rb
More file actions
50 lines (46 loc) · 1.3 KB
/
signature.rb
File metadata and controls
50 lines (46 loc) · 1.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# frozen_string_literal: true
require 'jwt/security_utils'
require 'openssl'
require 'jwt/algos/hmac'
require 'jwt/algos/eddsa'
require 'jwt/algos/ecdsa'
require 'jwt/algos/rsa'
require 'jwt/algos/unsupported'
begin
require 'rbnacl'
rescue LoadError => e
abort(e.message) if defined?(RbNaCl)
end
# JWT::Signature module
module JWT
# Signature logic for JWT
module Signature
extend self
ALGOS = [
Algos::Hmac,
Algos::Ecdsa,
Algos::Rsa,
Algos::Eddsa,
Algos::Unsupported
].freeze
ToSign = Struct.new(:algorithm, :msg, :key)
ToVerify = Struct.new(:algorithm, :public_key, :signing_input, :signature)
def sign(algorithm, msg, key)
algo = ALGOS.find do |alg|
alg.const_get(:SUPPORTED).include? algorithm
end
algo.sign ToSign.new(algorithm, msg, key)
end
def verify(algorithm, key, signing_input, signature)
algo = ALGOS.find do |alg|
alg.const_get(:SUPPORTED).include? algorithm
end
verified = algo.verify(ToVerify.new(algorithm, key, signing_input, signature))
raise(JWT::VerificationError, 'Signature verification raised') unless verified
rescue OpenSSL::PKey::PKeyError
raise JWT::VerificationError, 'Signature verification raised'
ensure
OpenSSL.errors.clear
end
end
end