Rijndael加密|填充无效,无法删除

时间:2014-01-29 06:36:35

标签: c# encryption

我是密码学新手,我不太清楚我在这里做错了什么,

public static byte[] EncryptData(byte[] data, string keystr)
{
    if (keystr.Length > 32)
        keystr = keystr.Substring(0, 32);
    else
        while (keystr.Length != 32)
            keystr += "0";

    byte[] iv = Encoding.UTF8.GetBytes(SALT);
    byte[] key = Encoding.UTF8.GetBytes(keystr);

    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (RijndaelManaged rijndaelManaged = new RijndaelManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC })
        {
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateEncryptor(key, iv), CryptoStreamMode.Write))
            {
                cryptoStream.Write(data, 0, data.Length);
            }
        }
        return memoryStream.ToArray();
    }
}

public static byte[] DecryptData(byte[] data, string keystr)
{
    if (keystr.Length > 32)
        keystr = keystr.Substring(0, 32);
    else
        while (keystr.Length != 32)
            keystr += "0";

    byte[] iv = Encoding.UTF8.GetBytes(SALT);
    byte[] key = Encoding.UTF8.GetBytes(keystr.ToUpper());

    using (MemoryStream memoryStream = new MemoryStream())
    {
        using (RijndaelManaged rijndaelManaged = new RijndaelManaged { Key = key, IV = iv, Padding = PaddingMode.PKCS7, Mode = CipherMode.CBC })
        {
            using (CryptoStream cryptoStream = new CryptoStream(memoryStream, rijndaelManaged.CreateDecryptor(key, iv), CryptoStreamMode.Write))
            {
                cryptoStream.Write(data, 0, data.Length);
            }
        }
        return memoryStream.ToArray();
    }
}

正如您所看到的,我传递了一个字节数组和一个密码。我确保密码总是32个字符。

我在解密数据时获得Padding is invalid and cannot be removed.

钥匙和盐总是一样的。

1 个答案:

答案 0 :(得分:2)

key可以同时传递给两种方法,但出于某种原因,在你丢弃更多熵(用于更长的字符串)或填充键(用于更短的字符串)之后,对于某些方法你这样做的原因:

keystr.ToUpper()

但仅限于解密方面。所以使用的密钥是不同的。

我强烈建议您不要致电ToUpper。其他建议可能是没有固定的salt / IV,并且允许iv和key也作为字节数组传递,而不是strings。加密自然会处理字节数组,并且实际上鼓励加密较弱的这些包装器方法可能是一个坏主意。