EncodeHash.cs 加密類
Code
[copy to clipboard]
CODE:
using System;
using System.Collections.Generic;
using System.Text;
using System.Security.Cryptography;
namespace QQLogin
{
/**//// <summary>
/// 編碼加密類
/// </summary>
class EncodeHash
{
/**//// <summary>
/// 通過MD5加密後返回加密後的BASE64密碼
/// </summary>
/// <param name="pwd">要加密的內容</param>
/// <returns>通過MD5加密後返回加密後的BASE64密碼</returns>
public static string pwdHash(string pwd)
{//使用MD5的16位加密後再轉換成BASE64
System.Security.Cryptography.MD5 md5 = System.Security.Cryptography.MD5.Create();//實例化一個md5對像
// 加密後是一個字節類型的數組,這裡要注意編碼UTF8/Unicode等的選擇
byte[] s = md5.ComputeHash(System.Text.Encoding.UTF8.GetBytes(pwd));
return Convert.ToBase64String(s);
}
/**//// <summary>
/// 返回MD5的32位加密後的密碼
/// </summary>
/// <param name="inputString">要加密的內容</param>
/// <returns>加密後的結果</returns>
public static string StringToMD5Hash(string inputString)
{
MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
byte[] encryptedBytes = md5.ComputeHash(Encoding.ASCII.GetBytes(inputString));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < encryptedBytes.Length; i++)
{
sb.AppendFormat("{0:x2}", encryptedBytes);
}
return sb.ToString();
}
/**//// <summary>
/// Base64編碼
/// </summary>
/// <param name="code"></param>
/// <returns></returns>
public static string EncodeBase64(string code)
{
string encode = "";
byte[] bytes = System.Text.Encoding.Default.GetBytes(code);
try
{
encode = Convert.ToBase64String(bytes);
}
catch
{
encode = code;
}
return encode;
}
/**//// <summary>
/// Base64解碼
/// </summary>
/// <param name="code_type"></param>
/// <param name="code"></param>
/// <returns></returns>
public static string DecodeBase64(string code_type, string code)
{
string decode = "";
byte[] bytes = Convert.FromBase64String(code);
try
{
decode = Encoding.GetEncoding(code_type).GetString(bytes);
}
catch
{
decode = code;
}
return decode;
}
}
}