C#中.net8WebApi加密解密

2024-05-05 06:12

本文主要是介绍C#中.net8WebApi加密解密,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

        尤其在公网之中,数据的安全及其的重要,除过我们使用jwt之外,还可以对传送的数据进行加密,就算别人使用抓包工具,抓到数据,一时半会儿也解密不了数据,当然,加密也影响了效率,肯定不如明文传递的效率高。

1.创建一个.net8WebApi

2. 建立一个学生类的实体类,Student.cs

namespace WebApplication2.Entity
{public class Student{public int Id { get; set; }public string Name { get; set; }public int Age { get; set; }public string Address { get; set; }}
}

3.建立加密,解密的方法

using System.Security.Cryptography;
using System.Text;namespace WebApplication2.Common
{public static class PublicMethod{public static byte[] key = Encoding.UTF8.GetBytes("12345678123456781234567812345678");  //32位,自己可以定义public static byte[] iv = Encoding.UTF8.GetBytes("1234567812345678"); //16位,自己可以定义/// <summary>/// 加密/// </summary>/// <param name="cipherText"></param>/// <param name="Key"></param>/// <param name="IV"></param>/// <returns></returns>/// <exception cref="ArgumentNullException"></exception>public static string DecryptStringFromBytes_Aes(byte[] cipherText, byte[] Key, byte[] IV){if (cipherText == null || cipherText.Length <= 0)throw new ArgumentNullException(nameof(cipherText));if (Key == null || Key.Length <= 0)throw new ArgumentNullException(nameof(Key));if (IV == null || IV.Length <= 0)throw new ArgumentNullException(nameof(IV));string plaintext = null;using (Aes aesAlg = Aes.Create()){aesAlg.Key = Key;aesAlg.IV = IV;ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);using (MemoryStream msDecrypt = new MemoryStream(cipherText)){using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read)){using (StreamReader srDecrypt = new StreamReader(csDecrypt)){plaintext = srDecrypt.ReadToEnd();}}}}return plaintext;}/// <summary>/// 解密/// </summary>/// <param name="plainText"></param>/// <param name="Key"></param>/// <param name="IV"></param>/// <returns></returns>/// <exception cref="ArgumentNullException"></exception>public static byte[] EncryptStringToBytes_Aes(string plainText, byte[] Key, byte[] IV){if (plainText == null || plainText.Length <= 0)throw new ArgumentNullException(nameof(plainText));if (Key == null || Key.Length <= 0)throw new ArgumentNullException(nameof(Key));if (IV == null || IV.Length <= 0)throw new ArgumentNullException(nameof(IV));byte[] encrypted;using (Aes aesAlg = Aes.Create()){aesAlg.Key = Key;aesAlg.IV = IV;ICryptoTransform encryptor = aesAlg.CreateEncryptor(aesAlg.Key, aesAlg.IV);using (MemoryStream msEncrypt = new MemoryStream()){using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write)){using (StreamWriter swEncrypt = new StreamWriter(csEncrypt)){swEncrypt.Write(plainText);}encrypted = msEncrypt.ToArray();}}}return encrypted;}}
}

4.使用

写一个GetStudent()方法,进行加密

using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Nodes;
using System.Text.Json;
using WebApplication2.Entity;
using WebApplication2.Common;namespace WebApplication2.Controllers
{[ApiController][Route("api/[controller]/[action]")]public class WeatherForecastController : ControllerBase{private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};private readonly ILogger<WeatherForecastController> _logger;public WeatherForecastController(ILogger<WeatherForecastController> logger){_logger = logger;}[HttpGet]public Task<string> GetStudent(){Student student = new Student();student.Id = 1;student.Name = "John";student.Age = 25;student.Address = "New York";  //增加实体类属性string jsonString = JsonSerializer.Serialize(student); //序列化对象byte[] encrypted = PublicMethod.EncryptStringToBytes_Aes(jsonString, PublicMethod.key, PublicMethod.iv); //加密string encryptedString = Convert.ToBase64String(encrypted); //转换为base64字符串return Task.FromResult<string>(encryptedString);   //返回加密后的字符串}[HttpGet(Name = "GetWeatherForecast")]public IEnumerable<WeatherForecast> Get(){return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),TemperatureC = Random.Shared.Next(-20, 55),Summary = Summaries[Random.Shared.Next(Summaries.Length)]}).ToArray();}}
}

5.运行后的结果

点击GetStudent方法获取的结果是

yF9I1zV4iB43L9tDi+UEH/Xs3aPayl7C5stjk0yOl9L/s92Xup9NVZvOLKSGz4e0EL4ruJRGedhCUlxEknMzXQ==

此时,数据已经加密成功了。 可以传递给前端进行使用了,前端拿到再进行解密。

6.写一个获取到前端加密的字符串,然后进行解密

using Microsoft.AspNetCore.DataProtection.KeyManagement;
using Microsoft.AspNetCore.Mvc;
using System.Text.Json.Nodes;
using System.Text.Json;
using WebApplication2.Entity;
using WebApplication2.Common;namespace WebApplication2.Controllers
{[ApiController][Route("api/[controller]/[action]")]public class WeatherForecastController : ControllerBase{private static readonly string[] Summaries = new[]{"Freezing", "Bracing", "Chilly", "Cool", "Mild", "Warm", "Balmy", "Hot", "Sweltering", "Scorching"};private readonly ILogger<WeatherForecastController> _logger;public WeatherForecastController(ILogger<WeatherForecastController> logger){_logger = logger;}[HttpGet]public Task<string> GetStudent(){Student student = new Student();student.Id = 1;student.Name = "John";student.Age = 25;student.Address = "New York";  //增加实体类属性string jsonString = JsonSerializer.Serialize(student); //序列化对象byte[] encrypted = PublicMethod.EncryptStringToBytes_Aes(jsonString, PublicMethod.key, PublicMethod.iv); //加密string encryptedString = Convert.ToBase64String(encrypted); //转换为base64字符串return Task.FromResult<string>(encryptedString);   //返回加密后的字符串}[HttpPost]public Task<bool> GetStudent1(string strStudent){byte[] str = Convert.FromBase64String(strStudent);  //字符串转换为字节数组string jsonString = PublicMethod.DecryptStringFromBytes_Aes(str, PublicMethod.key, PublicMethod.iv); //解密Student student = JsonSerializer.Deserialize<Student>(jsonString); //反序列化对象//这里可以对student进行业务操作return Task.FromResult<bool>(true);   //返回加密后的字符串}[HttpGet(Name = "GetWeatherForecast")]public IEnumerable<WeatherForecast> Get(){return Enumerable.Range(1, 5).Select(index => new WeatherForecast{Date = DateOnly.FromDateTime(DateTime.Now.AddDays(index)),TemperatureC = Random.Shared.Next(-20, 55),Summary = Summaries[Random.Shared.Next(Summaries.Length)]}).ToArray();}}
}

7.运行后

我们把刚才的字符串传递进去,然后在程序内部调试,能看得到数据

在程序内部,看到了数据,说明解密成功。

本文源码:

https://download.csdn.net/download/u012563853/89261917

本文来源:

C#中.net8WebApi加密解密-CSDN博客

这篇关于C#中.net8WebApi加密解密的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/960966

相关文章

利用python实现对excel文件进行加密

《利用python实现对excel文件进行加密》由于文件内容的私密性,需要对Excel文件进行加密,保护文件以免给第三方看到,本文将以Python语言为例,和大家讲讲如何对Excel文件进行加密,感兴... 目录前言方法一:使用pywin32库(仅限Windows)方法二:使用msoffcrypto-too

C#使用StackExchange.Redis实现分布式锁的两种方式介绍

《C#使用StackExchange.Redis实现分布式锁的两种方式介绍》分布式锁在集群的架构中发挥着重要的作用,:本文主要介绍C#使用StackExchange.Redis实现分布式锁的... 目录自定义分布式锁获取锁释放锁自动续期StackExchange.Redis分布式锁获取锁释放锁自动续期分布式

C# foreach 循环中获取索引的实现方式

《C#foreach循环中获取索引的实现方式》:本文主要介绍C#foreach循环中获取索引的实现方式,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友参考下吧... 目录一、手动维护索引变量二、LINQ Select + 元组解构三、扩展方法封装索引四、使用 for 循环替代

C# Where 泛型约束的实现

《C#Where泛型约束的实现》本文主要介绍了C#Where泛型约束的实现,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧... 目录使用的对象约束分类where T : structwhere T : classwhere T : ne

C#实现将Excel表格转换为图片(JPG/ PNG)

《C#实现将Excel表格转换为图片(JPG/PNG)》Excel表格可能会因为不同设备或字体缺失等问题,导致格式错乱或数据显示异常,转换为图片后,能确保数据的排版等保持一致,下面我们看看如何使用C... 目录通过C# 转换Excel工作表到图片通过C# 转换指定单元格区域到图片知识扩展C# 将 Excel

C#中async await异步关键字用法和异步的底层原理全解析

《C#中asyncawait异步关键字用法和异步的底层原理全解析》:本文主要介绍C#中asyncawait异步关键字用法和异步的底层原理全解析,本文给大家介绍的非常详细,对大家的学习或工作具有一... 目录C#异步编程一、异步编程基础二、异步方法的工作原理三、代码示例四、编译后的底层实现五、总结C#异步编程

C#TextBox设置提示文本方式(SetHintText)

《C#TextBox设置提示文本方式(SetHintText)》:本文主要介绍C#TextBox设置提示文本方式(SetHintText),具有很好的参考价值,希望对大家有所帮助,如有错误或未考虑... 目录C#TextBox设置提示文本效果展示核心代码总结C#TextBox设置提示文本效果展示核心代

C#中DrawCurve的用法小结

《C#中DrawCurve的用法小结》本文主要介绍了C#中DrawCurve的用法小结,通常用于绘制一条平滑的曲线通过一系列给定的点,具有一定的参考价值,感兴趣的可以了解一下... 目录1. 如何使用 DrawCurve 方法(不带弯曲程度)2. 如何使用 DrawCurve 方法(带弯曲程度)3.使用Dr

Java中使用Hutool进行AES加密解密的方法举例

《Java中使用Hutool进行AES加密解密的方法举例》AES是一种对称加密,所谓对称加密就是加密与解密使用的秘钥是一个,下面:本文主要介绍Java中使用Hutool进行AES加密解密的相关资料... 目录前言一、Hutool简介与引入1.1 Hutool简介1.2 引入Hutool二、AES加密解密基础

使用C#代码在PDF文档中添加、删除和替换图片

《使用C#代码在PDF文档中添加、删除和替换图片》在当今数字化文档处理场景中,动态操作PDF文档中的图像已成为企业级应用开发的核心需求之一,本文将介绍如何在.NET平台使用C#代码在PDF文档中添加、... 目录引言用C#添加图片到PDF文档用C#删除PDF文档中的图片用C#替换PDF文档中的图片引言在当