Skip to content

Commit

Permalink
encode hmac without key
Browse files Browse the repository at this point in the history
  • Loading branch information
JotaSe authored and excpt committed Jul 7, 2020
1 parent b9b1b03 commit 95d8d9f
Show file tree
Hide file tree
Showing 4 changed files with 42 additions and 2 deletions.
17 changes: 16 additions & 1 deletion README.md
Expand Up @@ -79,6 +79,21 @@ puts token

decoded_token = JWT.decode token, hmac_secret, true, { algorithm: 'HS256' }

# Array
# [
# {"data"=>"test"}, # payload
# {"alg"=>"HS256"} # header
# ]
puts decoded_token

# Without secret key
token = JWT.encode payload, nil, 'HS256'

# eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pVzcY2dX8JNM3LzIYeP2B1e1Wcpt1K3TWVvIYSF4x-o
puts token

decoded_token = JWT.decode token, nil, true, { algorithm: 'HS256' }

# Array
# [
# {"data"=>"test"}, # payload
Expand Down Expand Up @@ -460,7 +475,7 @@ begin
rescue JWT::JWKError
# Handle problems with the provided JWKs
rescue JWT::DecodeError
# Handle other decode related issues e.g. no kid in header, no matching public key found etc.
# Handle other decode related issues e.g. no kid in header, no matching public key found etc.
end
```

Expand Down
1 change: 1 addition & 0 deletions lib/jwt/algos/hmac.rb
Expand Up @@ -7,6 +7,7 @@ module Hmac

def sign(to_sign)
algorithm, msg, key = to_sign.values
key ||= ''
authenticator, padded_key = SecurityUtils.rbnacl_fixup(algorithm, key)
if authenticator && padded_key
authenticator.auth(padded_key, msg.encode('binary'))
Expand Down
13 changes: 12 additions & 1 deletion spec/integration/readme_examples_spec.rb
Expand Up @@ -18,7 +18,7 @@
]
end

it 'HMAC' do
it 'decodes with HMAC algorithm with secret key' do
token = JWT.encode payload, 'my$ecretK3y', 'HS256'
decoded_token = JWT.decode token, 'my$ecretK3y', false

Expand All @@ -29,6 +29,17 @@
]
end

it 'decodes with HMAC algorithm without secret key' do
token = JWT.encode payload, nil, 'HS256'
decoded_token = JWT.decode token, nil, false

expect(token).to eq 'eyJhbGciOiJIUzI1NiJ9.eyJkYXRhIjoidGVzdCJ9.pVzcY2dX8JNM3LzIYeP2B1e1Wcpt1K3TWVvIYSF4x-o'
expect(decoded_token).to eq [
{ 'data' => 'test' },
{ 'alg' => 'HS256' }
]
end

it 'RSA' do
rsa_private = OpenSSL::PKey::RSA.generate 2048
rsa_public = rsa_private.public_key
Expand Down
13 changes: 13 additions & 0 deletions spec/jwt_spec.rb
Expand Up @@ -414,4 +414,17 @@
expect(JWT.encode('Hello World', 'secret', 'HS256', { alg: 'HS256'})).to eq JWT.encode('Hello World', 'secret', 'HS256')
end
end

context 'when hmac algorithm is used without secret key' do
it 'encodes payload' do
payload = { a: 1, b: 'b'}

token = JWT.encode(payload, '', 'HS256')

expect do
token_without_secret = JWT.encode(payload, nil, 'HS256')
expect(token).to eq(token_without_secret)
end.not_to raise_error
end
end
end

0 comments on commit 95d8d9f

Please sign in to comment.