【问题标题】:Find the public and private keys using RSACryptoServiceProvider in c#在 c# 中使用 RSACryptoServiceProvider 查找公钥和私钥
【发布时间】:2013-05-18 16:33:12
【问题描述】:

我有以下代码。

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();

当我使用 RSAEncrypt 方法时,它采用参数“RSAKeyInfo”(用于加密的公钥和用于解密的私钥)。

如何获取私钥和​​公钥的值,该方法用于加密和解密。

谢谢,

【问题讨论】:

    标签: c# rsa


    【解决方案1】:

    你需要使用RSA.ToXmlString

    下面的代码使用两个不同的 RSA 实例,其中包含一个包含公钥和私钥的共享字符串。只获取公钥,使用false参数,true参数将返回公钥+私钥。

    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);
    
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-05-28
      • 2012-11-19
      • 2017-04-10
      • 1970-01-01
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-06-21
      相关资源
      最近更新 更多