询问者
使用AES的CFB模式加密,设置PaddingMode为None时加密出错

问题
-
public static byte[] EncryptStringToBytes_Aes(byte[] plainText, byte[] Key, byte[] IV) { // Check arguments. if (plainText == null || plainText.Length <= 0) throw new ArgumentNullException("plainText"); if (Key == null || Key.Length <= 0) throw new ArgumentNullException("Key"); if (IV == null || IV.Length <= 0) throw new ArgumentNullException("Key"); byte[] encrypted; // Create an AesCryptoServiceProvider object // with the specified key and IV. using (AesCryptoServiceProvider aesAlg = new AesCryptoServiceProvider()) { aesAlg.Key = Key; aesAlg.IV = IV; aesAlg.Mode = CipherMode.CFB; aesAlg.Padding = PaddingMode.None; // Create a decrytor to perform the stream transform. ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV); // Create the streams used for encryption. using (MemoryStream msEncrypt = new MemoryStream()) { using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)) { //Write all data to the stream. csEncrypt.Write(plainText, 0, plainText.Length); csEncrypt.FlushFinalBlock(); encrypted = msEncrypt.ToArray(); } } } // Return the encrypted bytes from the memory stream. return encrypted; }
加密函数如上所示,代码是参考msdn的示例写的,加密时csEncrypt.FlushFinalBlock();会抛异常,异常信息“输入数据不是完整的块”
全部回复
-
你好:
请参考MSDN 文档:
默认AesCryptoServiceProvider.FeedbackSize好像是128,而CipherMode是8,尝试添加以下代码看看:
aesAlg.FeedbackSize = 8;
或者不要使用PaddingMode.None,使用其他选项。- 已标记为答案 CaillenModerator 2014年5月4日 2:45
- 取消答案标记 ThankfulHeartModerator 2014年5月15日 5:49
-
FeedbackSize设为8也是一样的错误
使用PaddingMode.None的目的是为了和其他语言加密出来的数据对接,所以这个没法改。
我尝试将输入的byte[]长度控制在BlockSize(默认16)的倍数时,不会抛异常,看起来似乎是设置PaddingMode.None的作用只是不对原始输入数据进行填充,内部加密函数依旧需要输入BlockSize整数倍的数据才能工作。但对CFB模式来说,理应是可以不用填充数据到BlockSize整数倍大小也可以正常加密的。
- 已建议为答案 ThankfulHeartModerator 2014年5月15日 5:49
- 取消建议作为答案 Jiang Liaoye 2014年5月16日 9:04