Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create x509 certificate with openssl/makecert tool

I'm creating a x509 certificate using makecert with the following parameters:

makecert -r -pe -n "CN=Client" -ss MyApp

I want to use this certificate to encrypt and decrypt data with RSA algoritm. I look to generated certificate in windows certificate store and everything seems ok (It has a private key, public key is a RSA key with 1024 bits and so on..)

Now i use this C# code to encrypt data:

X509Store store = new X509Store("MyApp", StoreLocation.CurrentUser);
store.Open(OpenFlags.ReadOnly);
X509Certificate2Collection certs = store.Certificates.Find(X509FindType.FindBySubjectName, "Client", false);
X509Certificate2 _x509 = certs[0];

using (RSACryptoServiceProvider rsa = (RSACryptoServiceProvider)_x509.PublicKey.Key)
{
    byte[] dataToEncrypt = Encoding.UTF8.GetBytes("hello");
    _encryptedData = rsa.Encrypt(dataToEncrypt, true);
}

When executing the Encrypt method, i receive a CryptographicException with message "Bad key".

I think the code is fine. Probably i'm not creating the certificate properly. Any comments? Thanks

---------------- EDIT --------------
If anyone know how to create the certificate using OpenSsl, its also a valid answer for me.

like image 666
Zé Carlos Avatar asked Jun 09 '10 17:06

Zé Carlos


People also ask

How do I create a certificate x509?

Open cmd prompt, change directory to desktop & type command- openssl. It is a process of creating a simple x509 certificate that will be used for digital signatures. Press enter and fill in all the required information like the password for creating keys & a few personal information.

How do I create a self signed certificate with MakeCert?

To create self-signed certificates, use the Powershell Cmdlet New-SelfSignedCertificate. The MakeCert tool creates an X. 509 certificate, signed by the test root key or other specified key, that binds your name to the public part of the key pair. The certificate is saved to a file, a system certificate store, or both.

What is x509 Openssl?

The x509 command is a multi purpose certificate utility. It can be used to display certificate information, convert certificates to various forms, sign certificate requests like a "mini CA" or edit certificate trust settings. Since there are a large number of options they will split up into various sections.


1 Answers

To allow the key to be used for encryption, you should use the -sky-option. Per default ´makecert` uses the AT_SIGNATURE key specification, which will not work with encryption/decryption. Instead have it use the AT_KEYEXCHANGE specification by issuing the following command:

makecert -r -pe -n "CN=Client" -ss MyApp -sky Exchange

(Remember to delete the previous key or use another container-name).

like image 157
Rasmus Faber Avatar answered Sep 23 '22 14:09

Rasmus Faber