说明
从bouncycastle C#的主页中可以看到 1.8.4版本增加了SM4分组加密算法的支持。
通过官方提供的测试用例我们可以知道如何调用该算法。
测试用例: SM4Test.cs
本次将使用Visual Studio 2019 带大家从零开始编写一个SM4 算法的Demo。
工具准备:
- Visual Studio 2019
本次Demo包括
- 建立工程
- 引入包管理
- Demo编写
From Zero
文件 > 新建 > 项目
选择: 控制台应用(.NET Core),下一步
填写项目信息,创建
VS默认会使用模板给我们创建一个HElloWorld程序。
此处使用 NuGet包管理工具引入三方的程序包。
NuGet 类似于 Maven的包管理工具
在 解决方案管理器中找到我们的项目(Sm4Demo)
右键依赖项>管理 Neget程序包
在弹出的窗口中: 选择浏览> 在搜索栏中输入 bouncy,就可以看到我们需要的Bouncycastle程序包。
在右侧选择适合的版本点击安装。
注意这里版本一定要高于1.8.4 否则不支持SM4分组加密算法哦。
安装后弹出警告,这是因为我们项目 默认使用.net 3.1,而BC包是使用.net 4.6以上的版本
此处我们暂时忽略。
安装完成我们就可以在解决方案中看到我们安装的BC包。
接下来我们就可以编写我们的代码
QuickStart
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using System;
using System.Linq;
using System.Text;
namespace Sm4Demo
{
class Program
{
static void Main()
{
byte[] plaintext = Encoding.ASCII.GetBytes("Hello World");
byte[] keyBytes = Encoding.ASCII.GetBytes("0123456789ABCDEF");
byte[] iv = Encoding.ASCII.GetBytes("0123456789ABCDEF");
// 加密
KeyParameter key = ParameterUtilities.CreateKeyParameter("SM4", keyBytes);
ParametersWithIV keyParamWithIv = new ParametersWithIV(key, iv);
IBufferedCipher inCipher = CipherUtilities.GetCipher("SM4/CBC/PKCS7Padding");
inCipher.Init(true, keyParamWithIv);
byte[] cipher = inCipher.DoFinal(plaintext);
Console.WriteLine("加密后的密文(hex): {0}", BitConverter.ToString(cipher, 0).Replace("-", string.Empty));
// 解密
inCipher.Reset();
inCipher.Init(false, keyParamWithIv);
byte[] bin = inCipher.DoFinal(cipher);
string ans = Encoding.UTF8.GetString(bin);
Console.WriteLine("解密明文内容: {0}\t是否匹配: {1}", ans, Enumerable.SequenceEqual(plaintext, bin));
Console.ReadLine();
}
}
}
运行结果截图
参考文献
[1]. 快速入门:在 Visual Studio 中安装和使用包(仅适用于 Windows) . microsoft . 2018/07/24 . https://docs.microsoft.com/zh-cn/nuget/quickstart/install-and-use-a-package-in-visual-studio
[2]. SM4Test . bc-csharp . https://github.com/bcgit/bc-csharp/blob/master/crypto/test/src/test/SM4Test.cs
[3]. Encrypt string with Bouncy Castle AES/CBC/PKCS7 . stackoverflow . tim . https://stackoverflow.com/questions/29701401/encrypt-string-with-bouncy-castle-aes-cbc-pkcs7
[4]. How to compare arrays in C#? . stackoverflow . mahdi . https://stackoverflow.com/questions/4423318/how-to-compare-arrays-in-c
[5]. Converting string to byte array in C# . stackoverflow . Timothy Randall . https://stackoverflow.com/questions/16072709/converting-string-to-byte-array-in-c-sharp