C#實(shí)現(xiàn)對(duì)AES加密和解密的方法
/// <summary>
/// ASE加解密
/// </summary>
public class AESHelper
{
/// <summary>
/// 獲取密鑰
/// </summary>
private static string Key
{
get
{
return "abcdef1234567890"; ////必須是16位
}
}
//默認(rèn)密鑰向量
private static byte[] _key1 = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF, 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
/// <summary>
/// AES加密算法
/// </summary>
/// <param name="plainText">明文字符串</param>
/// <returns>將加密后的密文轉(zhuǎn)換為Base64編碼,以便顯示</returns>
public static string AESEncrypt(string plainText)
{
//分組加密算法
SymmetricAlgorithm des = Rijndael.Create();
byte[] inputByteArray = Encoding.UTF8.GetBytes(plainText);//得到需要加密的字節(jié)數(shù)組
//設(shè)置密鑰及密鑰向量
des.Key = Encoding.UTF8.GetBytes(Key);
des.IV = _key1;
byte[] cipherBytes = null;
using (MemoryStream ms = new MemoryStream())
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write))
{
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
cipherBytes = ms.ToArray();//得到加密后的字節(jié)數(shù)組
cs.Close();
ms.Close();
}
}
return Convert.ToBase64String(cipherBytes);
}
/// <summary>
/// AES解密
/// </summary>
/// <param name="cipherText">密文字符串</param>
/// <returns>返回解密后的明文字符串</returns>
public static string AESDecrypt(string showText)
{
byte[] cipherText = Convert.FromBase64String(showText);
SymmetricAlgorithm des = Rijndael.Create();
des.Key = Encoding.UTF8.GetBytes(Key);
des.IV = _key1;
byte[] decryptBytes = new byte[cipherText.Length];
using (MemoryStream ms = new MemoryStream(cipherText))
{
using (CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Read))
{
cs.Read(decryptBytes, 0, decryptBytes.Length);
cs.Close();
ms.Close();
}
}
return Encoding.UTF8.GetString(decryptBytes).Replace("\0", ""); ///將字符串后尾的'\0'去掉
}
}
Key的值可以放在config文件中,也可放入數(shù)據(jù)庫中。
相關(guān)文章
C# BeginInvoke實(shí)現(xiàn)異步編程方式
這篇文章主要介紹了C# BeginInvoke實(shí)現(xiàn)異步編程方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-01-01
C#通過GET/POST方式發(fā)送Http請(qǐng)求
本文主要介紹了C#實(shí)現(xiàn)http請(qǐng)求的兩種方式,get和post方式。文中通過示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2021-09-09
C#探秘系列(四)——GetHashCode,ExpandoObject
這篇繼續(xù)分享下GetHashCode和ExpandoObject這兩個(gè)比較好玩的方法。2014-05-05
C#編程實(shí)現(xiàn)獲取文件夾中所有文件的文件名
這篇文章主要介紹了C#編程實(shí)現(xiàn)獲取文件夾中所有文件的文件名,可實(shí)現(xiàn)獲取特定目錄下制定類型文件名稱的功能,涉及C#針對(duì)文件與目錄的遍歷、查詢等操作相關(guān)技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-11-11
C#實(shí)現(xiàn)同Active MQ通訊的方法
這篇文章主要介紹了C#實(shí)現(xiàn)同Active MQ通訊的方法,簡單分析了Active MQ的功能及C#與之通訊的實(shí)現(xiàn)技巧,需要的朋友可以參考下2016-07-07
C#網(wǎng)絡(luò)編程基礎(chǔ)之進(jìn)程和線程詳解
這篇文章主要介紹了C#網(wǎng)絡(luò)編程基礎(chǔ)之進(jìn)程和線程詳解,本文對(duì)進(jìn)程、線程、線程池知識(shí)做了淺顯易懂的講解,并配有代碼實(shí)例,需要的朋友可以參考下2014-08-08

