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

csharp 复制代码
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;

// AES
using System.IO;
using System.Security.Cryptography;
using Microsoft.EntityFrameworkCore.Metadata.Internal;

namespace yc_api.Controllers
{
    [Route("restful/[controller]")]
    [ApiController]
    public class RpcController : ControllerBase
    {
        private ILogger<RpcController> _logger;
        private readonly IConfiguration _configuration;
        
        public RpcController(ILogger<RpcController> logger, IConfiguration configuration)
        {
            _logger = logger;
            _configuration = configuration;
        }

        // POST api/values
        [EnableCors("cors")]
        [HttpPost]
        public ActionResult Post([FromBody] JObject requestData)
        {
            dynamic rv = new ExpandoObject();
            rv.success = false;

            // 生成AES256位密钥
            //using (var rng = new RNGCryptoServiceProvider())
            //{
            //    byte[] key = new byte[32]; // 256 位密钥
            //    rng.GetBytes(key);
            //    return new JsonResult(key);
            //    Console.WriteLine(BitConverter.ToString(key).Replace("-", "").ToLower());
            //} originalText = "Hello, World!";

            // 加密
            //string encryptedText = AesEncryption.Encrypt(originalText);
            //rv.encryptedText = encryptedText;

            //var str = requestData["encryptedData"].ToString();

             解密
            //string decryptedText = AesEncryption.Decrypt(str);
            //rv.decryptedText = decryptedText;


            try
            {
                string encryptedData = requestData["encryptedData"].ToString();

                if (string.IsNullOrEmpty(encryptedData))
                {
                    return BadRequest("Encrypted data is missing.");
                }

                string decryptedJson = AesEncryption.Decrypt(encryptedData);
                var data = JsonConvert.DeserializeObject(decryptedJson);

                return Ok(data);
            }
            catch (CryptographicException ex)
            {
                return BadRequest($"Decryption error: {ex.Message}");
            }
            catch (Exception ex)
            {
                return BadRequest($"Error: {ex.Message}");
            }
            return new JsonResult(rv);
        }

        // GET api/values/5
        [HttpGet("{id}")]
        public ActionResult<string> Get(int id)
        {
            return "value";
        }

        // PUT api/values/5
        [HttpPut("{id}")]
        public void Put(int id, [FromBody] string value)
        {
        }

        // DELETE api/values/5
        [HttpDelete("{id}")]
        public void Delete(int id)
        {
        }

        public class AesEncryption
        {
            private static readonly byte[] Key = Convert.FromBase64String("");
            private static readonly byte[] IV = new byte[16]; // 初始化向量(IV)

            public static string Encrypt(string plainText)
            {
                using (var aes = Aes.Create())
                {
                    aes.Key = Key;
                    aes.IV = IV;
                    aes.Padding = PaddingMode.PKCS7; // 设置填充模式
                    aes.Mode = CipherMode.CBC; // 设置模式为 CBC

                    using (var ms = new MemoryStream())
                    {
                        using (var cryptoStream = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
                        {
                            using (var writer = new StreamWriter(cryptoStream))
                            {
                                writer.Write(plainText);
                            }
                        }
                        return Convert.ToBase64String(ms.ToArray());
                    }
                }
            }

            public static string Decrypt(string cipherText)
            {
                byte[] cipherBytes = Convert.FromBase64String(cipherText); // 先转换为 byte[]

                using (var aes = Aes.Create())
                {
                    aes.Key = Key;
                    //aes.IV = IV;
                    aes.IV = Encoding.UTF8.GetBytes(""); // 确保 IV 一致

                    aes.Padding = PaddingMode.PKCS7; // 设置填充模式
                    aes.Mode = CipherMode.CBC; // 设置模式为 CBC

                    using (var ms = new MemoryStream(cipherBytes))
                    {
                        using (var cryptoStream = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Read))
                        {
                            using (var reader = new StreamReader(cryptoStream))
                            {
                                return reader.ReadToEnd();
                            }
                        }
                    }
                }
            }
        }
    }
}
相关推荐
王解3 分钟前
掌握 Jest 中的模拟函数:提升单元测试的效率与可靠性
前端·javascript·单元测试·es6
qq229511650212 分钟前
asp.net+uniapp养老助餐管理系统 微信小程序
微信小程序·uni-app·asp.net
floret*26 分钟前
在 hiveSQL 中判断一个字段是否包含某个值
前端·javascript·数据库
2301_7969821429 分钟前
‌webdriver.Chrome()参数简介
前端·chrome·python
yqcoder1 小时前
electron 中 ipcRenderer 作用
前端·javascript·electron
时光追逐者1 小时前
Visual Studio 2022:一个功能全面且强大的IDE
ide·c#·.net·.netcore·visual studio
zls3653651 小时前
C# WPF 与 JS 交互可以使用的第三方库
开发语言·javascript·c#·wpf·交互
前端李易安2 小时前
webpack的常见配置
前端·webpack·node.js
VinciYan2 小时前
.NET使用TDengine时序数据库和SqlSugar操作TDengine
大数据·c#·.net·tdengine