C# AES加解密

最近常遇到需要使用AES加解密的需求,無論是網路傳輸/API相關的部份。
分享一下
Github原始碼下載
https://github.com/superlevin/CSharpAES

using System.Security.Cryptography;
public static string SHAEncrypt(string str)
{
var crypt = new System.Security.Cryptography.SHA256Managed();
var hash = new System.Text.StringBuilder();
byte[] crypto = crypt.ComputeHash(Encoding.UTF8.GetBytes(str));
foreach (byte theByte in crypto)
{
hash.Append(theByte.ToString("x2"));
// x小寫 X 大寫 x2 補0
}
return hash.ToString();
}
public static string AESEncrypt(string str, string strkey, string strivKey, bool isVasEncrypt = false)
{

var aesCipher = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};

var keyStr = KeyGenerator(strkey);
var key = Convert.FromBase64String(keyStr);
var ivKey = Encoding.UTF8.GetBytes(strivKey);
var input = str;
var ivStr = Convert.ToBase64String(ivKey);

aesCipher.Key = key;
aesCipher.IV = ivKey;
byte[] b = System.Text.Encoding.UTF8.GetBytes(str); // plain text to be encrypted
ICryptoTransform encryptTransform = aesCipher.CreateEncryptor();
byte[] cipherText = encryptTransform.TransformFinalBlock(b, 0, b.Length);
return Convert.ToBase64String(cipherText);
}
public static string AESDecrypt(string encstring, string strkey, string strivKey)
{
var aesCipher = new AesManaged
{
KeySize = 128,
BlockSize = 128,
Mode = CipherMode.CBC,
Padding = PaddingMode.PKCS7
};
var keyStr = KeyGenerator(strkey);
var key = Convert.FromBase64String(keyStr);
aesCipher.Key = key;
aesCipher.IV = Encoding.UTF8.GetBytes(strivKey);

var encryptBytes = Convert.FromBase64String(encstring);
ICryptoTransform decryptTransform = aesCipher.CreateDecryptor();
byte[] plainText = decryptTransform.TransformFinalBlock(encryptBytes, 0, encryptBytes.Length);

return System.Text.Encoding.UTF8.GetString(plainText);
}

讓資料庫密碼加上鹽(Salt)值

以往許多人喜歡在資料庫的密碼欄使用明碼儲存,但站在資訊安全角度來說不是挺安全的,可以產生一個Salt值後,增加安全性。
[php]
// 隨機產生一組長度為10的Salt值
$salt = substr(md5(uniqid(rand(), true)), 0, 10);
// 存入資料庫的密碼欄,使用Salt值加上md5雜湊後存回資料庫
$new_password = md5(md5($old_password.$salt));
[/php]
使用者登入後,先從資料庫讀出salt值,接著再一樣加上salt值加上md5後比對就可以了!