Created
April 23, 2019 09:12
-
-
Save adnan-kamili/14b40d754205c216f3658df0144de6f6 to your computer and use it in GitHub Desktop.
Asp.Net Core + RSA PEM File
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System.IO; | |
using System.Security.Cryptography; | |
using Microsoft.IdentityModel.Tokens; | |
using Org.BouncyCastle.Crypto; | |
using Org.BouncyCastle.Crypto.Parameters; | |
using Org.BouncyCastle.OpenSsl; | |
using Org.BouncyCastle.Security; | |
using Org.BouncyCastle.Asn1.Pkcs; | |
namespace MyWebApi.Services | |
{ | |
public class RsaPemService | |
{ | |
public static RsaSecurityKey PrivateKeyFromPem(string keyPairPem, string passphrase) | |
{ | |
PemReader pemReader = new PemReader(new StringReader(keyPairPem), new PasswordFinder(passphrase)); | |
AsymmetricCipherKeyPair keyPair = (AsymmetricCipherKeyPair)pemReader.ReadObject(); | |
RsaPrivateCrtKeyParameters privateKeyParameters = (RsaPrivateCrtKeyParameters)keyPair.Private; | |
RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(privateKeyParameters); | |
return new RsaSecurityKey(rsaParameters); | |
} | |
public static RsaSecurityKey PublicKeyFromPem(string publicKeyPem) | |
{ | |
PemReader pemReader = new PemReader(new StringReader(publicKeyPem)); | |
RsaKeyParameters publicKeyParameters = (RsaKeyParameters)pemReader.ReadObject(); | |
RSAParameters rsaParameters = DotNetUtilities.ToRSAParameters(publicKeyParameters); | |
return new RsaSecurityKey(rsaParameters); | |
} | |
} | |
class PasswordFinder : IPasswordFinder | |
{ | |
private string _password; | |
public PasswordFinder(string password) | |
{ | |
this._password = password; | |
} | |
public char[] GetPassword() | |
{ | |
return _password.ToCharArray(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment