Skip to content

Instantly share code, notes, and snippets.

@adnan-kamili
Created April 23, 2019 09:12
Show Gist options
  • Save adnan-kamili/14b40d754205c216f3658df0144de6f6 to your computer and use it in GitHub Desktop.
Save adnan-kamili/14b40d754205c216f3658df0144de6f6 to your computer and use it in GitHub Desktop.
Asp.Net Core + RSA PEM File
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