我在 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();
}
}