【问题标题】:C# Problem encrypting using RSA使用 RSA 加密的 C# 问题
【发布时间】:2026-02-02 15:00:01
【问题描述】:

我正在使用我从 MSDN 中提取的这个功能

static public byte[] RSAEncrypt(byte[] DataToEncrypt, RSAParameters RSAKeyInfo, bool DoOAEPPadding)
        {
            try
            {
                byte[] encryptedData;
                //Create a new instance of RSACryptoServiceProvider.
                using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
                {

                    //Import the RSA Key information. This only needs
                    //toinclude the public key information.
                    RSA.ImportParameters(RSAKeyInfo);

                    //Encrypt the passed byte array and specify OAEP padding.  
                    //OAEP padding is only available on Microsoft Windows XP or
                    //later.  
                    encryptedData = RSA.Encrypt(DataToEncrypt, DoOAEPPadding);
                }
                return encryptedData;
            }
            //Catch and display a CryptographicException  
            //to the console.
            catch (CryptographicException e)
            {
                Console.WriteLine(e.Message);

                return null;
            }

        }

我从这里调用方法:

 using (RSACryptoServiceProvider RSA = new RSACryptoServiceProvider())
            {

                //Pass the data to ENCRYPT, the public key information 
                //(using RSACryptoServiceProvider.ExportParameters(false),
                //and a boolean flag specifying no OAEP padding.
                encryptedData = RSAEncrypt(dataToEncrypt, RSA.ExportParameters(false), false);

但我收到此错误消息:

Key not valid for use in specified state.

有什么想法吗?

【问题讨论】:

    标签: c# rsa


    【解决方案1】:

    代码运行良好!!我试过了,我认为你可能在解密时遇到问题,因为你应该使用相同的密钥

    【讨论】:

      【解决方案2】:

      不幸的是,我不知道您的 Rsa 问题,但您可能想从我使用了很长时间的 here 尝试这个。

      public static string Encrypt(this string stringToEncrypt, string key)
              {
                  if (string.IsNullOrEmpty(stringToEncrypt))
                  {
                      throw new ArgumentException("An empty string value cannot be encrypted.");
                  }
      
                  if (string.IsNullOrEmpty(key))
                  {
                      throw new ArgumentException("Cannot encrypt using an empty key. Please supply an encryption key.");
                  }
      
                  System.Security.Cryptography.CspParameters cspp = new System.Security.Cryptography.CspParameters();
                  cspp.KeyContainerName = key;
      
                  System.Security.Cryptography.RSACryptoServiceProvider rsa = new System.Security.Cryptography.RSACryptoServiceProvider(cspp);
                  rsa.PersistKeyInCsp = true;
      
                  byte[] bytes = rsa.Encrypt(System.Text.UTF8Encoding.UTF8.GetBytes(stringToEncrypt), true);
      
                  return BitConverter.ToString(bytes);
              }
      

      您还可以在那里找到解密扩展。我希望它会有所帮助。

      【讨论】: