3

我可以加密图像文件。但无法解密该文件。

而 ((readLen = cryptStrm.Read(bs, 0, bs.Length)) > 0)

谁能猜出哪一部分是错的?我编写的代码如下。

当我阅读加密文件时,我根本无法阅读。当我使用 vss 看到 cryptstream 的属性时,称为长度和位置的 CryptoStream 属性具有“NotSupportedException”。

我浪费了很多时间来解决这个问题.....请帮助我......

加密[位图>>加密文件]

解密[加密文件>>文件]


加密

    public static void EncryptFile(
        Bitmap bmp, string destFile, byte[] key, byte[] iv)
    {

        System.Security.Cryptography.RijndaelManaged rijndael =
            new System.Security.Cryptography.RijndaelManaged();

        rijndael.Key = key;
        rijndael.IV = iv;

        System.IO.FileStream outFs = new System.IO.FileStream(
            destFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);

        System.Security.Cryptography.ICryptoTransform encryptor =
            rijndael.CreateEncryptor();

        System.Security.Cryptography.CryptoStream cryptStrm =
            new System.Security.Cryptography.CryptoStream(
                outFs, encryptor,
                System.Security.Cryptography.CryptoStreamMode.Write);

        MemoryStream ms = new MemoryStream();
        bmp.Save(ms, ImageFormat.Jpeg);


        byte[] bs = new byte[1024];
        int readLen;
        while ((readLen = ms.Read(bs, 0, bs.Length)) > 0)
        {
            cryptStrm.Write(bs, 0, readLen);
        }

        ms.Close();
        cryptStrm.Close();
        encryptor.Dispose();
        outFs.Close();
    }

解密

    public static void DecryptFile(
        string sourceFile, string destFile, byte[] key, byte[] iv)
    {

        System.Security.Cryptography.RijndaelManaged rijndael =
            new System.Security.Cryptography.RijndaelManaged();

        rijndael.Key = key;
        rijndael.IV = iv;

        System.IO.FileStream inFs = new System.IO.FileStream(
            sourceFile, System.IO.FileMode.Open, System.IO.FileAccess.Read);

        System.Security.Cryptography.ICryptoTransform decryptor =
            rijndael.CreateDecryptor();

        System.Security.Cryptography.CryptoStream cryptStrm =
            new System.Security.Cryptography.CryptoStream(
                inFs, decryptor,
                System.Security.Cryptography.CryptoStreamMode.Read);

        System.IO.FileStream outFs = new System.IO.FileStream(
            destFile, System.IO.FileMode.Create, System.IO.FileAccess.Write);
        byte[] bs = new byte[1024];
        int readLen;

        while ((readLen = cryptStrm.Read(bs, 0, bs.Length)) > 0)
        {
            outFs.Write(bs, 0, readLen);
        }

        outFs.Close();
        cryptStrm.Close();
        decryptor.Dispose();
        inFs.Close();
    }
4

1 回答 1

0

尝试设置 rijndael 的 Mode 和 Padding 成员。
当我进行类似的实现时,默认填充模式会导致问题。

            // It is reasonable to set encryption mode to Cipher Block Chaining
            // (CBC). Use default options for other symmetric key parameters.
            rijndael.Mode = CipherMode.CBC;
            rijndael.Padding = PaddingMode.None;

于 2011-04-30T18:27:21.310 回答