自学内容网 自学内容网

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


原文地址:https://blog.csdn.net/weixin_61769998/article/details/142594992

免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!