天天看點

c#如何優雅實作資料加密存儲、模糊比對和脫敏

作者:opendotnet

C#可以使用以下方式優雅實作資料加密存儲、模糊比對和脫敏:

資料加密存儲:可以使用C#内置的加密類庫,如System.Security.Cryptography命名空間下的類。可以使用對稱加密算法(如AES)或非對稱加密算法(如RSA)對資料進行加密,再存儲到資料庫或檔案中。在讀取資料時,需要先進行解密操作。

模糊比對:可以使用C#内置的字元串比對類庫,如System.Text.RegularExpressions命名空間下的類。可以使用正規表達式進行模糊比對。例如,可以使用Regex.Match方法比對字元串中的某個子串,或使用Regex.Replace方法替換字元串中的某些字元。

脫敏:可以使用C#内置的字元串處理類庫,如System.String命名空間下的類。可以使用Substring方法截取字元串的部分内容,或使用Replace方法替換字元串中的某些字元。例如,可以将身份證号碼的前幾位和後幾位進行脫敏處理,隻顯示中間部分的幾個字元。

資料加密存儲

using System;
using System.Security.Cryptography;
using System.Text;
public static class EncryptionHelper
{
 public static string Encrypt(string plaintext)
 {
 byte[] salt = new byte[] { 0x26, 0x19, 0x7E, 0x7A, 0x9C, 0x7D, 0x62, 0x96 };
 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("mysecretpassword", salt, 1000);
 Aes aes = Aes.Create();
 aes.Key = key.GetBytes(aes.KeySize / 8);
 aes.IV = key.GetBytes(aes.BlockSize / 8);
 byte[] encryptedBytes;
 using (MemoryStream ms = new MemoryStream())
 {
 using (CryptoStream cs = new CryptoStream(ms, aes.CreateEncryptor(), CryptoStreamMode.Write))
 {
 byte[] plaintextBytes = Encoding.UTF8.GetBytes(plaintext);
 cs.Write(plaintextBytes, 0, plaintextBytes.Length);
 }
 encryptedBytes = ms.ToArray();
 }
return Convert.ToBase64String(encryptedBytes);
 }
 public static string Decrypt(string ciphertext)
 {
 byte[] salt = new byte[] { 0x26, 0x19, 0x7E, 0x7A, 0x9C, 0x7D, 0x62, 0x96 };
 Rfc2898DeriveBytes key = new Rfc2898DeriveBytes("mysecretpassword", salt, 1000);
 Aes aes = Aes.Create();
 aes.Key = key.GetBytes(aes.KeySize / 8);
 aes.IV = key.GetBytes(aes.BlockSize / 8);
 byte[] encryptedBytes = Convert.FromBase64String(ciphertext);
 byte[] plaintextBytes;
 using (MemoryStream ms = new MemoryStream())
 {
 using (CryptoStream cs = new CryptoStream(ms, aes.CreateDecryptor(), CryptoStreamMode.Write))
 {
 cs.Write(encryptedBytes, 0, encryptedBytes.Length);
 }
 plaintextBytes = ms.ToArray();
 }
return Encoding.UTF8.GetString(plaintextBytes);
 }
}
           

模糊比對

using System;
public static class FuzzyMatchHelper
{
 public static bool FuzzyMatch(string pattern, string text)
 {
if (string.IsOrEmpty(pattern) || string.IsOrEmpty(text))
 {
return false;
 }
 int patternIndex = 0;
 int textIndex = 0;
while (patternIndex < pattern.Length && textIndex < text.Length)
 {
if (pattern[patternIndex] == text[textIndex])
 {
 patternIndex++;
 textIndex++;
 }
else if (patternIndex == 0)
 {
 textIndex++;
 }
else
 {
 patternIndex = 0;
 }
 }
return patternIndex == pattern.Length;
 }
}
           

脫敏

using System;
using System.Text.RegularExpressions;
public static class DataMaskingHelper
{
 public static string Mask(string data)
 {
if (string.IsOrEmpty(data))
 {
return data;
 }
 string pattern = @"(?<=\d{3})\d(?=\d{4})";
return Regex.Replace(data, pattern, "*");
 }
}
           

繼續閱讀