一種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);}}
}

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/pingmian/82509.shtml
繁體地址,請注明出處:http://hk.pswp.cn/pingmian/82509.shtml
英文地址,請注明出處:http://en.pswp.cn/pingmian/82509.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

“軒轅杯“云盾礪劍CTF挑戰賽 Web wp

文章目錄 ezflaskezjsezrceezssrf1.0簽到ezsql1.0ez_web1非預期預期解 ezflask ssti, 過濾了一些關鍵詞, 繞一下就行 name{{url_for["__globals__"]["__builtins__"]["eval"]("__tropmi__"[::-1])(os)["po""pen"…

Matlab快速上手五十六:詳解符號運算里假設的用法,通過假設可以設置符號變量的取值范圍,也可以通過假設設置變量屬于集合:整數、正數和實數等

1.符號變量中假設的概念 在符號數學工具箱中&#xff0c;符號變量默認范圍是全體復數&#xff0c;也就是說&#xff0c;符號運算是在全體復數域進行的&#xff0c;若需要運算中&#xff0c;不使用全體復數域&#xff0c;可以為變量設定取值范圍&#xff0c;這就用到了假設&…

【python實用小腳本-79】[HR轉型]Excel難民到數據工程師|用Python實現CSV秒轉JSON(附HRIS系統對接方案)

場景故事&#xff1a;從手動復制粘貼到自動化數據流轉 "Kelly&#xff0c;我們需要把3000名員工的考勤數據導入新HR系統&#xff0c;今天能完成嗎&#xff1f;"去年這個時候&#xff0c;作為HRIS項目負責人的我&#xff0c;面對這個需求時第一反應是打開Excel開始手…

數據透視:水安 B 證如何影響水利企業的生存指數?

某大數據公司提取了 3000 家水利企業的經營數據&#xff0c;一組關聯分析令人震驚&#xff1a;B 證配備率與企業利潤率的相關系數達 0.67—— 這意味著持證率每提升 10%&#xff0c;企業利潤率平均提高 4.2 個百分點。當我們用數據解剖這本紅本本&#xff0c;會發現它像一根無形…

從零搭建上門做飯平臺:高并發訂單系統設計

你知道為什么聰明人都在搶著做上門做飯平臺嗎&#xff1f;因為這可能是餐飲行業最后一片藍海&#xff01;傳統餐飲還在為房租人工發愁時&#xff0c;上門私廚已經輕裝上陣殺出重圍。不需要門店租金&#xff0c;不用養服務員&#xff0c;廚師直接上門服務&#xff0c;成本直降60…

openpi π? 項目部署運行邏輯(四)——機器人主控程序 main.py — aloha_real

π? 機器人主控腳本都在 examples 中&#xff1a; 可以看到包含了多種類機器人適配 此筆記首先記錄了 aloha_real 部分 aloha_real 中&#xff0c;main.py 是 openpi ALOHA 平臺上“主控執行入口”&#xff0c;負責&#xff1a; 建立與推理服務器&#xff08;serve_policy.…

利用 Python 爬蟲獲取唯品會 VIP 商品詳情:實戰指南

在當今電商競爭激烈的環境中&#xff0c;VIP 商品往往是商家的核心競爭力所在。這些商品不僅代表著品牌的高端形象&#xff0c;更是吸引高價值客戶的關鍵。因此&#xff0c;獲取 VIP 商品的詳細信息對于市場分析、競品研究以及優化自身產品策略至關重要。Python 作為一種強大的…

鴻蒙桌面快捷方式開發

桌面快捷方式開發實戰 [參考文檔] (https://developer.huawei.com/consumer/cn/doc/best-practices/bpta-desktop-shortcuts) 在module.json5配置文件中的abilities標簽下的metadata中設置resource屬性值為$profile:shortcuts_config&#xff0c;指定應用的快捷方式配置文件&…

3分鐘學會跨瀏覽器富文本編輯器開發:精準光標定位+內容插入(附完整代碼)

一、痛點直擊&#xff1a;傳統編輯器的三大坑 作為前端開發&#xff0c;你是否遇到過以下靈魂拷問&#xff1f; ? 為什么Firefox光標能精準定位&#xff0c;IE卻永遠跳轉到開頭&#xff1f;? 圖片上傳后如何保證插入位置不偏移&#xff1f;? 跨瀏覽器兼容測試時&#xff0…

RK3562 Linux-5.10 內核HUSB311 Type-C 控制器芯片調試記錄

硬件原理&#xff1a; 1. type C 接口&#xff1a; 1.1 HUSB311芯片&#xff0c; CC1和CC2 邏輯接到HUSB311 上面&#xff0c; 接I2C0組和USBCC_INT_L USBCC_INT_L 接到GPIO0_A6 做為CC的邏輯中斷 1.2 TYPEC_DP/TYPEC_DM 接到ARM 端的USB3.0 OTG上面 1.2 TYPEC_RX1P/TYPEC…

深入理解Java中的BigDecimal:高精度計算的核心工具

精心整理了最新的面試資料和簡歷模板&#xff0c;有需要的可以自行獲取 點擊前往百度網盤獲取 點擊前往夸克網盤獲取 引言 在Java編程中&#xff0c;處理浮點數運算時可能會遇到精度丟失的問題。例如&#xff1a; System.out.println(0.1 0.2); // 輸出&#xff1a;0.30000…

大模型微調(面經總結)

持續更新中 一、LORA篇1、介紹一下Lora的原理2、LoRA 是為了解決什么問題提出的&#xff1f;哪些模型適合用 LoRA 微調&#xff1f;什么是低秩分解&#xff1f;**低秩分解&#xff1a;用小矩陣逼近大矩陣** 3、LoRA初始化4、LoRA初始化秩 r 是怎么選的&#xff1f;為什么不選其…

Camera相機人臉識別系列專題分析之一:人臉識別系列專題SOP及理論知識介紹

【關注我&#xff0c;后續持續新增專題博文&#xff0c;謝謝&#xff01;&#xff01;&#xff01;】 上一篇我們講了&#xff1a;內存泄漏和內存占用拆解系列專題 這一篇我們開始講&#xff1a; Camera相機人臉識別系列專題分析之一&#xff1a;人臉識別系列專題SOP及理論知識…

【Elasticsearch】PUT` 請求覆蓋式更新

是的&#xff0c;Elasticsearch 中的 PUT 請求是覆蓋式的。當你使用 PUT 請求向索引中寫入文檔時&#xff0c;如果文檔已經存在&#xff0c;Elasticsearch 會完全替換整個文檔的內容&#xff0c;而不是進行部分更新。 覆蓋式的具體行為 - 文檔存在時&#xff1a;PUT 請求會用新…

計算機系統結構-第4章-數據級并行

數據集并行的概念: 并行場景1: 對不同數據執行相同的操作: 串行執行: 可以同時進行: 可以嘗試一個多條指令,多核執行 引入: SISD: 單核,單線程,串行執行,這樣耗時 MIMD: 多核,多線程,并行執行,一條指令多次重復,變成了MIMID 存在的問題: 在標量CPU流水線中&#xff0…

重新安裝解決mac vscode點擊不能跳轉問題

依次執行以下過程 刪除vscode程序 刪除vscode的緩存文件夾(xxx表示你的用戶名) /Users/xxx/Library/Application Support/Code 重新安裝vscode 這時候你會反向可以跳轉項目內的import 文件以及自定義函數。但是import安裝的包還不能點擊跳轉 配置python環境 如果你電腦沒有安…

題目 3334: 藍橋杯2025年第十六屆省賽真題-園藝

題目 3334: 藍橋杯2025年第十六屆省賽真題-園藝 時間限制: 2s 內存限制: 192MB 提交: 129 解決: 37 題目描述 小藍從左到右種了 n 棵小樹&#xff0c;第 i 棵樹的高度為 hi &#xff0c;相鄰樹的間隔相同。 小藍想挪走一些樹使得剩下的樹等間隔分布&#xff0c;且從左到右高度逐…

Chrome 開發中的任務調度與線程模型實戰指南

內容 概述 快速入門指南 核心概念線程詞典 線程任務優先使用序列而不是物理線程 發布并行任務 直接發布到線程池通過 TaskRunner 發布 發布順序任務 發布到新序列發布到當前&#xff08;虛擬&#xff09;主題 使用序列代替鎖將多個任務發布到同一線程 發布到瀏覽器進程中的主線…

詳解osgb的頂點,紋理,索引,UV讀取與存儲

virtual void apply(osg::Geode& node) {for (int i 0; i < node.getNumDrawables(); i){osg::Geometry* geometry dynamic_cast<osg::Geometry*>(node.getDrawable(i));if (geometry){//apply(*g);//***********************************************//解析頂點…

CSS闖關指南:從手寫地獄到“類”積木之旅|得物技術

一、背景 在Web開發網頁設計中&#xff0c;CSS&#xff08;層疊樣式表&#xff09;扮演著至關重要的角色&#xff0c;它用于控制網頁的布局、外觀和視覺效果。CSS不僅可以美化網頁的視覺表現&#xff0c;還可以提高網頁的可訪問性、可維護性和響應式設計。在我們進行網頁開發的…