C#AES流未关闭图片加密

时间:2015-12-05 17:19:36

标签: c# encryption aes

我正在编写一个C#应用程序来使用AES加密图片,我能够成功加密和解密图片,但这些流程从未关闭。因此,如果我尝试用加密的图片重写图片,我会收到“System.IO.IOException”异常,因为它已被另一个进程使用。如果我在加密后尝试删除我正在尝试加密的文件,则会发生同样的事情。任何人都可以确定为什么蒸汽永远不会关闭?他们都在使用声明,所以他们不应该在使用块的末尾关闭?还会让用户输入密钥的字符串和加密和解密的IV值来创建任何安全问题吗?

        // Method to encrypt the picture
    public static void encryptPicture(string inputFile, string outputFile, string keyInput, string ivInput)
    {
        byte[] toEncrypt = AESEncryptor.imageToByteArray(inputFile);
        byte[] kholder = ASCIIEncoding.ASCII.GetBytes(keyInput);
        byte[] iHolder = ASCIIEncoding.ASCII.GetBytes(ivInput);
        Array.Resize<byte>(ref kholder, 32);
        Array.Resize<byte>(ref iHolder, 16);
        byte[] byteArray = AESEncryptor.EncryptByteToByte(toEncrypt, kholder, iHolder);
        File.WriteAllBytes(outputFile, byteArray);
    }

        //converts image to byte array
    public static byte[] imageToByteArray(string fileNameInput)
    {
        byte[] toReturn = null;
        using (var ms = new MemoryStream())
        {
            Image img = Image.FromFile(fileNameInput);
            img.Save(ms, ImageFormat.Jpeg);
            toReturn= ms.ToArray();
        }
        return toReturn;
    }

 //encrypts a byte arrar
    public static byte[] EncryptByteToByte(byte[] inputArray, byte[] Key, byte[] IV)
    {
        // Check arguments.
        if (inputArray == null || inputArray.Length <= 0)
            throw new ArgumentNullException("plainText");
        if (Key == null || Key.Length <= 0)
            throw new ArgumentNullException("Key");
        if (IV == null || IV.Length <= 0)
            throw new ArgumentNullException("Key");
        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))
                {
                    csEncrypt.Write(inputArray, 0, inputArray.Length);
                    encrypted = msEncrypt.ToArray();
                }
            }
        }


        // Return the encrypted bytes from the memory stream.
        return encrypted;

    }

0 个答案:

没有答案