AES对称加密
在数据库设计中尤其在设计用户数据表时通常都要考虑用户数据加密的情况数据表中不明文显示用户信息避免泄露用户隐私。针对用户姓名、手机号、身份证号等敏感信息可以采用AES对称加密。与Hash加密不同的是AES对称加密是可逆的通过解密数据库的信息可以还原完整信息显示。为了防止数据库泄露窃取者还原用户信息在使用AES加密时需要用到密钥文件。这里建议密钥文件单独保存。代码文件结构AesKeyManager(密钥管理器)AesHelper密钥工具类。一、密钥文件C#内置AES 不需要添加第三方依赖。/// summary/// 密钥管理器/// /summarypublicstaticclassAesKeyManager{privatestaticreadonlystringappPathPath.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),MyPro);privatestaticreadonlystringKeyFilePath.Combine(appPath,aes.key);/// summary/// 获取AES Key/// 首次获取自动生成/// /summary/// returns/returnspublicstaticbyte[]GetKey(){if(!File.Exists(KeyFile)){CreateKey();}byte[]protectedKeyFile.ReadAllBytes(KeyFile);returnProtectedData.Unprotect(protectedKey,null,DataProtectionScope.CurrentUser);}publicstaticvoidCreateKey(){Directory.CreateDirectory(appPath);byte[]aseKeyRandomNumberGenerator.GetBytes(32);byte[]protectedKeyProtectedData.Protect(aseKey,null,DataProtectionScope.CurrentUser);File.WriteAllBytes(KeyFile,protectedKey);}/// summary/// AES Key 文件路径/// /summarypublicstaticstringKeyFilePathKeyFile;}二、密钥工具类/// summary/// AES 工具类/// /summarypublicstaticclassAesHelper{/// summary/// 加密/// /summary/// param nameplainText/param/// returns/returnspublicstaticstringEncrypt(stringplainText){byte[]keyAesKeyManager.GetKey();usingAesaesAes.Create();aes.Keykey;aes.GenerateIV();// 每次随机生成 IVusingMemoryStreammsnew();ms.Write(aes.IV);usingCryptoStreamcsnew(ms,aes.CreateEncryptor(),CryptoStreamMode.Write);usingStreamWriterswnew(cs);sw.Write(plainText);sw.Close();returnConvert.ToBase64String(ms.ToArray());}/// summary/// 解密/// /summary/// param nameplainText/param/// returns/returnspublicstaticstringDecrypt(stringcipherText){byte[]keyAesKeyManager.GetKey();byte[]bufferConvert.FromBase64String(cipherText);usingAesaesAes.Create();aes.Keykey;byte[]ivnewbyte[16];// 提取前 16 字节为 IVArray.Copy(buffer,0,iv,0,16);aes.IViv;usingMemoryStreammsnew(buffer,16,buffer.Length-16);usingCryptoStreamcsnew(ms,aes.CreateDecryptor(),CryptoStreamMode.Read);usingStreamReadersrnew(cs);returnsr.ReadToEnd();}}附赠一个手机号脱敏显示也作为自己的学习记录。/// summary/// 手机号脱敏显示/// /summary/// param namephone/param/// returns/returnspublicstaticstringMaskPhone(stringphone){if(string.IsNullOrWhiteSpace(phone))returnphone;if(phone.Length!11)returnphone;returnphone.Substring(0,3)****phone.Substring(7);}感谢看完全文比心