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();
                            }
                        }
                    }
                }
            }
        }
    }
}
相关推荐
开心工作室_kaic1 小时前
ssm161基于web的资源共享平台的共享与开发+jsp(论文+源码)_kaic
java·开发语言·前端
刚刚好ā1 小时前
js作用域超全介绍--全局作用域、局部作用、块级作用域
前端·javascript·vue.js·vue
向宇it1 小时前
【unity小技巧】unity 什么是反射?反射的作用?反射的使用场景?反射的缺点?常用的反射操作?反射常见示例
开发语言·游戏·unity·c#·游戏引擎
九鼎科技-Leo1 小时前
什么是 WPF 中的依赖属性?有什么作用?
windows·c#·.net·wpf
沉默璇年2 小时前
react中useMemo的使用场景
前端·react.js·前端框架
yqcoder2 小时前
reactflow 中 useNodesState 模块作用
开发语言·前端·javascript
Heaphaestus,RC2 小时前
【Unity3D】获取 GameObject 的完整层级结构
unity·c#
2401_882727572 小时前
BY组态-低代码web可视化组件
前端·后端·物联网·低代码·数学建模·前端框架
baivfhpwxf20232 小时前
C# 5000 转16进制 字节(激光器串口通讯生成指定格式命令)
开发语言·c#
直裾3 小时前
Scala全文单词统计
开发语言·c#·scala