繁体   English   中英

c#中的AES加密

[英]AES Encryption in c#

我尝试使用示例MSDN https://msdn.microsoft.com/ru-ru/library/system.security.cryptography.aes(v=vs.110).aspx加密文件。当我加密.txt文件时,那么一切都很好,但是当我尝试加密其他文件(.bmp,.pdf ...)时,该文件不会被解密。 错误在哪里?

我修改了代码以下载文件

internal static void EncryptAes(string pathData, string pathEnCrypt)
    {
        string plainText;
        using (StreamReader sr = new StreamReader(pathData))
            plainText = sr.ReadToEnd();
        byte[] encrypted;
        // Create an Aes object
        // with the specified key and IV.
        using (Aes aesAlg = Aes.Create())
        {
            aesAlg.Key = Key;
            aesAlg.IV = IV;

            // Create a decrytor to perform the stream transform.
            ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

            // Create the streams used for encryption.
            using (MemoryStream msEncrypt = new MemoryStream())
            {
                using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                {
                    using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                    {

                        //Write all data to the stream.
                        swEncrypt.Write(plainText);
                    }
                    encrypted = msEncrypt.ToArray();
                }
            }
            using (FileStream fstream = new FileStream(pathEnCrypt, FileMode.Create))
                fstream.Write(encrypted, 0, encrypted.Length);
        }
    }

StreamReader应该使用特殊编码的文本数据。 因此,您不能将其用于二进制数据。

如果文件不是很大,则可以将文件内容读取到MemmoryStream中,然后将其用于AES。

像字符串一样对十六进制/二进制数据进行操作,将导致数据丢失,因此您将无法完全恢复它。 为了让你可以想看看一个/多个想法 ,它说明你想为VB.NET做什么

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM