解密时要解密的数据长度无效

时间:2014-05-03 23:29:50

标签: c# image encryption

我需要加密图像,返回加密数据的字符串,然后解密

这是我的加密代码:

string plainText = ASCIIEncoding.ASCII.GetString(Imagebytes);
byte[] encrypted;
byte[] key = Encoding.UTF8.GetBytes("M02cnQ51Ji97vwT4");;
// Create an AesCryptoServiceProvider object 
using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider())
{
    aesAlg.Key = key;
    aesAlg.BlockSize = 128;

    // 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 (var aesAlg = new AesManaged())
{


    aesAlg.Key = new UTF8Encoding().GetBytes("M02cnQ51Ji97vwT4");
    aesAlg.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);

    return UTF8Encoding.UTF8.GetString(encryptor.TransformFinalBlock(Imagebytes, 0, Imagebytes.Length)).Length;

}

我的解密工作正常(因为我可以完美地接收图像/视频)

这是代码:

const  string BLOB_KEY = "TTAyY25RNTFKaTk3dndUNA==";
using (RijndaelManaged rm = new RijndaelManaged())
{
    rm.Mode = CipherMode.ECB;
    rm.Key = Convert.FromBase64String(BLOB_KEY);
    rm.IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
    rm.Padding = PaddingMode.Zeros;
    using (MemoryStream ms = new MemoryStream())
    {
        using (CryptoStream cs = new CryptoStream(ms, rm.CreateDecryptor(),
                    CryptoStreamMode.Write))
        {
            cs.Write(image, 0, image.Length);
            return ms.ToArray();
        }
    }
}

我的加密代码有什么问题?

2 个答案:

答案 0 :(得分:1)

你最初的代码行已经错了:

string plainText = ASCIIEncoding.ASCII.GetString(Imagebytes);

图像不是字符串,明文也不一定是字符串。两者都由字节组成。所以你不应该使用StreamWriter,只是普通的流。

转换过程中可能会丢失数据。

此外,您正在写一个解密流,而您在一侧使用ECB模式而在另一侧使用CBC模式。

我强烈建议您阅读材料并重新开始。

答案 1 :(得分:0)

谢谢,我已将我的代码更改为:

var aesAlg = new AesManaged
        {
            KeySize = 128,
            Key = key,
            BlockSize = 128,
            Mode = CipherMode.ECB,
            Padding = PaddingMode.Zeros,
            IV = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }
        };

        ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);
        return encryptor.TransformFinalBlock(Imagebytes, 0, Imagebytes.Length);

它工作正常!