1

获取异常“加密的数据长度无效”。

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

1 回答 1

5

PaddingMode.None要求输入是块大小的倍数。使用像PaddingMode.PKCS7instread 这样的想法。


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

  1. 常数不能成为好盐
  2. 恒定盐以及从密码中确定性推导 IV 意味着您正在重用 (Key, IV) 对,这不应该这样做
  3. 您不添加身份验证/某种 MAC。这通常会导致填充预言或类似的攻击
  4. 您从 PBKDF2 输出中阅读了更多本机大小。这将您的密钥派生速度减半,而不会减慢攻击者的速度。
于 2013-01-17T12:24:30.767 回答