Skip to content

Commit

Permalink
Happy and unhappy test for hmac algo
Browse files Browse the repository at this point in the history
  • Loading branch information
anakinj committed Sep 15, 2024
1 parent 71019d7 commit 7b2c73a
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 1 deletion.
1 change: 0 additions & 1 deletion lib/jwt/jwa/hmac.rb
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,6 @@ def initialize(alg, digest)

def sign(data:, signing_key:)
signing_key ||= ''

raise_verify_error!('HMAC key expected to be a String') unless signing_key.is_a?(String)

OpenSSL::HMAC.digest(digest.new, signing_key, data)
Expand Down
22 changes: 22 additions & 0 deletions spec/jwt/jwa/hmac_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,16 @@

RSpec.describe JWT::JWA::Hmac do
let(:instance) { described_class.new('HS256', OpenSSL::Digest::SHA256) }
let(:valid_signature) { [60, 56, 87, 72, 185, 194, 150, 13, 18, 148, 76, 245, 94, 91, 201, 64, 111, 91, 167, 156, 43, 148, 41, 113, 168, 156, 137, 12, 11, 31, 58, 97].pack('C*') }
let(:hmac_secret) { 'secret_key' }

describe '#sign' do
subject { instance.sign(data: 'test', signing_key: hmac_secret) }

context 'when signing with a key' do
it { is_expected.to eq(valid_signature) }
end

# Address OpenSSL 3.0 errors with empty hmac_secret - https://github.com/jwt/ruby-jwt/issues/526
context 'when nil hmac_secret is passed' do
let(:hmac_secret) { nil }
Expand Down Expand Up @@ -103,4 +109,20 @@
end
end
end

describe '#verify' do
subject { instance.verify(data: 'test', signature: signature, verification_key: hmac_secret) }

context 'when signature is valid' do
let(:signature) { valid_signature }

it { is_expected.to be(true) }
end

context 'when signature is invalid' do
let(:signature) { [60, 56, 87, 72, 185, 194].pack('C*') }

it { is_expected.to be(false) }
end
end
end

0 comments on commit 7b2c73a

Please sign in to comment.