解密数据时出错

时间:2015-05-09 04:54:51

标签: c# encryption private-key pfx

我使用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();

  }

2 个答案:

答案 0 :(得分: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);
        }
    }

答案 1 :(得分:0)

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