| | | 1 | | using Microsoft.IdentityModel.Tokens; |
| | | 2 | | |
| | | 3 | | namespace Kestrun.Jwt; |
| | | 4 | | |
| | | 5 | | /// <summary> |
| | | 6 | | /// Provides extension methods for the JwtAlgorithm enum. |
| | | 7 | | /// </summary> |
| | | 8 | | public static class JwtAlgorithmExtensions |
| | | 9 | | { |
| | | 10 | | /// <summary> |
| | | 11 | | /// Converts the specified <see cref="JwtAlgorithm"/> to its corresponding JWT algorithm string. |
| | | 12 | | /// </summary> |
| | | 13 | | /// <param name="alg">The JWT algorithm to convert.</param> |
| | | 14 | | /// <param name="keyByteLength">The key length in bytes, used only when <see cref="JwtAlgorithm.Auto"/> is specified |
| | | 15 | | /// <returns>The JWT algorithm string representation.</returns> |
| | | 16 | | public static string ToJwtString(this JwtAlgorithm alg, int keyByteLength = 0) |
| | | 17 | | { |
| | | 18 | | // handle the “Auto” case only for HMAC |
| | 76 | 19 | | return alg == JwtAlgorithm.Auto |
| | 76 | 20 | | ? keyByteLength switch |
| | 76 | 21 | | { |
| | 8 | 22 | | >= 64 => SecurityAlgorithms.HmacSha512, |
| | 7 | 23 | | >= 48 => SecurityAlgorithms.HmacSha384, |
| | 21 | 24 | | _ => SecurityAlgorithms.HmacSha256 |
| | 76 | 25 | | } |
| | 76 | 26 | | : alg switch |
| | 76 | 27 | | { |
| | 3 | 28 | | JwtAlgorithm.HS256 => SecurityAlgorithms.HmacSha256, |
| | 3 | 29 | | JwtAlgorithm.HS384 => SecurityAlgorithms.HmacSha384, |
| | 3 | 30 | | JwtAlgorithm.HS512 => SecurityAlgorithms.HmacSha512, |
| | 76 | 31 | | |
| | 5 | 32 | | JwtAlgorithm.RS256 => SecurityAlgorithms.RsaSha256, |
| | 3 | 33 | | JwtAlgorithm.RS384 => SecurityAlgorithms.RsaSha384, |
| | 3 | 34 | | JwtAlgorithm.RS512 => SecurityAlgorithms.RsaSha512, |
| | 76 | 35 | | |
| | 3 | 36 | | JwtAlgorithm.PS256 => SecurityAlgorithms.RsaSsaPssSha256, |
| | 3 | 37 | | JwtAlgorithm.PS384 => SecurityAlgorithms.RsaSsaPssSha384, |
| | 3 | 38 | | JwtAlgorithm.PS512 => SecurityAlgorithms.RsaSsaPssSha512, |
| | 76 | 39 | | |
| | 3 | 40 | | JwtAlgorithm.ES256 => SecurityAlgorithms.EcdsaSha256, |
| | 3 | 41 | | JwtAlgorithm.ES384 => SecurityAlgorithms.EcdsaSha384, |
| | 3 | 42 | | JwtAlgorithm.ES512 => SecurityAlgorithms.EcdsaSha512, |
| | 76 | 43 | | |
| | 2 | 44 | | _ => throw new ArgumentOutOfRangeException(nameof(alg), alg, null) |
| | 76 | 45 | | }; |
| | | 46 | | } |
| | | 47 | | } |