一种选择是使用 BouncyCastle 库,它们确实支持 Aes/Ofb/NoPadding。
另一种选择是使用 c# 框架中的 System.Security.Cryptography.Aes 并使用 PaddingMode.Zeros 进行加密,然后将加密数据截断为与输入数据相同的长度(丢弃加密文本末尾的填充数据)。解密时,将填充(任何垃圾或零)附加到密文以对齐块长度,设置 PaddingMode.None,解密,最后丢弃填充字节(它们将是伪造的)。像这样的东西:
var aes2 = Aes.Create();
aes2.KeySize = 128;
aes2.BlockSize = 128;
aes2.Mode = CipherMode.CFB;
aes2.Padding = PaddingMode.Zeros;
var aes2Data = new byte[buff.Length];
// strip padded data
Buffer.BlockCopy(aes2.CreateEncryptor().TransformFinalBlock(buff, 0, buff.Length), 0,
aes2Data, 0, buff.Length);
Console.WriteLine("Aes2 size: {0}", aes2Data.Length);
// validate aes2
var size = aes2Data.Length;
var pad = aes2Data.Length % 16;
if (pad != 0)
{
var tmp = new byte[aes2Data.Length + 16 - pad];
Buffer.BlockCopy(aes2Data, 0, tmp, 0, aes2Data.Length);
aes2Data = tmp;
}
var aes2Decr = Aes.Create();
aes2Decr.Padding = PaddingMode.None;
aes2Decr.Key = aes2.Key;
aes2Decr.Mode = aes2.Mode;
aes2Decr.IV = aes2.IV;
var data2 = aes2Decr.CreateDecryptor().TransformFinalBlock(aes2Data, 0, aes2Data.Length);
valid = data2.Take(size).SequenceEqual(buff);
if (!valid)
throw new ApplicationException("Invalid data");