将 openssl public 密钥导入 C# RSACryptoServiceProvider

Import openssl public key to C# RSACryptoServiceProvider

我正在用 C++ 创建服务器端程序,程序使用 openssl 库创建 RSA public 和私钥,然后 public 通过网络为客户端分发密钥。在客户端,我编写了 C# 程序,首先获取 public 密钥,然后加密数据。但我无法将 public 密钥添加到 RSACryptoServiceProvider。

有没有办法将 RSA public 密钥导入 RSACryptoServiceProvider?

-----开始 RSA PUBLIC 密钥----- MIIBCAKCAQEAsgVkBAQPdtRtICOqWdZ0ZiMAb9UvUX0BaxANN22bL5RzTJAL+PmG QKaA61B1m0NPOjdIIXMwkaAzXOmzuNwKm2Ugb8jO15B6ovAhe73jAoltFFdi10Te zCJgT8/xLAWt1mOXCAK9vD4Pv5LMN76BF+YjEVvylQ3l87255ElZrP4UluCGj0U3 uczW8+Cqao3QoL6xSxPU9jSK0FT/OhAL312cAXYbnaiJH+wAf1kkv4ez28XAlFId MlCmh2n8YSuxk1GdOXaps8IoluDzmHeQ8vk2quQMPpFXzfCayBoPm9lVPOjOQkAH 8ClJda0Uy052N5aE0BuyX1KRxOSdRRKk9wIBAw==

-----结束 RSA PUBLIC 密钥-----

您可以使用 BouncyCastle 执行此操作,不幸的是,这是解决此问题的唯一方法之一。

PemReader reader = new PemReader(new StreamReader(File.Open(file, FileMode.Open)));
AsymmetricCipherKeyPair = (AsymmetricCipherKeyPair)reader.ReadObject();
reader.Reader.Close();

此代码未经测试,因此某些方法名称可能略有偏差。然后,您可以使用 DotNetUtilities class 中的静态方法转换为 RSACryptoServiceProvider.

这是一个示例代码,展示了如何在 c#

中将 RSA public 密钥添加到 RSACryptoServiceProvider
public 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);
}