BouncyCastle C# SM4 CBC加解密

说明

bouncycastle C#的主页中可以看到 1.8.4版本增加了SM4分组加密算法的支持。

算法支持

通过官方提供的测试用例我们可以知道如何调用该算法。

测试用例: SM4Test.cs

测试用截图

本次将使用Visual Studio 2019 带大家从零开始编写一个SM4 算法的Demo。

工具准备:

  • Visual Studio 2019

本次Demo包括

  1. 建立工程
  2. 引入包管理
  3. Demo编写

From Zero

文件 > 新建 > 项目
在这里插入图片描述
选择: 控制台应用(.NET Core),下一步
在这里插入图片描述

填写项目信息,创建

在这里插入图片描述

VS默认会使用模板给我们创建一个HElloWorld程序。

在这里插入图片描述

此处使用 NuGet包管理工具引入三方的程序包。

NuGet 类似于 Maven的包管理工具

在 解决方案管理器中找到我们的项目(Sm4Demo)

右键依赖项>管理 Neget程序包
Neget程序包
在弹出的窗口中: 选择浏览> 在搜索栏中输入 bouncy,就可以看到我们需要的Bouncycastle程序包。
在这里插入图片描述
在右侧选择适合的版本点击安装。

注意这里版本一定要高于1.8.4 否则不支持SM4分组加密算法哦。

安装后弹出警告,这是因为我们项目 默认使用.net 3.1,而BC包是使用.net 4.6以上的版本
在这里插入图片描述
此处我们暂时忽略。

安装完成我们就可以在解决方案中看到我们安装的BC包。

在这里插入图片描述

接下来我们就可以编写我们的代码

QuickStart

GitHub

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

以下是使用Bouncy Castle库进行SM4加解密的示例程序: ```java import org.bouncycastle.crypto.BlockCipher; import org.bouncycastle.crypto.engines.SM4Engine; import org.bouncycastle.crypto.modes.CBCBlockCipher; import org.bouncycastle.crypto.params.KeyParameter; import org.bouncycastle.crypto.params.ParametersWithIV; import org.bouncycastle.util.encoders.Hex; import java.nio.charset.StandardCharsets; import java.security.SecureRandom; public class SM4Example { public static void main(String[] args) { // 待加密的数据 String plaintext = "Hello, world!"; byte[] plaintextBytes = plaintext.getBytes(StandardCharsets.UTF_8); // 生成随机密钥和IV byte[] key = new byte[16]; byte[] iv = new byte[16]; SecureRandom random = new SecureRandom(); random.nextBytes(key); random.nextBytes(iv); // 初始化SM4算法引擎和CBC模式 BlockCipher engine = new SM4Engine(); CBCBlockCipher cipher = new CBCBlockCipher(engine); // 将密钥和IV转换为参数 KeyParameter keyParam = new KeyParameter(key); ParametersWithIV params = new ParametersWithIV(keyParam, iv); // 加密数据 cipher.init(true, params); byte[] ciphertextBytes = new byte[cipher.getOutputSize(plaintextBytes.length)]; int len = cipher.processBytes(plaintextBytes, 0, plaintextBytes.length, ciphertextBytes, 0); try { cipher.doFinal(ciphertextBytes, len); } catch (Exception e) { e.printStackTrace(); } String ciphertext = Hex.toHexString(ciphertextBytes); System.out.println("加密后的数据:" + ciphertext); // 解密数据 cipher.init(false, params); byte[] decryptedBytes = new byte[cipher.getOutputSize(ciphertextBytes.length)]; len = cipher.processBytes(ciphertextBytes, 0, ciphertextBytes.length, decryptedBytes, 0); try { cipher.doFinal(decryptedBytes, len); } catch (Exception e) { e.printStackTrace(); } String decryptedText = new String(decryptedBytes, StandardCharsets.UTF_8); System.out.println("解密后的数据:" + decryptedText); } } ``` 该示例程序使用Bouncy Castle库的SM4引擎和CBC模式对数据进行加解密,并将结果输出到控制台。需要注意的是,SM4算法使用128位密钥和128位IV,因此在示例程序中生成了随机的16字节密钥和IV。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值