要加密的数据长度无效

获取exception“数据长度为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); } 

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


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

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