uruk-project / Jwt

JSON Web Token implementation for .Net & .Net Core
MIT License
80 stars 13 forks source link

Hash-Algorithm for key derivation (ECDH-ES) #580

Open inf9144 opened 6 months ago

inf9144 commented 6 months ago

Hey, i tried your library and the one from Microsoft (Microsoft.IdentityModel.JsonWebTokens) and the interoperability between both. https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 seems to state that the Hash should be calculated with SHA256

In Microsoft code it looks like this:

// JWA's spec https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 specifies SHA256, saml might be different
byte[] derivedKey = _ecdhPrivate.DeriveKeyFromHash(_ecdhPublic.PublicKey, HashAlgorithmName.SHA256, prepend, append);

In your code the hash algorithm is defined through it's encryption algorithm:

_hashAlgorithm = GetHashAlgorithm(encryptionAlgorithm);
...
 var hashAlgorithm = encryptionAlgorithm.SignatureAlgorithm.HashAlgorithm
...
exchangeHash = new ReadOnlySpan<byte>(ephemeralKey.DeriveKeyFromHash(otherPartyKey.PublicKey, _hashAlgorithm, _secretPreprend, secretAppend), 0, _keySizeInBytes);>

If you now use a combination of EcdhEsA128kw and Aes128CbcHmacSha256 it works because here SHA256 is used. But if you use a combination of EcdhEsA256kw and Aes256CbcHmacSha512 the tokens from the MS-Lib and the tokens of your lib cannot be understood by the other party, because you would use SHA512 in that case.

Who is right - who is wrong? I dont have clue but hope you have an answer to this because i would like to connect two applications using different frameworks ;-)

ycrumeyrolle commented 6 months ago

https://datatracker.ietf.org/doc/html/rfc7518#section-4.6.2 states that

the Digest Method is SHA-256.

So it looks this is a bug. I will investigate on next week.

ycrumeyrolle commented 2 months ago

@inf9144 PR #582 try to fix this issue, but there is a drawback.

When generating the ephemeral key, now the hash algorithm is forced to SHA2-256. This is fine for encryption algorithms like A128CBC-HS256 which require a key of 256 bits. For A256CBC-HS512 we generate a key with trailing zero.

@inf9144 do you know if it is the same with MSAL ?