我當前使用這種方式設置RijndaelManaged(由於服務器如何處理加密,IV和Key是相同的)。服務器也使用CFB8作爲Mode,我是否正確設置了它?C#AES-128 CFB錯誤
public static RijndaelManaged GenerateAES(byte[] key)
{
RijndaelManaged cipher = new RijndaelManaged();
cipher.Mode = CipherMode.CFB;
cipher.Padding = PaddingMode.None;
cipher.KeySize = 128;
cipher.Key = key;
cipher.IV = key;
return cipher;
}
我寫做這樣的數據: ICryptoTransform的E = GenerateAES(鍵).CreateEncryptor();
using(CryptoStream stream = new CryptoStream(BaseStream, e, CryptoStreamMode.Write))
{
stream.WriteByte(b);
stream.FlushFinalBlock();
}
BaseStream是我打開的NetworkStream,'b'是我發送給我的函數的值。
當我嘗試將0×00(作爲測試)到流,我得到這個錯誤:
System.Security.Cryptography.CryptographicException: Length of the data to encrypt is invalid.
at System.Security.Cryptography.RijndaelManagedTransform.EncryptData(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount, Byte[]& outputBuffer, Int32 outputOffset, PaddingMode paddingMode, Boolean fLast)
at System.Security.Cryptography.RijndaelManagedTransform.TransformFinalBlock(Byte[] inputBuffer, Int32 inputOffset, Int32 inputCount)
at System.Security.Cryptography.CryptoStream.FlushFinalBlock()
at System.Security.Cryptography.CryptoStream.Dispose(Boolean disposing)
at System.IO.Stream.Close()
我只能做這個功能測試與否,如果我可以對服務器進行通信,而無需依賴在任何外部庫上。
的填充是沒有一個CryptoStream的構造函數,我我確信這一點。出於絕望,我嘗試將PaddingMode更改爲零,*它似乎工作,直到我有寫錯誤(流忽然變得無法寫入)。 – 0xFF 2012-08-02 12:33:11
@ SwDevMan81不,填充在加密之前應用於明文,以允許分組密碼(如AES)在任意長度的明文上操作。來自MSDN的PaddingMode枚舉:「大多數純文本消息不包含完全填充塊的大量字節,通常沒有足夠的字節填充最後一個塊。當發生這種情況時,將在文本中添加填充字符串「。 – Iridium 2012-08-02 12:39:09
@ 0xFF如果服務器不使用填充,那麼要加密的數據*的長度必須等於塊大小的倍數,這就是分組密碼的工作原理。 – Iridium 2012-08-02 12:44:44