У меня есть код для строкового шифрования/дешифрования с использованием алгоритма AES. Шифрование работает отлично, как ожидалось, но я не смог получить правильный текст, когда я его расшифрую. В коде дешифрования должно быть что-то не так.C# AES Код дешифрования
Я скопировал приведенный ниже код.
Пожалуйста, помогите с этим. Благодарю.
Ниже приведен код шифрования и дешифрования.
public static class EncryptionHelper
{
private static int BlockSize = 16;
private static byte[] Key
{
get
{
byte[] hash = SHA1.Create().ComputeHash(Encoding.UTF8.GetBytes("BlahBlahBlah"));
byte[] key = new byte[BlockSize];
Array.Copy(hash, 0, key, 0, BlockSize);
return key;
}
}
private static byte[] IV
{
get
{
StringBuilder builder = new StringBuilder();
Random random = new Random();
for (int i = 0; i < BlockSize; i++)
{
char ch = Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65)));
builder.Append(ch);
}
return Encoding.UTF8.GetBytes(builder.ToString());
}
}
public static string DecodeAndDecrypt(string cipherText)
{
string DecodeAndDecrypt = AesDecrypt(Convert.FromBase64String(HttpUtility.UrlDecode(cipherText)));
return (DecodeAndDecrypt);
}
public static string EncryptAndEncode(string plaintext)
{
return HttpUtility.UrlEncode(Convert.ToBase64String(AesEncrypt(plaintext)));
}
public static string AesDecrypt(Byte[] inputBytes)
{
Byte[] outputBytes = inputBytes;
string plaintext = string.Empty;
using (MemoryStream memoryStream = new MemoryStream(outputBytes))
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateDecryptor(Key, IV), CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(cryptoStream))
{
plaintext = srDecrypt.ReadToEnd();
}
}
}
return plaintext;
}
public static byte[] AesEncrypt(string inputText)
{
byte[] inputBytes = UTF8Encoding.UTF8.GetBytes(inputText);
for (int i = 0; i < BlockSize; i++)
{
inputBytes[i] ^= IV[i];
}
byte[] result = null;
using (MemoryStream memoryStream = new MemoryStream())
{
using (CryptoStream cryptoStream = new CryptoStream(memoryStream, GetCryptoAlgorithm().CreateEncryptor(Key, IV), CryptoStreamMode.Write))
{
cryptoStream.Write(inputBytes, 0, inputBytes.Length);
cryptoStream.FlushFinalBlock();
result = memoryStream.ToArray();
}
}
return result;
}
private static RijndaelManaged GetCryptoAlgorithm()
{
RijndaelManaged algorithm = new RijndaelManaged();
algorithm.Padding = PaddingMode.PKCS7;
algorithm.Mode = CipherMode.CBC;
algorithm.KeySize = 128;
algorithm.BlockSize = 128;
return algorithm;
}
}
Что это: 'inputBytes [i]^= IV [i];' Это некоторая предыдущая попытка зашифровать вручную, что не требуется Теперь? – weston
Также 'IV' ** может ** быть одинаков для кодирования и декодирования, не уверен. http://stackoverflow.com/questions/8041451/good-aes-initialization-vector-practice – weston
Я пробовал пропустить входBytes [i]^= IV [i]; Но не повезло –