|
數據的加密重要性大家皆知,很多情況下需要對數據進行加密處理,但各種重要數據的加密要求不一樣,有些需要時可逆的,有些是不要求可逆的,可逆的一般稱之為對稱加密算法,不可逆的一般可以成為非對稱加密算法。如登錄密碼,一般較好的方式是采用不可逆的加密算法,如MD5、SHA256、哈希數值等,當然也有的采用可逆的強度好一些的加密方式,在選擇加密鍵值的時候,變化一下也算是比較不錯的選擇。另外一些為了掩人耳目或者不讓別人直接可以查看到,就采用其他的加密算法,如DES加密算法、AES的RijndaelManaged加密算法,或者也可以采用Base64加密,甚至我看到一個很變態的方式,就是用MD5加密的頭,內容則采用Base64的方式加密,一般不知道內情的還真的不好處理。
在吉日《[走火入魔失眠夜]淺談管理軟件信息安全,用戶名、密碼的加密解密【附C#配套加密解密源碼】》 的文章中也對加密做了一些介紹和分析,并貼出了MD5、DES的加密方式代碼,吉日的文章圖文并茂、哲理及詼諧例子并存,本文有感而發,做一些補充,希望園子同行共通過切磋,交流心得。
加密字符串的方式有很多,也都可以通過這樣的加密文件內容,不過較好的方式可能是采用DES及AES兩種方式來加密文件了,下面貼出的代碼中包含了加解密文件的算法。下面具體貼出本人收藏的各種加密算法代碼。
1、DES加密字符串及文件等
如果想可逆的算法,這種方式一般不錯,只要結合動態密鑰,就可以做出強度比較高的加密應用了。
public const string DEFAULT_ENCRYPT_KEY = "12345678";/// <summary>
/// 使用默認加密
/// </summary>
/// <param name="strText"></param>
/// <returns></returns>
public static string DesEncrypt(string strText)
{
try
{
return DesEncrypt(strText, DEFAULT_ENCRYPT_KEY);
}
catch
{
return "";
}
}
/// <summary>
/// 使用默認解密
/// </summary>
/// <param name="strText"></param>
/// <returns></returns>
public static string DesDecrypt(string strText)
{
try
{
return DesDecrypt(strText, DEFAULT_ENCRYPT_KEY);
}
catch
{
return "";
}
}
/// <summary>
/// Encrypt the string
/// Attention:key must be 8 bits
/// </summary>
/// <param name="strText">string</param>
/// <param name="strEncrKey">key</param>
/// <returns></returns>
public static string DesEncrypt(string strText, string strEncrKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.UTF8.GetBytes(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
return Convert.ToBase64String(ms.ToArray());
}
/// <summary>
/// Decrypt string
/// Attention:key must be 8 bits
/// </summary>
/// <param name="strText">Decrypt string</param>
/// <param name="sDecrKey">key</param>
/// <returns>output string</returns>
public static string DesDecrypt(string strText, string sDecrKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byte[] inputByteArray = new Byte[strText.Length];
byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
inputByteArray = Convert.FromBase64String(strText);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
Encoding encoding = new UTF8Encoding();
return encoding.GetString(ms.ToArray());
}
/// <summary>
/// Encrypt files
/// Attention:key must be 8 bits
/// </summary>
/// <param name="m_InFilePath">Encrypt file path</param>
/// <param name="m_OutFilePath">output file</param>
/// <param name="strEncrKey">key</param>
public static void DesEncrypt(string m_InFilePath, string m_OutFilePath, string strEncrKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byKey = Encoding.UTF8.GetBytes(strEncrKey.Substring(0, 8));
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(byKey, IV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
/// <summary>
/// Decrypt files
/// Attention:key must be 8 bits
/// </summary>
/// <param name="m_InFilePath">Decrypt filepath</param>
/// <param name="m_OutFilePath">output filepath</param>
/// <param name="sDecrKey">key</param>
public static void DesDecrypt(string m_InFilePath, string m_OutFilePath, string sDecrKey)
{
byte[] byKey = null;
byte[] IV = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
byKey = Encoding.UTF8.GetBytes(sDecrKey.Substring(0, 8));
FileStream fin = new FileStream(m_InFilePath, FileMode.Open, FileAccess.Read);
FileStream fout = new FileStream(m_OutFilePath, FileMode.OpenOrCreate, FileAccess.Write);
fout.SetLength(0);
//Create variables to help with read and write.
byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
long rdlen = 0; //This is the total number of bytes written.
long totlen = fin.Length; //This is the total length of the input file.
int len; //This is the number of bytes to be written at a time.
DES des = new DESCryptoServiceProvider();
CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(byKey, IV), CryptoStreamMode.Write);
//Read from the input file, then encrypt and write to the output file.
while (rdlen < totlen)
{
len = fin.Read(bin, 0, 100);
encStream.Write(bin, 0, len);
rdlen = rdlen + len;
}
encStream.Close();
fout.Close();
fin.Close();
}
2、 對稱加密算法AES RijndaelManaged加密解密
private static readonly string Default_AES_Key = "@#kim123";
private static byte[] Keys = { 0x41, 0x72, 0x65, 0x79, 0x6F, 0x75, 0x6D, 0x79,
0x53,0x6E, 0x6F, 0x77, 0x6D, 0x61, 0x6E, 0x3F };
/// <summary>
/// 對稱加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是塊式加密算法)
/// </summary>
/// <param name="encryptString">待加密字符串</param>
/// <returns>加密結果字符串</returns>
public static string AES_Encrypt(string encryptString)
{
return AES_Encrypt(encryptString, Default_AES_Key);
}
/// <summary>
/// 對稱加密算法AES RijndaelManaged加密(RijndaelManaged(AES)算法是塊式加密算法)
/// </summary>
/// <param name="encryptString">待加密字符串</param>
/// <param name="encryptKey">加密密鑰,須半角字符</param>
/// <returns>加密結果字符串</returns>
public static string AES_Encrypt(string encryptString, string encryptKey)
{
encryptKey = GetSubString(encryptKey, 32, "");
encryptKey = encryptKey.PadRight(32, ' ');
RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 32));
rijndaelProvider.IV = Keys;
ICryptoTransform rijndaelEncrypt = rijndaelProvider.CreateEncryptor();
byte[] inputData = Encoding.UTF8.GetBytes(encryptString);
byte[] encryptedData = rijndaelEncrypt.TransformFinalBlock(inputData, 0, inputData.Length);
return Convert.ToBase64String(encryptedData);
}
/// <summary>
/// 對稱加密算法AES RijndaelManaged解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <returns>解密成功返回解密后的字符串,失敗返源串</returns>
public static string AES_Decrypt(string decryptString)
{
return AES_Decrypt(decryptString, Default_AES_Key);
}
/// <summary>
/// 對稱加密算法AES RijndaelManaged解密字符串
/// </summary>
/// <param name="decryptString">待解密的字符串</param>
/// <param name="decryptKey">解密密鑰,和加密密鑰相同</param>
/// <returns>解密成功返回解密后的字符串,失敗返回空</returns>
public static string AES_Decrypt(string decryptString, string decryptKey)
{
try
{
decryptKey = GetSubString(decryptKey, 32, "");
decryptKey = decryptKey.PadRight(32, ' ');
RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
rijndaelProvider.IV = Keys;
ICryptoTransform rijndaelDecrypt = rijndaelProvider.CreateDecryptor();
byte[] inputData = Convert.FromBase64String(decryptString);
byte[] decryptedData = rijndaelDecrypt.TransformFinalBlock(inputData, 0, inputData.Length);
return Encoding.UTF8.GetString(decryptedData);
}
catch
{
return string.Empty;
}
}
/// <summary>
/// 按字節長度(按字節,一個漢字為2個字節)取得某字符串的一部分
/// </summary>
/// <param name="sourceString">源字符串</param>
/// <param name="length">所取字符串字節長度</param>
/// <param name="tailString">附加字符串(當字符串不夠長時,尾部所添加的字符串,一般為"...")</param>
/// <returns>某字符串的一部分</returns>
private static string GetSubString(string sourceString, int length, string tailString)
{
return GetSubString(sourceString, 0, length, tailString);
}
/// <summary>
/// 按字節長度(按字節,一個漢字為2個字節)取得某字符串的一部分
/// </summary>
/// <param name="sourceString">源字符串</param>
/// <param name="startIndex">索引位置,以0開始</param>
/// <param name="length">所取字符串字節長度</param>
/// <param name="tailString">附加字符串(當字符串不夠長時,尾部所添加的字符串,一般為"...")</param>
/// <returns>某字符串的一部分</returns>
private static string GetSubString(string sourceString, int startIndex, int length, string tailString)
{
string myResult = sourceString;
//當是日文或韓文時(注:中文的范圍:/u4e00 - /u9fa5, 日文在/u0800 - /u4e00, 韓文為/xAC00-/xD7A3)
if (System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[/u0800-/u4e00]+") ||
System.Text.RegularExpressions.Regex.IsMatch(sourceString, "[/xAC00-/xD7A3]+"))
{
//當截取的起始位置超出字段串長度時
if (startIndex >= sourceString.Length)
{
return string.Empty;
}
else
{
return sourceString.Substring(startIndex,
((length + startIndex) > sourceString.Length) ? (sourceString.Length - startIndex) : length);
}
}
//中文字符,如"中國人民abcd123"
if (length <= 0)
{
return string.Empty;
}
byte[] bytesSource = Encoding.Default.GetBytes(sourceString);
//當字符串長度大于起始位置
if (bytesSource.Length > startIndex)
{
int endIndex = bytesSource.Length;
//當要截取的長度在字符串的有效長度范圍內
if (bytesSource.Length > (startIndex + length))
{
endIndex = length + startIndex;
}
else
{ //當不在有效范圍內時,只取到字符串的結尾
length = bytesSource.Length - startIndex;
tailString = "";
}
int[] anResultFlag = new int[length];
int nFlag = 0;
//字節大于127為雙字節字符
for (int i = startIndex; i < endIndex; i++)
{
if (bytesSource[i] > 127)
{
nFlag++;
if (nFlag == 3)
{
nFlag = 1;
}
}
else
{
nFlag = 0;
}
anResultFlag[i] = nFlag;
}
//最后一個字節為雙字節字符的一半
if ((bytesSource[endIndex - 1] > 127) && (anResultFlag[length - 1] == 1))
{
length = length + 1;
}
byte[] bsResult = new byte[length];
Array.Copy(bytesSource, startIndex, bsResult, 0, length);
myResult = Encoding.Default.GetString(bsResult);
myResult = myResult + tailString;
return myResult;
}
return string.Empty;
}
/// <summary>
/// 加密文件流
/// </summary>
/// <param name="fs"></param>
/// <returns></returns>
public static CryptoStream AES_EncryptStrream(FileStream fs, string decryptKey)
{
decryptKey = GetSubString(decryptKey, 32, "");
decryptKey = decryptKey.PadRight(32, ' ');
RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
rijndaelProvider.IV = Keys;
ICryptoTransform encrypto = rijndaelProvider.CreateEncryptor();
CryptoStream cytptostreamEncr = new CryptoStream(fs, encrypto, CryptoStreamMode.Write);
return cytptostreamEncr;
}
/// <summary>
/// 解密文件流
/// </summary>
/// <param name="fs"></param>
/// <returns></returns>
public static CryptoStream AES_DecryptStream(FileStream fs, string decryptKey)
{
decryptKey = GetSubString(decryptKey, 32, "");
decryptKey = decryptKey.PadRight(32, ' ');
RijndaelManaged rijndaelProvider = new RijndaelManaged();
rijndaelProvider.Key = Encoding.UTF8.GetBytes(decryptKey);
rijndaelProvider.IV = Keys;
ICryptoTransform Decrypto = rijndaelProvider.CreateDecryptor();
CryptoStream cytptostreamDecr = new CryptoStream(fs, Decrypto, CryptoStreamMode.Read);
return cytptostreamDecr;
}
/// <summary>
/// 對指定文件加密
/// </summary>
/// <param name="InputFile"></param>
/// <param name="OutputFile"></param>
/// <returns></returns>
public static bool AES_EncryptFile(string InputFile, string OutputFile)
{
try
{
string decryptKey = "www.iqidi.com";
FileStream fr = new FileStream(InputFile, FileMode.Open);
FileStream fren = new FileStream(OutputFile, FileMode.Create);
CryptoStream Enfr = AES_EncryptStrream(fren, decryptKey);
byte[] bytearrayinput = new byte[fr.Length];
fr.Read(bytearrayinput, 0, bytearrayinput.Length);
Enfr.Write(bytearrayinput, 0, bytearrayinput.Length);
Enfr.Close();
fr.Close();
fren.Close();
}
catch
{
//文件異常
return false;
}
return true;
}
/// <summary>
/// 對指定的文件解壓縮
/// </summary>
/// <param name="InputFile"></param>
/// <param name="OutputFile"></param>
/// <returns></returns>
public static bool AES_DecryptFile(string InputFile, string OutputFile)
{
try
{
string decryptKey = "www.iqidi.com";
FileStream fr = new FileStream(InputFile, FileMode.Open);
FileStream frde = new FileStream(OutputFile, FileMode.Create);
CryptoStream Defr = AES_DecryptStream(fr, decryptKey);
byte[] bytearrayoutput = new byte[1024];
int m_count = 0;
do
{
m_count = Defr.Read(bytearrayoutput, 0, bytearrayoutput.Length);
frde.Write(bytearrayoutput, 0, m_count);
if (m_count < bytearrayoutput.Length)
break;
} while (true);
Defr.Close();
fr.Close();
frde.Close();
}
catch
{
//文件異常
return false;
}
return true;
}
#endregion
3、 Base64加密解密算法
#region Base64加密解密/// <summary>
/// Base64是一種使用64基的位置計數法。它使用2的最大次方來代表僅可列印的ASCII 字元。
/// 這使它可用來作為電子郵件的傳輸編碼。在Base64中的變數使用字元A-Z、a-z和0-9 ,
/// 這樣共有62個字元,用來作為開始的64個數字,最後兩個用來作為數字的符號在不同的
/// 系統中而不同。
/// Base64加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Encrypt(string str)
{
byte[] encbuff = System.Text.Encoding.UTF8.GetBytes(str);
return Convert.ToBase64String(encbuff);
}
/// <summary>
/// Base64解密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
public static string Base64Decrypt(string str)
{
byte[] decbuff = Convert.FromBase64String(str);
return System.Text.Encoding.UTF8.GetString(decbuff);
}
#endregion
7、 MD5及Base64結合加密
這種結合方式也是比較不錯的算法,至少是四不像,一般分析比較困難,比較有迷惑性,就是掛羊頭,賣狗肉的行為,其實Base64加密方式,也可以做的比較復雜,不一定是上面的那種解決方式的,你可以添加一些較為復雜的算法在里面的。
/// <summary>/// 加密字符串
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string EncryptString(string input)
{
return MD5Util.AddMD5Profix(Base64Util.Encrypt(MD5Util.AddMD5Profix(input)));
//return Base64.Encrypt(MD5.AddMD5Profix(Base64.Encrypt(input)));
}
/// <summary>
/// 解密加過密的字符串
/// </summary>
/// <param name="input"></param>
/// <param name="throwException">解密失敗是否拋異常</param>
/// <returns></returns>
public static string DecryptString(string input, bool throwException)
{
string res = "";
try
{
res = input;// Base64.Decrypt(input);
if (MD5Util.ValidateValue(res))
{
return MD5Util.RemoveMD5Profix(Base64Util.Decrypt(MD5Util.RemoveMD5Profix(res)));
}
else
{
throw new Exception("字符串無法轉換成功!");
}
}
catch
{
if (throwException)
{
throw;
}
else
{
return "";
}
}
}
//-----------下面是MD5Util下面的函數
/// <summary>
/// 添加MD5的前綴,便于檢查有無篡改
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string AddMD5Profix(string input)
{
return GetMD5_4(input) + input;
}
/// <summary>
/// 移除MD5的前綴
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static string RemoveMD5Profix(string input)
{
return input.Substring(4);
}
/// <summary>
/// 驗證MD5前綴處理的字符串有無被篡改
/// </summary>
/// <param name="input"></param>
/// <returns></returns>
public static bool ValidateValue(string input)
{
bool res = false;
if (input.Length >= 4)
{
string tmp = input.Substring(4);
if (input.Substring(0, 4) == GetMD5_4(tmp))
{
res = true;
}
}
return res;
}
NET技術:談談數據加密的處理--提供各種算法處理,轉載需保留來源!
鄭重聲明:本文版權歸原作者所有,轉載文章僅為傳播更多信息之目的,如作者信息標記有誤,請第一時間聯系我們修改或刪除,多謝。