C# ASP.NET CORE web api 实现sm2加密解密

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Dapper;
using System.Dynamic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System.Data;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
using System.IO;
using System.Text;
using Microsoft.AspNetCore.Cors;
using Microsoft.AspNetCore.Hosting.Server;

// sm2
using Org.BouncyCastle.Crypto;
using Org.BouncyCastle.Crypto.Parameters;
using Org.BouncyCastle.Security;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Math;
using Org.BouncyCastle.Crypto.Generators;
using Org.BouncyCastle.Crypto.Signers;
using Org.BouncyCastle.Crypto.Engines;
using Org.BouncyCastle.Crypto.Agreement;
using Org.BouncyCastle.Asn1.X9;
using Org.BouncyCastle.Utilities.Encoders;
using Org.BouncyCastle.Math.EC;


namespace yc_api.Controllers
{
    [Route("restful/[controller]")]
    [ApiController]
    public class RpcController : ControllerBase
    {
        private ILogger<RpcController> _logger;
        private readonly IConfiguration _configuration;
		string privateKey = "425d5298a76147560c2eb6e5680063146f169fc7b19bfa69e5d06112286d4895";
		string publicKey = "048f75cd8db30f242570f56bb6a39afa133c6828ec5f452159b3ad2a1d092bbc9c6994d9a34addd9f0c92a7ead66fe814c35a339ea67be1bf623f82d7001cbb6e8";

        public RpcController(ILogger<RpcController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        // GET restful/rpc

		[EnableCors("cors")]
		[HttpGet]
		public ActionResult Get([FromBody] JObject requestData)
		{
		    dynamic rv = new ExpandoObject();
		    rv.success = false;
		
		    GenerateSM2KeyPair(out privateKey, out publicKey);
			rv.privateKey = privateKey;
			rv.publicKey = publicKey;
			return new JsonResult(rv);
			
			//sm2加密
			string message = "{\"fendian_id\":0,\"db\":\"mssql\",\"function\":\"app_get_weixin_message\"}";
			string e = Encrypt(message, publicKey);
			// SM2解密;
			string d = Decrypt(e, privateKey);
			rv.jiami = e;
			rv.jiemi = d;
			return new JsonResult(rv);
			
			//SM2解密;
			string encryptedData = requestData["encryptedData"]?.ToString();
			if (!string.IsNullOrEmpty(encryptedData) && encryptedData.StartsWith("04"))
			{
			    // 去掉前面的 "04"
			    string hexData = encryptedData.Substring(2);
			    try
			    {
			        string decryptedData = Decrypt(hexData, privateKey);
			        rv.jiemi = decryptedData;
			        rv.success = true;
			    }
			    catch (Exception ex)
			    {
			        rv.err = $"解密失败: {ex.Message}";
			    }
			}
			else
			{
			    rv.err = "无效的加密数据格式";
			}
			return new JsonResult(rv);
			    return new JsonResult(rv);
			}
	// 生成 SM2 密钥对,密钥对使用 Base64 进行编码
public static void GenerateSM2KeyPair(out string privateKey, out string publicKey)
{
    // 获取 SM2 曲线参数
    X9ECParameters curve = ECNamedCurveTable.GetByName("sm2p256v1");
    KeyGenerationParameters parameters = new ECKeyGenerationParameters(new ECDomainParameters(curve), new SecureRandom());

    // 创建 SM2 密钥对生成器
    ECKeyPairGenerator generator = new ECKeyPairGenerator();
    generator.Init(parameters);

    // 创建密钥对
    var keyPair = generator.GenerateKeyPair();

    // 私钥
    ECPrivateKeyParameters privateKeyParameters = (ECPrivateKeyParameters)keyPair.Private;
    privateKey = ByteArrayToHexString(privateKeyParameters.D.ToByteArrayUnsigned());

    // 公钥
    ECPublicKeyParameters publicKeyParameters = (ECPublicKeyParameters)keyPair.Public;
    byte[] encodedPublicKey = publicKeyParameters.Q.GetEncoded();
    publicKey = ByteArrayToHexString(encodedPublicKey); // 转换为十六进制格式
}

// 辅助函数:将字节数组转换为十六进制字符串
private static string ByteArrayToHexString(byte[] bytes)
{
    return BitConverter.ToString(bytes).Replace("-", "").ToLowerInvariant();
}

//base64格式
/ SM2 公钥加密
public static string Encrypt(string message, string key)
{
    // 获取 SM2 曲线参数
    X9ECParameters curve = ECNamedCurveTable.GetByName("sm2p256v1");

    ECPoint q = curve.Curve.DecodePoint(Base64.Decode(key));
    ECDomainParameters domain = new ECDomainParameters(curve);
    ECPublicKeyParameters pubk = new ECPublicKeyParameters("EC", q, domain);

    // 创建SM2加密器
    SM2Engine sm2Engine = new SM2Engine();
    sm2Engine.Init(true, new ParametersWithRandom(pubk, new SecureRandom()));

    // 将原始数据转换为字节数组
    byte[] dataBytes = Encoding.UTF8.GetBytes(message);

    // 执行加密操作
    byte[] encryptedData = sm2Engine.ProcessBlock(dataBytes, 0, dataBytes.Length);

    // 将加密结果转换为 Base64 字符串
    return Base64.ToBase64String(encryptedData);
}


/// SM2 私钥解密
public static string Decrypt(string message, string key)
{
    // 获取 SM2 曲线参数
    X9ECParameters curve = ECNamedCurveTable.GetByName("sm2p256v1");

    ECDomainParameters domain = new ECDomainParameters(curve);
    BigInteger d = new BigInteger(1, Base64.Decode(key));
    ECPrivateKeyParameters prik = new ECPrivateKeyParameters(d, domain);

    // 创建SM2加密器
    SM2Engine sm2Engine = new SM2Engine();
    sm2Engine.Init(false, prik);

    byte[] encryptedData = Base64.Decode(message);

    // 执行解密操作
    byte[] decryptedData = sm2Engine.ProcessBlock(encryptedData, 0, encryptedData.Length);

    // 将解密结果转换为字符串
    return Encoding.UTF8.GetString(decryptedData);
}
	  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

A_ugust__

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值