Module: JWT::SecurityUtils

Defined in:
lib/jwt/security_utils.rb

Overview

Class Method Summary collapse

Class Method Details

.asn1_to_raw(signature, public_key) ⇒ Object



29
30
31
32
# File 'lib/jwt/security_utils.rb', line 29

def asn1_to_raw(signature, public_key)
  byte_size = (public_key.group.degree + 7) / 8
  OpenSSL::ASN1.decode(signature).value.map { |value| value.value.to_s(2).rjust(byte_size, "\x00") }.join
end

.raw_to_asn1(signature, private_key) ⇒ Object



34
35
36
37
38
39
# File 'lib/jwt/security_utils.rb', line 34

def raw_to_asn1(signature, private_key)
  byte_size = (private_key.group.degree + 7) / 8
  sig_bytes = signature[0..(byte_size - 1)]
  sig_char = signature[byte_size..-1] || ''
  OpenSSL::ASN1::Sequence.new([sig_bytes, sig_char].map { |int| OpenSSL::ASN1::Integer.new(OpenSSL::BN.new(int, 2)) }).to_der
end

.rbnacl_fixup(algorithm, key) ⇒ Object



41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
# File 'lib/jwt/security_utils.rb', line 41

def rbnacl_fixup(algorithm, key)
  algorithm = algorithm.sub('HS', 'SHA').to_sym

  return [] unless defined?(RbNaCl) && RbNaCl::HMAC.constants(false).include?(algorithm)

  authenticator = RbNaCl::HMAC.const_get(algorithm)

  # Fall back to OpenSSL for keys larger than 32 bytes.
  return [] if key.bytesize > authenticator.key_bytes

  [
    authenticator,
    key.bytes.fill(0, key.bytesize...authenticator.key_bytes).pack('C*')
  ]
end

.secure_compare(left, right) ⇒ Object



8
9
10
11
12
13
14
15
16
17
# File 'lib/jwt/security_utils.rb', line 8

def secure_compare(left, right)
  left_bytesize = left.bytesize

  return false unless left_bytesize == right.bytesize

  unpacked_left = left.unpack "C#{left_bytesize}"
  result = 0
  right.each_byte { |byte| result |= byte ^ unpacked_left.shift }
  result.zero?
end

.verify_ps(algorithm, public_key, signing_input, signature) ⇒ Object



23
24
25
26
27
# File 'lib/jwt/security_utils.rb', line 23

def verify_ps(algorithm, public_key, signing_input, signature)
  formatted_algorithm = algorithm.sub('PS', 'sha')

  public_key.verify_pss(formatted_algorithm, signature, signing_input, salt_length: :auto, mgf1_hash: formatted_algorithm)
end

.verify_rsa(algorithm, public_key, signing_input, signature) ⇒ Object



19
20
21
# File 'lib/jwt/security_utils.rb', line 19

def verify_rsa(algorithm, public_key, signing_input, signature)
  public_key.verify(OpenSSL::Digest.new(algorithm.sub('RS', 'sha')), signature, signing_input)
end