2017-01-12 29 views
1

我看到存在的有关此主题的另一个问题,但我检查每一个问题,我解决不了我的问题.. 这是我的方法来解密和其他方法来调用解密方法用所需参数:填充是无效的,不能被C#去除解密

public string Decrypt(AesOperationType operationType, byte[] criptotext, byte[] Key, byte[] initVector) 
{ 

     string plaintext = null; 

     using (Aes aesAlg = Aes.Create()) 
     { 
      aesAlg.KeySize = 128; 
      aesAlg.Key = Key; 
      aesAlg.IV = initVector; 
      if (operationType == AesOperationType.Cbc) 
      { 
       aesAlg.Mode = CipherMode.CBC; 
      } 
      else if (operationType == AesOperationType.Cfb) 
      { 
       aesAlg.Mode = CipherMode.ECB; 
      } 

      //apelam functia de decriptare 
      ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV); 

      using (MemoryStream msDecrypt = new MemoryStream(criptotext)) 

      using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)) 
      { 
       using (StreamReader srDecrypt = new StreamReader(csDecrypt)) 
       { 
        plaintext = srDecrypt.ReadToEnd(); 
       } 
      } 
     } 
     Console.WriteLine("Start decrypt for criptotext : " + BitConverter.ToString(criptotext) + "\n"); 
     Console.WriteLine("Plaintext after decrypt : " + plaintext + "\n"); 

     return plaintext; 
} 

public byte[] Encrypt_Call() 
{ 
     var key = "1212121212121212"; 
     var key_byte = Encoding.ASCII.GetBytes(key); 
     using (Aes aess = Aes.Create()) 
     { 
      var iv = aess.IV; 
      cryptdecrypt object = new cryptdecrypt(); 
      var result = object.Encrypt(AesOperationType.Cbc, "plaintext", key_byte, iv); 
      return result; 
     } 
} 

public void Decrypt_Call() 
{ 
     var key = "1212121212121212"; 
     var key_byte = Encoding.ASCII.GetBytes(key); 
     using (Aes aess = Aes.Create()) 
     { 
      var iv = aess.IV; 
      cryptdecrypt object = new cryptdecrypt(); 
      var cryptotext = Encrypt_Call(); 
      var result = object.Decrypt(AesOperationType.Cbc, cryptotext , key_byte, iv); 
     } 
} 

加密方法工作得很好,但在解密方法调用,我面对这样的错误:

Padding is invalid and cannot be removed.

我也试图把csDecrypt.FlushFinalBlock()这行之前该行:

using (StreamReader srDecrypt = new StreamReader(csDecrypt)) 

错误消失,因此我得到一个空字符串。

任何想法来解决这个问题?

+0

IV在哪里指定? – zaph

+1

您必须使用相同的密钥*和* IV进行加密和解密。看起来你可能在加密和解密方法中随机生成IV,因此它们不会相同。 – Iridium

+0

@KurokawaMasato AesOperationType是一个类,其中包含一个与Cbc,Cfb ..枚举的枚举 – Carto

回答

0

通常,无效的填充错误意味着解密失败。在这种情况下,CBC模式下IV没有被指定,所以它将是垃圾(或随机)。

或者:

  1. 指定块长度的IV(AES 16字节)。

  2. 在加密时创建一个随机IV并将其加到加密数据中。解密时,将IV关闭并用于解密。 < - 最佳选项

相关问题