当前位置: 首页 > news >正文

一种C# 的SM4 的 加解密的实现,一般用于医疗或者支付

一种C# 的SM4 的 加解密的实现

一般用于医疗或者支付

加密

 string cipherText = SM4Helper.Encrypt_test(data, key);

        public static string Encrypt_test(string plainText, string key)
        {

            byte[] keyBytes = Encoding.ASCII.GetBytes(key);
            byte[] inputBytes = Encoding.UTF8.GetBytes(plainText);

            // 初始化SM4引擎
            var engine = new SM4Engine();
            var cipher = new PaddedBufferedBlockCipher(engine, new Pkcs7Padding());
            cipher.Init(true, new KeyParameter(keyBytes));

            // 执行加密
            byte[] output = new byte[cipher.GetOutputSize(inputBytes.Length)];
            int len = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, output, 0);
            cipher.DoFinal(output, len);

            // 转换为大写十六进制字符串
            return BitConverter.ToString(output).Replace("-", "").ToUpper();
        }

解密

string decryptedText = SM4Helper.Decrypt_test(cipherText, key);

  public static string Decrypt_test(string plainText, string key)
        {

            byte[] keyBytes = Encoding.ASCII.GetBytes(key);
            byte[] inputBytes = FromHexString(plainText);

            // 初始化SM4引擎
            var engine = new SM4Engine();  
            var cipher = new PaddedBufferedBlockCipher(engine, new Pkcs7Padding());
            cipher.Init(false, new KeyParameter(keyBytes)); // false表示解密模式

            // 执行解密
            byte[] output = new byte[cipher.GetOutputSize(inputBytes.Length)];
            int len = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, output, 0);
            len += cipher.DoFinal(output, len);

            // 移除可能的填充字节
            byte[] result = new byte[len];
            Array.Copy(output, result, len);

            return Encoding.UTF8.GetString(result);
        }

SM4Helper 的全部代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Globalization;
using System.Text;
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Modes;
using Org.BouncyCastle.Crypto.Paddings;
using Org.BouncyCastle.Crypto.Parameters;namespace OneClikPay
{public class SM4Helper{/// <summary>/// SM4加密(ECB模式,PKCS7填充)/// </summary>public static string Encrypt(string plainText, string hexKey){byte[] keyBytes = FromHexString(hexKey); // 使用严格兼容的十六进制转换byte[] plainBytes = Encoding.UTF8.GetBytes(plainText);var cipher = CreateCipher(true, keyBytes);byte[] encrypted = cipher.DoFinal(plainBytes);return BytesToHex(encrypted);}/// <summary>/// SM4解密(ECB模式,PKCS7填充)/// </summary>public static string Decrypt(string hexCipherText, string hexKey){byte[] keyBytes = FromHexString(hexKey);byte[] cipherBytes = FromHexString(hexCipherText);var cipher = CreateCipher(false, keyBytes);byte[] decrypted = cipher.DoFinal(cipherBytes);return Encoding.UTF8.GetString(decrypted);}#region 核心加密模块private static BufferedBlockCipher CreateCipher(bool forEncryption, byte[] key){// 严格校验密钥长度if (key.Length != 16)throw new ArgumentException("密钥必须为128位(16字节)");IBlockCipher engine = new SM4Engine();var cipher = new PaddedBufferedBlockCipher(new EcbBlockCipher(engine), new Pkcs7Padding());cipher.Init(forEncryption, new KeyParameter(key));return cipher;}#endregion#region 完全兼容Java的十六进制转换(ByteUtils.fromHexString等效实现)public static byte[] FromHexString(string hex){if (hex == null)throw new ArgumentNullException(nameof(hex));hex = hex.Trim().Replace(" ", "").Replace("\n", "").Replace("\t", "");if (hex.Length % 2 != 0)throw new FormatException("十六进制字符串长度必须为偶数");byte[] bytes = new byte[hex.Length / 2];for (int i = 0; i < bytes.Length; i++){string hexByte = hex.Substring(i * 2, 2);if (!IsHexChar(hexByte[0]) || !IsHexChar(hexByte[1]))throw new FormatException($"非法十六进制字符: {hexByte}");bytes[i] = byte.Parse(hexByte, NumberStyles.HexNumber, CultureInfo.InvariantCulture);}return bytes;}private static bool IsHexChar(char c){return (c >= '0' && c <= '9') ||(c >= 'a' && c <= 'f') ||(c >= 'A' && c <= 'F');}private static string BytesToHex(byte[] bytes){StringBuilder hex = new StringBuilder(bytes.Length * 2);foreach (byte b in bytes){hex.AppendFormat("{0:X2}", b); // 强制大写,与Java的Hex.toHexString()一致}return hex.ToString();}#endregionpublic static string Encrypt_test(string plainText, string key){byte[] keyBytes = Encoding.ASCII.GetBytes(key);byte[] inputBytes = Encoding.UTF8.GetBytes(plainText);// 初始化SM4引擎var engine = new SM4Engine();var cipher = new PaddedBufferedBlockCipher(engine, new Pkcs7Padding());cipher.Init(true, new KeyParameter(keyBytes));// 执行加密byte[] output = new byte[cipher.GetOutputSize(inputBytes.Length)];int len = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, output, 0);cipher.DoFinal(output, len);// 转换为大写十六进制字符串return BitConverter.ToString(output).Replace("-", "").ToUpper();}public static string Decrypt_test(string plainText, string key){byte[] keyBytes = Encoding.ASCII.GetBytes(key);byte[] inputBytes = FromHexString(plainText);// 初始化SM4引擎var engine = new SM4Engine();  var cipher = new PaddedBufferedBlockCipher(engine, new Pkcs7Padding());cipher.Init(false, new KeyParameter(keyBytes)); // false表示解密模式// 执行解密byte[] output = new byte[cipher.GetOutputSize(inputBytes.Length)];int len = cipher.ProcessBytes(inputBytes, 0, inputBytes.Length, output, 0);len += cipher.DoFinal(output, len);// 移除可能的填充字节byte[] result = new byte[len];Array.Copy(output, result, len);return Encoding.UTF8.GetString(result);}}
}

相关文章:

  • 多线程(1)
  • ODSA架构与操作-1
  • 2025最新Gemini 2.5 Pro API限制全面解析:最完整的使用指南与优化方案
  • 做好测试用例设计工作的关键是什么?
  • 仓颉入门:特性
  • 嵌入式自学第二十九天(5.27)
  • DFS入门刷题c++
  • AI 智能体的那些事—架构设计关键点
  • 数据库管理与高可用-MySQL数据库初体验
  • Java 内存模型与 volatile 关键字深度解析:从可见性到指令重排
  • 【键盘说明书备份】ENERGYFORT
  • 什么是舵机,如何控制舵机
  • LVGL(Grid)
  • 用Qt/C++玩转观察者模式:一个会聊天的设计模式
  • Baklib企业CMS实现内容智能归档与精准检索
  • 红黑树,B树,二叉树之间的不同
  • C++类继承详解:权限控制与继承方式解析
  • Gemini Pro 2.5 输出
  • AI 编程如何让你轻松采集网站数据?
  • 第二十一章:数据治理之数据安全:数据安全的驱动因素以及常见的数据安全举措
  • 类豆瓣的模板 wordpress/宁波seo快速优化平台
  • 私服网站建设/潍坊百度快速排名优化
  • 做网站绿色和什么颜色搭配/百度如何发布作品
  • 深圳网站制作公司讯息/今日国内新闻头条新闻
  • 有口碑的模板网站建设/优化网站制作方法大全
  • 网站是否必须做可信网站认证/昆明seo排名外包