AES加密 - 加密字节

时间:2014-11-13 04:51:41

标签: c# encryption aes

我正在尝试使用Aes加密字节。但是,我得到的输出真的很奇怪。这是我的功能(加密和解密)。我做错了吗?

public static byte[] encryptStream(byte[] plain, byte[] Key, byte[] IV)
    {
        byte[] encrypted; ;
        using (MemoryStream mstream = new MemoryStream())
        {
            using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
            {
                using (CryptoStream cryptoStream = new CryptoStream(mstream,
                    aesProvider.CreateEncryptor(Key, IV), CryptoStreamMode.Write))
                {
                    cryptoStream.Write(plain, 0, plain.Length);
                }

            }
            encrypted = mstream.ToArray();
        }
        return encrypted;
    }

public static byte[] decryptStream(byte[] encrypted, byte[] Key, byte[] IV)
    {
        byte[] plain;
        using (MemoryStream mStream = new MemoryStream())
        {
            using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
            {
                using (CryptoStream cryptoStream = new CryptoStream(mStream,
                    aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                {
                    cryptoStream.Read(encrypted, 0, encrypted.Length);
                }
            }
            plain = mStream.ToArray();
        }
        return plain;
    }

1 个答案:

答案 0 :(得分:1)

当您从加密缓冲区中读取的cryptoStream中读取时,问题出在您的decryptStream()方法中。当您调用Read()时,您已经从加密缓冲区中读取,因为您将其与内存流包装在一起。您想要读入一个连接在一起的新缓冲区将是解密的字节。

    public static byte[] decryptStream(byte[] encrypted, byte[] Key, byte[] IV)
    {
        byte[] plain;
        byte[] buffer = new byte[32768];
        int totalRead = 0;
        MemoryStream plainStream = new MemoryStream();
        using (MemoryStream mStream = new MemoryStream(encrypted))
        {
            using (AesCryptoServiceProvider aesProvider = new AesCryptoServiceProvider())
            {
                using (CryptoStream cryptoStream = new CryptoStream(mStream,
                    aesProvider.CreateDecryptor(Key, IV), CryptoStreamMode.Read))
                {
                    while (true)
                    {
                        int read = cryptoStream.Read(buffer, 0, encrypted.Length);

                        if (read == 0)
                            break;
                        else
                            plainStream.Write(buffer, totalRead, read);

                        totalRead += read;
                    }

                }
            }

            plain = plainStream.ToArray();
        }
        return plain;
    }