使用AES对称加密在C#中实现数据库敏感数据加密存储,通过生成密钥和IV并安全保存,利用Aes类将明文加密为Base64字符串存入NVARCHAR或VARBINARY字段,读取时逆向解密;密钥应通过环境变量或密钥管理服务保护,避免硬编码;仅对身份证、手机号等敏感字段加密,密码须用哈希处理。

在C#中实现数据库数据的加密存储,核心思路是在数据写入数据库前进行加密,读取时再解密。这样即使数据库被非法访问,敏感信息也不会明文暴露。以下是常用且实用的方法。
AES(Advanced Encryption Standard)是最常用的对称加密算法,加解密速度快,适合大量数据处理。
实现步骤:
示例代码片段:
using System.Security.Cryptography;
using System.Text;
<p>public class AesEncryption
{
private static byte[] key = { /<em> 32字节密钥 </em>/ };
private static byte[] iv = { /<em> 16字节IV </em>/ };</p><pre class='brush:php;toolbar:false;'>public static string Encrypt(string plainText)
{
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
ICryptoTransform encryptor = aes.CreateEncryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, encryptor, CryptoStreamMode.Write))
{
using (StreamWriter sw = new StreamWriter(cs))
{
sw.Write(plainText);
}
return Convert.ToBase64String(ms.ToArray());
}
}
}
}
public static string Decrypt(string cipherText)
{
byte[] bytes = Convert.FromBase64String(cipherText);
using (Aes aes = Aes.Create())
{
aes.Key = key;
aes.IV = iv;
ICryptoTransform decryptor = aes.CreateDecryptor(aes.Key, aes.IV);
using (MemoryStream ms = new MemoryStream(bytes))
{
using (CryptoStream cs = new CryptoStream(ms, decryptor, CryptoStreamMode.Read))
{
using (StreamReader sr = new StreamReader(cs))
{
return sr.ReadToEnd();
}
}
}
}
}}
加密的安全性依赖于密钥保护。直接把密钥写在代码里非常危险。
推荐做法:
加密后数据是二进制或Base64字符串,因此数据库字段应设为:
不是所有数据都需要加密。建议只对敏感字段加密,例如:
基本上就这些。关键是选对算法、管好密钥、合理设计字段。不复杂但容易忽略细节。
以上就是如何用C#实现数据库数据的加密存储?方法是什么?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号