要加密的数据长度不符合要求

本文关键字:不符合 数据 加密 | 更新日期: 2023-09-27 17:54:05

获取异常"要加密的数据长度无效"。

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); 
} 

要加密的数据长度不符合要求

PaddingMode.None要求输入是块大小的倍数。用PaddingMode.PKCS7之类的代替


你的代码的其他几个问题:

  1. 一个常数不能成为好的盐
  2. 从密码中确定派生IV的恒定盐意味着您正在重用(Key, IV)对,这是不应该做的
  3. 你没有添加认证/某种MAC。这通常会导致填充预言或类似的攻击
  4. 您从PBKDF2输出中读取更多的本机大小。这样可以在不降低攻击者速度的情况下将密钥派生速度减半。