我正在开发一个项目,我需要使用“公钥”来使用RSA算法加密消息。我获得了证书,我的第一个想法是使用该证书中的公钥,经过调查后我了解到我需要使用RSACryptoServiceProvider
进行加密。
我检查了msdn,我认为应该使用的方法是RSACryptoServiceProvider.ImportCspBlob(byte[] keyBlob)
。
当我尝试使用从证书导出的公钥时,我收到的错误是证书的标头数据无效。
我知道我可以将X509certificate2.PublicKey.Key
投射到RSACryptoServiceProvider
但是从我对客户的理解是,我将继续只获得公钥,而不是证书。此密钥必须保存在.xml配置文件中。
总结一下:有没有办法在只给出证书的公钥的情况下生成RSACryptoServiceProvider
?
答案 0 :(得分:0)
您可以尝试查看此示例:RSA public key encryption in C#
var publicKey = "<RSAKeyValue><Modulus>21wEnTU+mcD2w0Lfo1Gv4rtcSWsQJQTNa6gio05AOkV/Er9w3Y13Ddo5wGtjJ19402S71HUeN0vbKILLJdRSES5MHSdJPSVrOqdrll/vLXxDxWs/U0UT1c8u6k/Ogx9hTtZxYwoeYqdhDblof3E75d9n2F0Zvf6iTb4cI7j6fMs=</Modulus><Exponent>AQAB</Exponent></RSAKeyValue>";
var testData = Encoding.UTF8.GetBytes("testing");
using ( var rsa = new RSACryptoServiceProvider(1024))
{
try
{
// client encrypting data with public key issued by server
//
rsa.FromXmlString(publicKey);
var encryptedData = rsa.Encrypt(testData, true);
var base64Encrypted = Convert.ToBase64String(encryptedData);
}
finally
{
rsa.PersistKeyInCsp = false;
}
}
答案 1 :(得分:0)
你没事,遵循一个很好的典型模式。数据的发件人不需要私钥。
以下内容可能会确认您已经找到的一些代码。 我设置了接收器/解码器私钥的一行我遗漏了。 我从我在构建部署中的测试用例中获取了这个。
byte[] certBytAr; // This is the certificate as bianry in a .cer file (no private key in it - public only)
X509Certificate2 cert2 = new X509Certificate2(certBytAr);
string strToEncrypt = "Public To Private Test StackOverFlow PsudeoCode. Surfs Up at Secret Beach.";
byte[] bytArToEncrypt = Encoding.UTF8.GetBytes(strToEncrypt);
RSACryptoServiceProvider rsaEncryptor = (RSACryptoServiceProvider)cert2.PublicKey.Key;
byte[] dataNowEncryptedArray = rsaEncryptor.Encrypt(bytArToEncrypt, true);
// done - you now have encrypted bytes
//
// somewhere elxe ...
// this should decrpyt it - simulate the destination which will decrypt the data with the private key
RSACryptoServiceProvider pk = // how this is set is complicated
// set the private key in the x509 oobject we created way above
cert2.PrivateKey = pk;
RSACryptoServiceProvider rsaDecryptor = (RSACryptoServiceProvider)cert2.PrivateKey;
byte[] dataDecrypted = rsaDecryptor.Decrypt(dataNowEncryptedArray, true);
Console.WriteLine(" encrypt 1 Way Intermediate " + BitConverter.ToString(dataDecrypted));
string strDecodedFinal = Encoding.UTF8.GetString(dataDecrypted);
if (strDecodedFinal == strToEncrypt)
{
}
else
{
Console.WriteLine(" FAILURE OF ENCRYPTION ROUND TRIP IN SIMPLE TEST (Direction: Public to Private). No Surfing For You ");
}