Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Extend RSAlgorithmFactory to support all ctors of RS256Algorithm #221

Merged
merged 8 commits into from
Oct 1, 2019
35 changes: 26 additions & 9 deletions src/JWT/Algorithms/RSAlgorithmFactory.cs
Original file line number Diff line number Diff line change
Expand Up @@ -8,31 +8,48 @@ namespace JWT.Algorithms
public sealed class RSAlgorithmFactory : HMACSHAAlgorithmFactory
{
private readonly Func<X509Certificate2> _certFactory;
private readonly Func<RS256Algorithm> _createAlgorithmMethod;

/// <summary>
/// Initializes a new instance of the <see cref="RSAlgorithmFactory"/> class
/// </summary>
/// <param name="certFactory">Func that returns <see cref="X509Certificate2" /> which will be used to instantiate <see cref="RS256Algorithm" /></param>
public RSAlgorithmFactory(Func<X509Certificate2> certFactory) =>
public RSAlgorithmFactory(Func<X509Certificate2> certFactory)
abatishchev marked this conversation as resolved.
Show resolved Hide resolved
{
_certFactory = certFactory;
_createAlgorithmMethod = CreateWithCertificate;
}

/// <summary>
/// Initializes a new instance of the <see cref="RSAlgorithmFactory"/> class
/// </summary>
/// <param name="publicKey">The RSA service provider which will be used to instantiate <see cref="RS256Algorithm" /></param>
public RSAlgorithmFactory(RSACryptoServiceProvider publicKey) =>
abatishchev marked this conversation as resolved.
Show resolved Hide resolved
_createAlgorithmMethod = () => new RS256Algorithm(publicKey);


/// <inheritdoc />
public override IJwtAlgorithm Create(JwtHashAlgorithm algorithm)
{
switch (algorithm)
{
case JwtHashAlgorithm.RS256:
{
var certificate = _certFactory();
#if NETSTANDARD1_3
return new RS256Algorithm((RSACryptoServiceProvider)certificate.GetRSAPublicKey(), certificate.GetRSAPrivateKey());
#else
return new RS256Algorithm((RSACryptoServiceProvider)certificate.PublicKey.Key, (RSA)certificate.PrivateKey);
#endif
}
{
return _createAlgorithmMethod();
}
default:
throw new NotSupportedException($"For algorithm {Enum.GetName(typeof(JwtHashAlgorithm), algorithm)} please use the appropriate factory by implementing {nameof(IAlgorithmFactory)}");
}
}

private RS256Algorithm CreateWithCertificate()
{
var certificate = _certFactory();
#if NETSTANDARD1_3
return new RS256Algorithm((RSACryptoServiceProvider)certificate.GetRSAPublicKey(), certificate.GetRSAPrivateKey());
#else
return new RS256Algorithm((RSACryptoServiceProvider)certificate.PublicKey.Key, (RSA)certificate.PrivateKey);
#endif
}
}
}