技术文摘
在 C# 里对 JSON 数据进行 AES 加密与解密
2024-12-30 17:20:52 小编
在 C# 里对 JSON 数据进行 AES 加密与解密
在当今数字化时代,数据安全至关重要。对 JSON 数据进行加密和解密是保护敏感信息的常见需求。在 C# 中,我们可以使用高级加密标准(AES)来实现这一目标。
AES 是一种对称加密算法,它使用相同的密钥进行加密和解密。我们需要引入相关的命名空间。
using System;
using System.Security.Cryptography;
using System.Text;
接下来,定义加密和解密的方法。
public static class AesEncryption
{
public static string EncryptJson(string json, string key)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = new byte[aesAlg.BlockSize / 8];
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(json);
}
}
return Convert.ToBase64String(msEncrypt.ToArray());
}
}
}
public static string DecryptJson(string encryptedJson, string key)
{
using (Aes aesAlg = Aes.Create())
{
aesAlg.Key = Encoding.UTF8.GetBytes(key);
aesAlg.IV = new byte[aesAlg.BlockSize / 8];
ICryptoTransform decryptor = aesAlg.CreateDecryptor(aesAlg.Key, aesAlg.IV);
using (MemoryStream msDecrypt = new MemoryStream(Convert.FromBase64String(encryptedJson)))
{
using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
{
using (StreamReader srDecrypt = new StreamReader(csDecrypt))
{
return srDecrypt.ReadToEnd();
}
}
}
}
}
}
在实际使用中,我们先指定一个密钥,然后调用加密方法对 JSON 数据进行加密。
string json = "{"name":"John","age":30}";
string key = "MySecretKey123";
string encryptedJson = AesEncryption.EncryptJson(json, key);
要解密加密后的 JSON 数据,只需调用解密方法。
string decryptedJson = AesEncryption.DecryptJson(encryptedJson, key);
通过在 C# 中对 JSON 数据进行 AES 加密和解密,我们能够有效地保护数据的机密性,确保敏感信息在传输和存储过程中的安全。
需要注意的是,密钥的管理和保护至关重要。应确保密钥的安全性,避免泄露,以保障加密的有效性。AES 加密虽然强大,但也需要根据具体的安全需求和合规要求来合理应用。
- Golang函数中类型断言与反射的异同
- PHP函数面试必知:掌握网络函数的客户端与服务器交互要点
- PHP函数代码风格新动态
- 如何用火焰图可视化 Golang 函数并发任务的执行
- PHP 函数与第三方库整合指南
- 运用人工智能提升C代码可维护性的方法
- C++ 函数性能优化终极秘籍:构建超高速代码
- 用Golang函数实现数据可视化及图表化的方法
- PHP函数面试必知:揭秘图像处理函数应用领域
- php函数代码部署优化的最佳架构
- PHP函数优化时的数据结构挑选
- C++ 友元函数:错误处理与调试的得力助手
- C语言函数指针和回调函数的关联是什么
- 自定义函数与 PHP 扩展函数如何交互
- PHP函数性能分析工具:剖析不同函数类型的实用工具