Question

I need a RSA public key encoded into DER format.

The key-pair is generated using RSACryptoServiceProvider.

What I'm looking for is the c# equivalent to the java:

PublicKey pubKey = myPair.getPublic();
byte[] keyBytes = pubKey.getEncoded();

I have tried looking into BouncyCastle but got lost so if the solution is there any pointers are welcome.

Was it helpful?

Solution

Using Bouncy Castle:

using Org.BouncyCastle.X509;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Parameters;

...

var generator = new RsaKeyPairGenerator ();
generator.Init (new KeyGenerationParameters (new SecureRandom (), 1024));
var keyPair = generator.GenerateKeyPair ();
RsaKeyParameters keyParam = (RsaKeyParameters)keyPair.Public;
var info = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo (keyParam);
RsaBytes = info.GetEncoded ();

The last three lines are the ones who take the RSA public key and export it.

OTHER TIPS

I tried to use aforementioned info.GetEncoded() but as a result, I couldn't use it to verify the signature created with the corresponding private key.

What works for me is converting it to a X509Certificate2.

private bool VerifySignature(string stringContent, string stringSignature, X509Certificate2 x509PublicKey)
{
    Int16 cbSignature = 0, cbCert = 0;
    int cbData = 0;
    CertBasicStruct sCert = new CertBasicStruct();
    var pbCert = PublicKey.RawData;
    cbCert = (Int16)pbCert.Length;

    byte[] pbData = Encoding.UTF8.GetBytes(stringContent);
    cbData = (Int16)pbData.Length;
    byte[] pbSignature = Convert.FromBase64String(Signature);
    cbSignature = (Int16)pbSignature.Length;
    var rtn = DllImportService.DecodeCertificate(pbCert, cbCert, ref sCert);
    var rtn_1 = DllImportService.VerifySignatureByCert(ref sCert, DllImportService.CKM_SHA256_RSA_PKCS, pbData, cbData, pbSignature, cbSignature);
    if (rtn_1 == 0)
    {
        LogWndAppendLine("Signature is valid.");
        return true;
    }
    else
    {
        LogWndAppendLine("Signature is invalid");
        return false;
    }
}

X509Certificate2.RawData would be what you are looking for.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top