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();
                            }
                        }
                    }
                }
            }
        }
    }
}
相关推荐
iknow1813 小时前
【前端安全】js逆向之微信公众号登录密码
开发语言·前端·javascript
面包会有的,牛奶也会有的。3 小时前
python测试开发---前后端交互Axios
开发语言·前端·vue.js·交互
Her...4 小时前
electron教程(三)窗口设置
前端·javascript·electron
frankz614 小时前
新版统信UOS系统 electron sandbox与GPU兼容问题
前端·javascript·electron
_.Switch4 小时前
边缘计算与 Python Web 应用:从理论到实践
开发语言·前端·人工智能·python·架构·log4j·边缘计算
2401_857297914 小时前
秋招内推2025--招联金融
java·前端·算法·金融·求职招聘
优雅永不过时·5 小时前
three.js 通过着色器实现热力图效果
前端·javascript·智慧城市·three.js·热力图·着色器
lizi888885 小时前
手把手教你用Python进行Web抓取(附代码)
前端·python·php
小彭努力中5 小时前
45. 圆形平面设置纹理贴图
前端·3d·webgl·贴图