我使用私鑰和以下函數對字符串進行加密和解密。 所以我使用加密函數對字符串進行加密,並使用解密函數對加密的字符串進行解密。 如果有人可以更改加密的字符串,然後使用解密函數進行解密,則解密的字符串在加密前不等於純文本。 我想知道在加密之前如何檢查解密的字符串是否等於純文本?如何檢查加密字符串的完整性,然後轉換爲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);
}
請問是否這是因爲您想要防止有人侵入您的系統並更改加密的字符串? – KBoek 2011-03-25 08:11:32
是的,沒錯。我在webmethod中加密字符串,然後將其存儲在隱藏字段中,但有人可能會看到或更改隱藏字段中的值並將其發送到服務器。 – 2011-03-25 08:15:13