要加密的数据长度无效

时间:2013-01-17 12:13:58

标签: c#

获取异常“数据长度为ENCRYPTION无效”。

private static readonly byte[] salt = Encoding.ASCII.GetBytes("S@sh@kt@ VMS");

public static string Encrypt(string textToEncrypt, string encryptionPassword)
{
    byte[] encryptedBytes = null;
    try
    {
        var algorithm = GetAlgorithm(encryptionPassword);
        algorithm.Padding = PaddingMode.None;
        using (ICryptoTransform encryptor = algorithm.CreateEncryptor(algorithm.Key, algorithm.IV))
        {
            byte[] bytesToEncrypt = Encoding.UTF8.GetBytes(textToEncrypt);
            encryptedBytes = InMemoryCrypt(bytesToEncrypt, encryptor);
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }
    return Convert.ToBase64String(encryptedBytes);
}

 // Performs an in-memory encrypt/decrypt transformation on a byte array.

private static byte[] InMemoryCrypt(byte[] data, ICryptoTransform transform)
{
    MemoryStream memory = new MemoryStream();
    using (Stream stream = new CryptoStream(memory, transform, CryptoStreamMode.Write))
    {
        stream.Flush();
        stream.Write(data, 0, data.Length);
        //stream.FlushFinalBlock();
    }
    return memory.ToArray();
}

private static RijndaelManaged GetAlgorithm(string encryptionPassword)
{
    // Create an encryption key from the encryptionPassword and salt.
    var key = new Rfc2898DeriveBytes(encryptionPassword, salt);
    // Declare that we are going to use the Rijndael algorithm with the key that we've just got.
    var algorithm = new RijndaelManaged();
    int bytesForKey = algorithm.KeySize/8;
    int bytesForIV = algorithm.BlockSize/8;
    algorithm.Key = key.GetBytes(bytesForKey);
    algorithm.IV = key.GetBytes(bytesForIV);
    return algorithm;
}

解密程序是:

public static string Decrypt(string encryptedText, string encryptionPassword)
{
    var algorithm = GetAlgorithm(encryptionPassword);
    algorithm.Padding = PaddingMode.PKCS7; 
    byte[] descryptedBytes;
    using (ICryptoTransform decryptor = algorithm.CreateDecryptor(algorithm.Key, algorithm.IV))
    {
        byte[] encryptedBytes = Convert.FromBase64String(encryptedText);
        descryptedBytes = InMemoryCrypt(encryptedBytes, decryptor);
    } 
    return Encoding.UTF8.GetString(descryptedBytes); 
} 

1 个答案:

答案 0 :(得分:4)

PaddingMode.None要求输入是块大小的倍数。使用像PaddingMode.PKCS7 instread。

这样的思考

您的代码的其他一些问题:

  1. 常数不能成为好盐
  2. 恒定的盐以及密码中IV的确定性推导意味着您正在重用(Key,IV)对,这不应该完成
  3. 您不添加身份验证/某种MAC。这通常会导致填充神谕或类似攻击
  4. 您从PBKDF2输出中读取了更多原始大小。这样可以在不降低攻击速度的情况下将关键的派生速度减半。