2016-05-03 21 views
0

我已經實現了代碼加密和解密方法。輸入字符串值傳遞給加密方法並獲取存儲在xml文件中的加密值。在獲得加密值後,使用Decrypt Method讀取xml文件來讀取值。在罕見的情況下,我收到錯誤(加密的輸入值不正確並且解密輸出值)。我該如何解決這個問題。請分享給我。 下面的示例代碼使用c#中的rijindeal algorthm加密解密時丟失的字符

public static string Decrypt(string cipherText) 
{ 
    try 
    {     


     string incoming = cipherText.Replace('_', '/').Replace('-', '+'); 
     switch (cipherText.Length % 4) 
     { 
      case 2: incoming += "=="; break; 
      case 3: incoming += "="; break; 
     } 
     byte[] initVectorBytes = Encoding.ASCII.GetBytes(initVector); 
     byte[] cipherTextBytes = Convert.FromBase64String(incoming); 
     PasswordDeriveBytes password = new PasswordDeriveBytes(passPhrase, null); 
     byte[] keyBytes = password.GetBytes(keysize/8); 
     RijndaelManaged symmetricKey = new RijndaelManaged(); 
     symmetricKey.Mode = CipherMode.CBC; 
     ICryptoTransform decryptor = symmetricKey.CreateDecryptor(keyBytes, initVectorBytes); 
     MemoryStream memoryStream = new MemoryStream(cipherTextBytes); 
     CryptoStream cryptoStream = new CryptoStream(memoryStream, decryptor, CryptoStreamMode.Read); 
     byte[] plainTextBytes = new byte[cipherTextBytes.Length]; 
     int decryptedByteCount = cryptoStream.Read(plainTextBytes, 0, plainTextBytes.Length); 
     memoryStream.Close(); 
     cryptoStream.Close(); 
     return Encoding.UTF8.GetString(plainTextBytes, 0, decryptedByteCount); 
    } 
    catch (Exception ex) 
    {     

      return "Exception"; 
    } 
} 
+0

變化ASCII編碼到UTF8編碼。使用刪除不可打印字符的Ascii編碼。我懷疑偶爾加密會產生Ascii編碼消除的字符。 – jdweng

回答

0

您手動添加填充到數據的末端,如果不扭轉的解密那就不是工作(它必須爲你做的decripting後加入之前)。

但是,該填充是不必要的,AES256需要填充數據,是的,但cryptostream會爲你做,所以如果你刪除所有填充的東西它將工作。

+0

我加密方法 – somu

0

使用TRIM()函數,並刪除所有的空格

這個問題時,有白色的空間,可能會發生。 使用修剪()函數來刪除空格。

例子 - :cipherText.Trim()

+0

感謝這封郵件。但我已經嘗試過這種方式 – somu

相關問題