2014-01-29 39 views
1

進出口新的加密和即時通訊不太清楚做什麼,我錯了這裏,Rijndael加密|填充是無效的不能刪除

public static byte[] EncryptData(byte[] data, string keystr) 
{ 
    if (keystr.Length > 32) 
     keystr = keystr.Substring(0, 32); 
    else 
     while (keystr.Length != 32) 
      keystr += "0"; 

    byte[] iv = Encoding.UTF8.GetBytes(SALT); 
    byte[] key = Encoding.UTF8.GetBytes(keystr); 

    using (MemoryStream memoryStream = new MemoryStream()) 
    { 
     using (RijndaelManaged rijndaelManaged = new RijndaelManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC }) 
     { 
      using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(key, iv), CryptoStreamMode.Write)) 
      { 
       cryptoStream.Write(data, 0, data.Length); 
      } 
     } 
     return memoryStream.ToArray(); 
    } 
} 

public static byte[] DecryptData(byte[] data, string keystr) 
{ 
    if (keystr.Length > 32) 
     keystr = keystr.Substring(0, 32); 
    else 
     while (keystr.Length != 32) 
      keystr += "0"; 

    byte[] iv = Encoding.UTF8.GetBytes(SALT); 
    byte[] key = Encoding.UTF8.GetBytes(keystr.ToUpper()); 

    using (MemoryStream memoryStream = new MemoryStream()) 
    { 
     using (RijndaelManaged rijndaelManaged = new RijndaelManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC }) 
     { 
      using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(key, iv), CryptoStreamMode.Write)) 
      { 
       cryptoStream.Write(data, 0, data.Length); 
      } 
     } 
     return memoryStream.ToArray(); 
    } 
} 

正如你可以看到一個字節數組和密碼IM傳遞。我確定密碼總是32個字符。

當我解密數據時,我得到了Padding is invalid and cannot be removed.

關鍵和鹽總是相同的。

回答

2

key可能會同時傳遞給兩種方法,但出於某種原因,在丟棄了更多的熵(對於更長的字符串)或填充了鍵(對於更短的字符串)之後,出於某種原因這個:

keystr.ToUpper() 

但是隻用於解密方。所以使用的密鑰是不同的。

我強烈建議您不要撥打ToUpper。其他建議可能是沒有固定的salt/IV,並且允許將iv和key作爲字節數組傳遞,而不是strings。加密自然會處理字節數組,並且將這些類似的封裝方法置於實際上鼓勵較弱加密的方法可能是一個壞主意。

+0

啊,非常感謝,從我以前的加密類愚蠢的複製粘貼錯誤。 –

相關問題