Jwt icon indicating copy to clipboard operation
Jwt copied to clipboard

Hash-Algorithm for key derivation (ECDH-ES)

Open inf9144 opened this issue 1 year ago • 2 comments

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 ;-)

inf9144 avatar Dec 11 '23 17:12 inf9144

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 avatar Dec 11 '23 19:12 ycrumeyrolle

@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 ?

ycrumeyrolle avatar Apr 22 '24 08:04 ycrumeyrolle