Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if private/public key pair match using (.NET / BouncyCastle)?

I have AsymmetricKeyParameter object for private and public key. What is the easiest way to see if they match?

I am trying to encrypt some text (private key) and decrypt some text (public key). So far I have not been able to do that but it seems like the wrong approach.

Update: Here is sample code:

X509Certificate2 c = new X509Certificate2(@"certificate.cer");
byte[] privateKeyData = System.IO.File.ReadAllBytes(@"private.key");
Org.BouncyCastle.X509.X509Certificate cert = DotNetUtilities.FromX509Certificate(c);


RsaPrivateCrtKeyParameters privateKey = (RsaPrivateCrtKeyParameters)PrivateKeyFactory.CreateKey(privateKeyData);
RsaKeyParameters publicKey = (RsaKeyParameters)cert.GetPublicKey();

if (privateKey.Modulus.Equals(publicKey.Modulus) && publicKey.Exponent.Equals(privateKey.PublicExponent)) 
{
     //they match
}
like image 749
Evgeni Petrov Avatar asked Jan 18 '12 09:01

Evgeni Petrov


1 Answers

The simplest way to check whether a private key and a public key match is to encrypt a piece of data with the public key and see if you can decrypt it with the private key - or alternatively to sign a piece of data with the private key and see if you can verify it with the public key.

If the keys are RSA keys, you can cast the public key to Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters and the private key to Org.BouncyCastle.Crypto.Parameters.RsaPrivateCrtKeyParameters and verify that the Modulus is the same and that Exponent of the public key is equal to PublicExponent of the private key. If you want to get really fancy, you could also validate all the remaining parameters of the private key (follow PKCS#1 section 3.2).

like image 111
Rasmus Faber Avatar answered Sep 21 '22 02:09

Rasmus Faber