将openssl创建的自签名证书导入X509Certificate2(Mono):可以加密,无法解密

JCC*_*CyC 2 c# mono openssl rsa x509certificate2

我在Fedora 14,MonoDevelop 2.4,Mono 2.6.7.我这样生成了我的自签名证书:

openssl req -x509 -nodes -days 365 -newkey rsa:2048 -keyout mysitename.key -out mysitename.crt
Run Code Online (Sandbox Code Playgroud)

然后我在C#中使用加密和解密.我正在选择.crt文件.问题是,X509Certificate2正在创建的没有私钥!因此,加密操作顺利进行,并解密炸弹.

我可能错误地运行openssl命令.或者在创建X509Certificate2对象时有些微妙吗?

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();
    }
}
Run Code Online (Sandbox Code Playgroud)

Pet*_*y B 7

创建PKCS#12证书:

openssl pkcs12 -export -in yourcert.crt -inkey yourprivkey.key -out newcert.p12
Run Code Online (Sandbox Code Playgroud)

它现在应该包含私钥.