我在c ++中创建服务器端程序,程序使用openssl库创建RSA公钥和私钥,然后通过网络为客户端分发公钥。在客户端我写了c#程序首先获取公钥然后加密数据。但我无法将公钥添加到RSACryptoServiceProvider。
有没有办法将RSA公钥导入RSACryptoServiceProvider?
-----开始RSA公钥----- MIIBCAKCAQEAsgVkBAQPdtRtICOqWdZ0ZiMAb9UvUX0BaxANN22bL5RzTJAL + PMG QKaA61B1m0NPOjdIIXMwkaAzXOmzuNwKm2Ugb8jO15B6ovAhe73jAoltFFdi10Te zCJgT8 / xLAWt1mOXCAK9vD4Pv5LMN76BF + YjEVvylQ3l87255ElZrP4UluCGj0U3 uczW8 + Cqao3QoL6xSxPU9jSK0FT / OhAL312cAXYbnaiJH + wAf1kkv4ez28XAlFId MlCmh2n8YSuxk1GdOXaps8IoluDzmHeQ8vk2quQMPpFXzfCayBoPm9lVPOjOQkAH 8ClJda0Uy052N5aE0BuyX1KRxOSdRRKk9wIBAw ==
----- END RSA PUBLIC KEY -----
答案 0 :(得分:1)
您可以使用BouncyCastle执行此操作,遗憾的是,这是解决此问题的唯一方法之一。
PemReader reader = new PemReader(new StreamReader(File.Open(file, FileMode.Open)));
AsymmetricCipherKeyPair = (AsymmetricCipherKeyPair)reader.ReadObject();
reader.Reader.Close();
此代码未经过测试,因此某些方法名称可能会有点过时。然后,您可以使用DotNetUtilities
类中的静态方法转换为RSACryptoServiceProvider
。
答案 1 :(得分:1)
这是一个示例代码,演示如何在RS#
中将RSA公钥添加到RSACryptoServiceProviderpublic Stream GenerateStreamFromString(string s)
{
MemoryStream stream = new MemoryStream();
StreamWriter writer = new StreamWriter(stream);
writer.Write(s);
writer.Flush();
stream.Position = 0;
return stream;
}
string publicKey = "-----BEGIN RSA PUBLIC KEY-----\nMIIBCAKCAQEAoNhWLaL11Zy4L6Cp2IDFv2JGnPkoRnFrKTy5b23uszzbSammdIwi\n6Wtr/7Zg3wmqlwt/yhH4F6rwSysB04xvMnWjuRsw2Kz4u7FHMPlgrIObGDFqcEms\nllNTA8xSWh/+TPfxWdAN5bpUwLYo6Mizl+VStL4CtVQFS8/mQSUnCju3csfxNGlk\nPQdbwZWB/5DdswrhkUcob8wl3bCCZCz3zWzMNJFTgTEiZQr+qTtuY7ST+fmpO33r\nDJoboysiGPKUkQixKcG2s1jJJkQircAHkmiQPS6PlUapNahFNaPa3rh1zR4l5NN6\nxWudPYQhZ8VvD4C8eT2bfrUlsikAyXIX4QIBAw==\n-----END RSA PUBLIC KEY-----\n"
using (Stream stream = GenerateStreamFromString(publicKey))
{
PemReader pemReader = new PemReader(new StreamReader(stream));
AsymmetricKeyParameter publicKey = (AsymmetricKeyParameter)pemReader.ReadObject();
pemReader.Reader.Close();
Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters rsaPub = (Org.BouncyCastle.Crypto.Parameters.RsaKeyParameters)publicKey;
RSAParameters RSAKeyInfo = Org.BouncyCastle.Security.DotNetUtilities.ToRSAParameters(rsaPub);
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(2048);
RSA.ImportParameters(RSAKeyInfo);
byte[] encryptedData = RSA.Encrypt(plainText, true);
}