.NET实现AES加密解密

AES加密有五种密码模式。.NET 内置的AES加密对象仅实现了两种(CBC、ECB),如果要实现OFB、CFB、CTR加密,仅仅只靠.NET内置的AES加密对象就无法实现了。如果想要实现的话,可以依靠一款强大的.NET 加密库:BouncyCastle.dll (nuget 上可找到 .NET Core版本:BouncyCastle.NetCore)。

今天作者向大家推荐的是一款依赖BouncyCastle.NetCore.dll实现加密的.NET 组件库:ZHI.ZSystem。

相对于.NET内置AES加密对象,它有以下优势:

  1.可以实现OFB、CFB、CTR、CTS加密

  2.静态函数调用,操作简单方便

相对于BouncyCastle加密库,它有以下优势:

  1.底层依赖BouncyCastle加密库,bug少

  2.调用函数方式简单,参数清晰明了,注释齐全

接下来我们用代码来证明吧!

1.nuget 搜索 ZHI.ZSystem并安装(目标框架是.NET Standard 2.0,所以.NET Core 和 .NET Framework都可以下载并使用)

 

2.调用AES加密/解密方法。(真的超级简单!)

3.得到结果。(下面我贴一下自己的加密结果)

介绍完了用法,担心小伙伴们还是不太会用,所以把代码贴出来!

/// <summary>
/// 单元测试 记得引用ZHI.ZSystem库
/// </summary>
[Test]
public void Test()
{
    //AES KEY 128 BIT
    var aes_key = "dyoo9IaP1NbuMOwk";
    //AES IV 16 BYTE
    var aes_iv = "kT0mtWAHg1lEympP";
    // plaintext
    var plaintext = "嘿嘿嘿 $&*!";

    //BASE64 输出
    var ciphertext_base_64_output = EncryptHelper.AESEncryptToBase64(plaintext, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding);
    //Hex 输出(十六进制输出)
    var ciphertext_hex_output = EncryptHelper.AESEncryptToHex(plaintext, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding);
    //AES 解密 BASE64
    var base_64_decrypt = EncryptHelper.AESDecryptFromBase64(ciphertext_base_64_output, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding);
    //AES 解密 Hex
    var hex_decrypt = EncryptHelper.AESDecryptFromHex(ciphertext_hex_output, aes_key, aes_iv, AesCipherMode.CBC, AesPaddingMode.PKCS7Padding);

    Console.WriteLine("CBC密码模式");
    Console.WriteLine("     加密结果base64输出:{0}", ciphertext_base_64_output);
    Console.WriteLine("     加密结果hex输出:{0}", ciphertext_hex_output);
    Console.WriteLine("     解密base64:{0}", base_64_decrypt);
    Console.WriteLine("     解密hex:{0}", hex_decrypt);
    Console.WriteLine();
    //BASE64 输出
    ciphertext_base_64_output = EncryptHelper.AESEncryptToBase64(plaintext, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding);
    //Hex 输出(十六进制输出)
    ciphertext_hex_output = EncryptHelper.AESEncryptToHex(plaintext, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding);
    //AES 解密 BASE64
    base_64_decrypt = EncryptHelper.AESDecryptFromBase64(ciphertext_base_64_output, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding);
    //AES 解密 Hex
    hex_decrypt = EncryptHelper.AESDecryptFromHex(ciphertext_hex_output, aes_key, aes_iv, AesCipherMode.CFB, AesPaddingMode.PKCS7Padding);
    Console.WriteLine("CFB密码模式");
    Console.WriteLine("     加密结果base64输出:{0}", ciphertext_base_64_output);
    Console.WriteLine("     加密结果hex输出:{0}", ciphertext_hex_output);
    Console.WriteLine("     解密base64:{0}", base_64_decrypt);
    Console.WriteLine("     解密hex:{0}", hex_decrypt);
    Console.WriteLine();
}

看完有没有觉得特别简单呢!

 

posted @ 2020-12-28 17:32  peashooters  阅读(1426)  评论(0编辑  收藏  举报