【问题标题】:error when decrypt data解密数据时出错
【发布时间】:2015-05-09 04:54:50
【问题描述】:

我使用 RSA 加密来 Enc/Dec 消息 加密运行良好,但在解密时我在这一行出现此错误。

rsa.Decrypt(dataByte, false);

说明:在执行当前 Web 请求期间发生未处理的异常。请查看堆栈跟踪以获取有关错误及其源自代码的位置的更多信息。

异常详情:System.Security.Cryptography.CryptographicException:参数不正确。

代码是:

string en=   x509_Encrypt(Current_Record_Hmac, PFXFile, s_pass);
string de=  ByteToString( X509_Decrypt(en, PFXFile, s_pass));


public static byte[] X509_Decrypt(string data, string certificateFile, string password)
 {

      var dataArray = data.Split(new char[] { ',' });
      byte[] dataByte = new byte[dataArray.Length];
      for (int i = 0; i < dataArray.Length; i++)
      {
          dataByte[i] = Convert.ToByte(dataArray[i]);
      }


      X509Certificate2 cert = new X509Certificate2(certificateFile, password);
      var rsa = new RSACryptoServiceProvider();    
      var x509_privateKey = cert.PrivateKey;
      string pri = x509_privateKey.ToString();   
      string x509_privateKey_ToString = x509_privateKey.ToString();   
      string X509_publicKey = ByteToString(cert.GetPublicKey());
      x509_privateKey_ToString = rsa.ToXmlString(true);
      X509_publicKey = rsa.ToXmlString(false);       
      rsa.FromXmlString(x509_privateKey_ToString);
      var decryptedByte = rsa.Decrypt(dataByte, false);
      return (decryptedByte);                
  }

  public string x509_Encrypt(string input, string certificateFile, string password)
  {


      var dataToEncrypt = _encoder.GetBytes(input);           
      var encoding = new System.Text.ASCIIEncoding();

      X509Certificate2 cert = new X509Certificate2(certificateFile, password);
      var x509_privateKey = cert.PrivateKey;
      string x509_privateKey_ToString = ByteToString(encoding.GetBytes(x509_privateKey.ToString()));

      string X509_publicKey = ByteToString(cert.GetPublicKey());


     //Encrypting the text using the public key
      RSACryptoServiceProvider cipher = new RSACryptoServiceProvider();
      x509_privateKey_ToString = cipher.ToXmlString(true);
      X509_publicKey = cipher.ToXmlString(false);      
      cipher.FromXmlString(X509_publicKey);

     var encryptedByteArray = cipher.Encrypt(dataToEncrypt, false).ToArray();
     var length = encryptedByteArray.Count();
     var item = 0;
     var sb = new StringBuilder();
     foreach (var x in encryptedByteArray)
     {
         item++;
         sb.Append(x);

         if (item < length)
             sb.Append(",");
     }

     return sb.ToString();

  }

【问题讨论】:

    标签: c# encryption private-key pfx


    【解决方案1】:

    试试这个解密方法:

        public string X509_Decrypt(string inputString, string pathToCertFile, string password)
        {
            if (inputString == null)
            {
                return null;
            }
    
            X509Certificate2 certificate = new X509Certificate2(pathToCertFile, password, X509KeyStorageFlags.MachineKeySet);
    
            try
            {
                var cryptoProvider = (RSACryptoServiceProvider)certificate.PrivateKey;
                int dwKeySize = cryptoProvider.KeySize;
                int blockSize = ((dwKeySize / 8) % 3 != 0) ? (((dwKeySize / 8) / 3) * 4) + 4 : ((dwKeySize / 8) / 3) * 4;
                int iterations = inputString.Length / blockSize;
    
                var arrayList = new ArrayList();
                for (int i = 0; i < iterations; i++)
                {
                    byte[] encryptedBytes = Convert.FromBase64String(
                        inputString.Substring(blockSize * i, blockSize));
    
                    Array.Reverse(encryptedBytes);
                    arrayList.AddRange(cryptoProvider.Decrypt(encryptedBytes, true));
                }
    
                return Encoding.UTF32.GetString(arrayList.ToArray(Type.GetType("System.Byte")) as byte[]);
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }
    

    并为您的加密消息尝试这个:

        public string X509_Encrypt(string inputString, string pathToCertFile, string password)
        {
            if (inputString == null)
            {
                return null;
            }
    
            X509Certificate2 certificate = new X509Certificate2(pathToCertFile, password, X509KeyStorageFlags.MachineKeySet);
    
            try
            {
                // TODO: Add Proper Exception Handlers
                var rsaCryptoServiceProvider = (RSACryptoServiceProvider)certificate.PublicKey.Key;
    
                int keySize = rsaCryptoServiceProvider.KeySize / 8;
                byte[] bytes = Encoding.UTF32.GetBytes(inputString);
                int maxLength = keySize - 42;
                int dataLength = bytes.Length;
                int iterations = dataLength / maxLength;
    
                var stringBuilder = new StringBuilder();
                for (int i = 0; i <= iterations; i++)
                {
                    var tempBytes = new byte[ (dataLength - maxLength * i > maxLength) ? maxLength : dataLength - maxLength * i];
    
                    Buffer.BlockCopy(bytes, maxLength * i, tempBytes, 0, tempBytes.Length);
                    byte[] encryptedBytes = rsaCryptoServiceProvider.Encrypt(tempBytes, true);
                    Array.Reverse(encryptedBytes);
                    stringBuilder.Append(Convert.ToBase64String(encryptedBytes));
                }
                return stringBuilder.ToString();
            }
            catch (Exception ex)
            {
                throw new SystemException(ex.Message);
            }
        }
    

    【讨论】:

      【解决方案2】:

      您不能像这样将字节转换为字符。如果要将密文作为字符串传输,则需要在解密前使用base 64编码和解码等编码。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-01-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多