使用`RijndaelManaged`生成的加密结果为: 0x8d, 0x81, 0x27, 0xc6, 0x3c, 0xe2, 0x53, 0x2f, 0x35, 0x78, 0x90, 0xc2, 0x2e, 0x3b, 0x8a, 0x61, 0x41, 0x47, 0xd6, 0xd0, 0xff, 0x92, 0x72, 0x3d, 0xc6, 0x16, 0x2b, 0xd8, 0xb5, 0xd9, 0x12, 0x85
使用`AesCryptoServiceProvider`生成的加密结果为: 0x8d, 0x9f, 0x6e, 0x99, 0xe9, 0x54, 0x8b, 0x12, 0xa9, 0x88, 0x1a, 0x3d, 0x65, 0x23, 0x9c, 0x4e, 0x18, 0x5a, 0x89, 0x31, 0xf5, 0x75, 0xc5, 0x9e, 0x0d, 0x43, 0xe9, 0x86, 0xd4, 0xf3, 0x64, 0x3a
以下是产生这些结果的代码。
public partial class AesTest
{
private SymmetricAlgorithm mEncryptionType;
private byte[] mPrivateKey;
private byte[] mInitializationVector;
private byte[] mData;
public AesTest()
{
//设置私钥
mPrivateKey = new byte[32]
{
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22,
0x22, 0x22, 0x22, 0x22
};
//设置初始化向量
mInitializationVector = new byte[16]
{
0x33, 0x33, 0x33, 0x33,
0x33, 0x33, 0x33, 0x33,
0x33, 0x33, 0x33, 0x33,
0x33, 0x33, 0x33, 0x33
};
//设置数据
mData = new byte[16]
{
0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44,
0x44, 0x44, 0x44, 0x44
};
//创建加密算法实例
mEncryptionType = new RijndaelManaged();
//设置加密模式为CFB
mEncryptionType.Mode = CipherMode.CFB;
//设置填充方式为PKCS7
mEncryptionType.Padding = PaddingMode.PKCS7;
//设置加密块大小为128位
mEncryptionType.BlockSize = 128;
//设置密钥大小为256位
mEncryptionType.KeySize = 256;
}
byte[] rij_encrypted_data = Encrypt(mData);mEncryptionType = new AesCryptoServiceProvider(); mEncryptionType.Mode = CipherMode.CFB; mEncryptionType.Padding = PaddingMode.PKCS7; mEncryptionType.BlockSize = 128; mEncryptionType.KeySize = 256;
byte[] aes_encrypted_data = Encrypt(mData); } public virtual byte[] Encrypt(byte[] unencryptedData) { return TransformData(unencryptedData, mEncryptionType.CreateEncryptor(mPrivateKey, mInitializationVector)); } private byte[] TransformData(byte[] dataToTransform, ICryptoTransform cryptoTransform) { byte[] result = new byte[0]; if (dataToTransform != null && cryptoTransform != null && dataToTransform.Length > 0) { // 创建内存流以存储结果 MemoryStream mem_stream = new MemoryStream(); // 创建加密流进行转换 CryptoStream crypto_stream = new CryptoStream(mem_stream, cryptoTransform, CryptoStreamMode.Write); // 写入数据并进行转换 crypto_stream.Write(dataToTransform, 0, dataToTransform.Length); // 刷新缓冲区并写入最终块 crypto_stream.FlushFinalBlock(); // 将转换后的内存流转换回字节数组 result = mem_stream.ToArray(); // 关闭流 mem_stream.Close(); crypto_stream.Close(); } return result; } }
说明:该代码段展示了一个使用 AES 算法进行数据加密的方法。在此之前,先通过设置加密模式、填充模式、块大小和密钥大小等参数来配置对称加密算法。然后,使用给定的私钥和初始化向量创建加密器,并使用 CryptoStream 进行数据转换。在写入待加密数据并刷新缓冲区之后,将加密后的数据存储在内存流中,并转换为字节数组返回。
我猜想我是否漏掉了什么。
更新:结果发现,如果您尝试将CipherMode设置为CFB,则AesManaged会抛出CryptographicException(“指定的密码模式对于此算法无效”)。 我认为AesCryptoServiceProvider也应该这样做,但它没有。看起来很奇怪,FIPS认证类允许无效的密码模式。