Find the public and private keys using RSACryptoServiceProvider in c#

匿名 (未验证) 提交于 2019-12-03 08:50:26

问题:

I have the following code.

RSACryptoServiceProvider RSA = new RSACryptoServiceProvider(); //Save the public key information to an RSAParameters structure. RSAParameters RSAKeyInfo = RSA.ExportParameters(true);  byte[] toEncryptData = Encoding.ASCII.GetBytes("hello world"); byte[] encryptedRSA = RSAEncrypt(toEncryptData, RSAKeyInfo, false); string EncryptedResult = System.Text.Encoding.Default.GetString(encryptedRSA);  byte[] decryptedRSA = RSADecrypt(encryptedRSA, RSAKeyInfo, false); string originalResult = System.Text.Encoding.Default.GetString(decryptedRSA); return userDetails.ToString(); 

When I use the RSAEncrypt method it takes the parameter "RSAKeyInfo" (Public key for encryption and Private key for decryption).

How can I get the value of private and public keys, which this method used for encryption and decryption.

Thanks,

回答1:

You need to use RSA.ToXmlString

Code below uses two different RSA instances with a shared string containing public and private keys. To obtain only public key, use a false parameters, true parameter will return public + private key.

class Program {     public static void Main(string[] args)     {         //Encrypt and export public and private keys         var rsa1 = new RSACryptoServiceProvider();         string publicPrivateXml = rsa1.ToXmlString(true);   // <<<<<<< HERE         byte[] toEncryptData = Encoding.ASCII.GetBytes("hello world");         byte[] encryptedRSA = rsa1.Encrypt(toEncryptData, false);         string EncryptedResult = Encoding.Default.GetString(encryptedRSA);          //Decrypt using exported keys         var rsa2 = new RSACryptoServiceProvider();         rsa2.FromXmlString(publicPrivateXml);             byte[] decryptedRSA = rsa2.Decrypt(encryptedRSA, false);         string originalResult = Encoding.Default.GetString(decryptedRSA);      } } 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!