csharp C#AES 256位加密加密SSN
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp C#AES 256位加密加密SSN相关的知识,希望对你有一定的参考价值。
static void Main()
{
string ssn = "33-11-4444";
string password = genPassword();
string encryptedTxt = EncryptText(ssn, password);
string decryptedTxt = DecryptText(encryptedTxt, password);
Console.WriteLine("Password: " + password);
Console.WriteLine("Encrypted text: " + encryptedTxt);
Console.WriteLine("Decrypted text: " + decryptedTxt);
Console.ReadLine();
}
public static string genPassword()
{
var random = new RNGCryptoServiceProvider();
// Maximum length of salt
int max_length = 32;
// Empty salt array
byte[] salt = new byte[max_length];
// Build the random bytes
random.GetNonZeroBytes(salt);
// Return the string encoded salt
return Convert.ToBase64String(salt);
}
public static string EncryptText(string input, string password)
{
// Get the bytes of the string
byte[] bytesToBeEncrypted = Encoding.UTF8.GetBytes(input);
// Hash the password with SHA256
byte[] passwordBytes = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
byte[] bytesEncrypted = null;
// The salt bytes must be at least 8 bytes. Private key
byte[] saltBytes = new byte[] { 111, 27, 3, 11, 18, 4, 19, 27 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeEncrypted, 0, bytesToBeEncrypted.Length);
cs.Close();
}
bytesEncrypted = ms.ToArray();
}
}
return Convert.ToBase64String(bytesEncrypted);
}
public static string DecryptText(string input, string password)
{
// Get the bytes of the string
byte[] bytesToBeDecrypted = Convert.FromBase64String(input);
byte[] passwordBytes = SHA256.Create().ComputeHash(Encoding.UTF8.GetBytes(password));
byte[] bytesDecrypted = null;
// The salt bytes must be at least 8 bytes. Private key.
byte[] saltBytes = new byte[] { 111, 27, 3, 11, 18, 4, 19, 27 };
using (MemoryStream ms = new MemoryStream())
{
using (RijndaelManaged AES = new RijndaelManaged())
{
AES.KeySize = 256;
AES.BlockSize = 128;
var key = new Rfc2898DeriveBytes(passwordBytes, saltBytes, 1000);
AES.Key = key.GetBytes(AES.KeySize / 8);
AES.IV = key.GetBytes(AES.BlockSize / 8);
AES.Mode = CipherMode.CBC;
using (var cs = new CryptoStream(ms, AES.CreateDecryptor(), CryptoStreamMode.Write))
{
cs.Write(bytesToBeDecrypted, 0, bytesToBeDecrypted.Length);
cs.Close();
}
bytesDecrypted = ms.ToArray();
}
}
return Encoding.UTF8.GetString(bytesDecrypted);
}
以上是关于csharp C#AES 256位加密加密SSN的主要内容,如果未能解决你的问题,请参考以下文章
是否可以在 .net framework 4.7 中使用 AES(256 位)GCM 模式加密数据?