2

一部のテキストに AES 暗号化を使用しようとしていますが、復号化されたテキストは元のテキストと同一ではありません。

  • 原文:abcd
  • 復号化されたテキスト:?9T?o??G???x;*

これが私のコードです:

public static void Main(string[] args)
{
    byte[] original = { 97, 98, 99, 100 }; //"abcd"
    byte[] key = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 };
    byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    byte[] encrypt = Encrypt(original, key, iv);
    byte[] decrypt = Decrypt(encrypt, key, iv);
    Console.WriteLine(Encoding.UTF8.GetString(original));
    Console.WriteLine(Encoding.UTF8.GetString(decrypt));
    Console.ReadKey();
}

public static byte[] Encrypt(byte[] original, byte[] key, byte[] iv)
{
    using (var memoryStream = new MemoryStream())
    {
        using (var aes = new AesManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC })
        {
            using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Write))
            {
                cryptoStream.Write(original, 0, original.Length);
            }
        }
        return memoryStream.ToArray();
    }
}

public static byte[] Decrypt(byte[] encrypt, byte[] key, byte[] iv)
{
    using (var memoryStream = new MemoryStream(encrypt))
    {
        using (var aes = new AesManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC })
        {
            using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(), CryptoStreamMode.Read))
            {
                byte[] decrypt = new byte[encrypt.Length];
                cryptoStream.Read(decrypt, 0, decrypt.Length);
                return decrypt;
            }
        }
    }
}

どうしたの?前もって感謝します。

4

2 に答える 2

4

復号化コードにこれがあります:

using (var cryptoStream = new CryptoStream(memoryStream, aes.CreateEncryptor(),
                                           CryptoStreamMode.Read))

call に変更するとaes.CreateDecryptor()、正常に動作します。

于 2012-11-10T09:01:09.140 に答える
0

復号化方法に問題があります。次のようなものを使用してください:

public string Decrypt(byte[] EncryptedValue)
        {
            #region Write the encrypted value to the decryption stream
            MemoryStream encryptedStream = new MemoryStream();
            CryptoStream decryptStream = new CryptoStream(encryptedStream, DecryptorTransform, CryptoStreamMode.Write);
            decryptStream.Write(EncryptedValue, 0, EncryptedValue.Length);
            decryptStream.FlushFinalBlock();
            #endregion

            #region Read the decrypted value from the stream.
            encryptedStream.Position = 0;
            Byte[] decryptedBytes = new Byte[encryptedStream.Length];
            encryptedStream.Read(decryptedBytes, 0, decryptedBytes.Length);
            encryptedStream.Close();
            #endregion
            return UTFEncoder.GetString(decryptedBytes);
        }
于 2012-11-10T09:06:20.903 に答える