2

我在 Fedora 14、MonoDevelop 2.4、Mono 2.6.7 中。我因此生成了我的自签名证书:

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

然后我正在玩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();
    }
}
4

2 回答 2

7

创建 PKCS#12 证书:

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

它现在应该包含私钥。

于 2011-02-05T04:00:40.563 回答
1

证书仅包含公钥。您使用的 OpenSSL 命令会在文件mysitename.key中创建密钥。您必须单独加载密钥文件。AFAIR 生成的密钥文件应包含 PKCS#8 格式的 base64 编码 RSA 私钥 - 由一些文本字符串 ( BEGIN/END RSA PRIVATE KEY ) 封装。

于 2010-12-08T08:44:40.607 回答