From 7b2c73ab9074536b78d6b34a57ceaaac12339442 Mon Sep 17 00:00:00 2001 From: Joakim Antman Date: Sun, 15 Sep 2024 14:19:59 +0300 Subject: [PATCH] Happy and unhappy test for hmac algo --- lib/jwt/jwa/hmac.rb | 1 - spec/jwt/jwa/hmac_spec.rb | 22 ++++++++++++++++++++++ 2 files changed, 22 insertions(+), 1 deletion(-) diff --git a/lib/jwt/jwa/hmac.rb b/lib/jwt/jwa/hmac.rb index 1dac71b3..f2db8faa 100644 --- a/lib/jwt/jwa/hmac.rb +++ b/lib/jwt/jwa/hmac.rb @@ -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) diff --git a/spec/jwt/jwa/hmac_spec.rb b/spec/jwt/jwa/hmac_spec.rb index 736f1e56..20504cde 100644 --- a/spec/jwt/jwa/hmac_spec.rb +++ b/spec/jwt/jwa/hmac_spec.rb @@ -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 } @@ -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