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

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();
                            }
                        }
                    }
                }
            }
        }
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

A_ugust__

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

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

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

打赏作者

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

抵扣说明:

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

余额充值