开发者

Importing an openssl-created self-signed cert into a X509Certificate2 (Mono): Can encrypt, can't decrypt

I'm in Fedora 14, MonoDevelop 2.4, Mono 2.6.7. I generated my self-signed cert thusly:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mysitename.key -out mysitename.crt

Then I'm playing with encryption and decryption in C# thusly. I'm selecting the .crt file. The problem is that the X509Certificate2 that's being created has no private key! Hence, the encrypt operation goes well, and de开发者_如何学运维crypt bombs.

I'm probably running the openssl command wrong. Or is it some subtlety in creating the X509Certificate2 object?

protected virtual void OnBtCertClicked (object sender, System.EventArgs e)
{
    try
    {
        if (myCert == null)
        {
            myCert = new X509Certificate2(fchCert.Filename);
        }

        RSACryptoServiceProvider pubKey = (RSACryptoServiceProvider)myCert.PublicKey.Key;
        byte[] myBlob = UTF8Encoding.Default.GetBytes(tbDisplay.Buffer.Text);
        byte[] myEncryptedBlob = pubKey.Encrypt(myBlob, false);
        tbDisplay.Buffer.Text = System.Convert.ToBase64String(myEncryptedBlob, Base64FormattingOptions.InsertLineBreaks);
    }
    catch (Exception excp)
    {
        tbDisplay.Buffer.Text = excp.GetType().ToString() + "\n\n" + excp.ToString();
    }
}

protected virtual void OnBtCertDecClicked (object sender, System.EventArgs e)
{
    try
    {
        if (myCert == null)
        {
            myCert = new X509Certificate2(fchCert.Filename);
        }

        if (!myCert.HasPrivateKey)
            throw new CryptographicException("Certificate has no private key");

        RSACryptoServiceProvider privKey = (RSACryptoServiceProvider)myCert.PrivateKey;
        byte[] myEncryptedBlob = System.Convert.FromBase64String(tbDisplay.Buffer.Text);
        byte[] myBlob = privKey.Decrypt(myEncryptedBlob, false);
        tbDisplay.Buffer.Text = UTF8Encoding.UTF8.GetString(myBlob);
    }
    catch (Exception excp)
    {
        tbDisplay.Buffer.Text = excp.GetType().ToString() + "\n\n" + excp.ToString();
    }
}


Create a PKCS#12 certificate:

openssl pkcs12 -export -in yourcert.crt -inkey yourprivkey.key -out newcert.p12

It should now contain the private key.


A certificate only contains the public key. The OpenSSL command you use creates the key in the file mysitename.key. You have to load the key file separately. AFAIR the generated key file should contain the base64 encoded RSA private key in PKCS#8 format- encapsulated by some text strings (BEGIN/END RSA PRIVATE KEY).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜