尤其在公网之中,数据的安全及其的重要,除过我们使用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博客