2011-03-25 16 views
1

我使用私鑰和以下函數對字符串進行加密和解密。 所以我使用加密函數對字符串進行加密,並使用解密函數對加密的字符串進行解密。 如果有人可以更改加密的字符串,然後使用解密函數進行解密,則解密的字符串在加密前不等於純文本。 我想知道在加密之前如何檢查解密的字符串是否等於純文本?如何檢查加密字符串的完整性,然後轉換爲Base64?

public string Encrypt(string plainText, string password) 
    { 
     GenerateKey(password); 
     return Encrypt(plainText); 
    } 
    public string Encrypt(string plainText) 
    { 
     if (Key == null) 
     { 
      throw new InvalidOperationException("Password must be provided or set."); 
     } 
     byte[] data = new UnicodeEncoding().GetBytes(plainText); 
     RijndaelManaged crypto = new RijndaelManaged(); 
     ICryptoTransform encryptor = crypto.CreateEncryptor(Key, Vector); 
     MemoryStream memoryStream = new MemoryStream(); 
     CryptoStream crptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Write); 
     crptoStream.Write(data, 0, data.Length); 
     crptoStream.FlushFinalBlock(); 
     crptoStream.Close(); 
     memoryStream.Close(); 
     return Convert.ToBase64String(memoryStream.ToArray()); 
    } 
    public string Decrypt(string encryptedText, string password) 
    { 
     GenerateKey(password); 
     return Decrypt(encryptedText); 
    } 
    public string Decrypt(string encryptedText) 
    { 

     if (Key == null) 
     { 

      throw new InvalidOperationException("Password must be provided or set."); 
     } 
     byte[] cipher = Convert.FromBase64String(encryptedText); 
     RijndaelManaged crypto = new RijndaelManaged(); 
     ICryptoTransform encryptor = crypto.CreateDecryptor(Key, Vector); 
     MemoryStream memoryStream = new MemoryStream(cipher); 
     CryptoStream crptoStream = new CryptoStream(memoryStream, encryptor, CryptoStreamMode.Read); 
     byte[] data = new byte[cipher.Length]; 
     int dataLength = crptoStream.Read(data, 0, data.Length); 
     memoryStream.Close(); 
     crptoStream.Close(); 
     return (new UnicodeEncoding()).GetString(data, 0, dataLength); 
    } 
+0

請問是否這是因爲您想要防止有人侵入您的系統並更改加密的字符串? – KBoek 2011-03-25 08:11:32

+0

是的,沒錯。我在webmethod中加密字符串,然後將其存儲在隱藏字段中,但有人可能會看到或更改隱藏字段中的值並將其發送到服務器。 – 2011-03-25 08:15:13

回答

2

嵌入校驗和。以例如明文的SHA1散列,base64,將其加到文本並加密。解密後,提取SHA1部分並根據字符串的其餘部分對其進行驗證。

0

您需要包含message authentication code(MAC)。

正確執行此操作的詳細信息超出了SO回答的範圍,所以我建議在開始實施前諮詢專家。

一個很好的起點將被Practical Cryptography(不針對.NET或任何其他平臺,但會告訴你,你需要做什麼—和爲什麼它是很難得到正確的)。

相關問題