仅使用公钥创建AsymmetricCipherKeyPair

我有点问题。 我正在尝试编写客户端 – 服务器应用程序(更多是POC),客户端从服务器请求公钥,然后服务器生成此密钥AsymmetricCipherKeyPair ,具有以下内容

  private static AsymmetricCipherKeyPair GenerateKeyPair() { RsaKeyPairGenerator g = new RsaKeyPairGenerator(); g.Init(new KeyGenerationParameters(new SecureRandom(), 1024)); var pair = g.GenerateKeyPair(); return pair; } 

这生成正确,可以正确加密和加密(在服务器端,但这失败了目的)

然后我将一个序列化的公钥发送给客户端

  private static byte[] SerialisePublic(AsymmetricCipherKeyPair keypair) { SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfoFactory.CreateSubjectPublicKeyInfo(keypair.Public); byte[] serializedPublicBytes = publicKeyInfo.ToAsn1Object().GetDerEncoded(); return serializedPublicBytes; } private static void SendBytes(TcpClient client, byte[] send) { NetworkStream stream = client.GetStream(); stream.Write(send, 0, send.Length); stream.Flush(); } 

但是现在,当我尝试初始化其他端的keypair对时,我需要一个私钥(这也违背了目的)

我尝试了以下内容

  static string EncryptString(string key, string message) { string res = ""; using (var rsa = new RSACryptoServiceProvider(128)) { try { rsa.FromXmlString(string.Format("{0}", key)); byte[] b = Encoding.ASCII.GetBytes(message); var encryptedData = rsa.Encrypt(b, true); var base64Encrypted = Convert.ToBase64String(encryptedData); res = base64Encrypted; } catch (Exception ex) { } finally { rsa.PersistKeyInCsp = false; } return res; } } 

(在没有密钥对的情况下,我以为我可以破解它)

但是,由于这不包含加密所需信息的近一半,因此很难实现。

如果可能的话,我想继续使用Bouncy Castle,但我愿意接受建议。

提前致谢。


UPDATE

客户端和服务器都是用C#编写的


更新2(谢谢安德鲁)

这将使用服务器提供的公钥初始化RsaEngine (或者至少是应该)(这不起作用,不要使用它)

  static byte[] EncryptBytes(byte[] key, byte[] message) { byte[] res = null; AsymmetricKeyParameter ic = (AsymmetricKeyParameter)PublicKeyFactory.CreateKey(key); RsaEngine e = new RsaEngine(); e.Init(true, ic); res = e.ProcessBlock(message, 0, message.Length); return res; } 

更新3

所以这不起作用, PublicKeyFactory似乎不喜欢返回的键抛出: Unknown object in GetInstance: Org.BouncyCastle.Asn1.DerApplicationSpecific

我认为这可能是服务器端的序列化问题,然后是客户端的反序列化问题。

因此,当客户端连接到服务器时,可能会使用CryptoStream来传输公钥和其他身份validation(密码短信,秘密敲门或笑话)。

敬请关注