public void TestMD5()
{
Console.WriteLine(this.EncodePassword("1"));
}
string EncodePassword(string originalPassword)
{
//Declarations
Byte[] originalBytes;
Byte[] encodedBytes;
MD5 md5;
//Instantiate MD5CryptoServiceProvider, get bytes for original password and compute hash (encoded password)
md5 = new MD5CryptoServiceProvider();
originalBytes = ASCIIEncoding.Default.GetBytes(originalPassword);
encodedBytes = md5.ComputeHash(originalBytes);
//Convert encoded bytes back to a ’readable’ string
return BitConverter.ToString(encodedBytes);
}
#endregion
#region RC4
/// <summary>
/// 加密或解密(对称)
/// </summary>
/// <param name="data">明文或密文</param>
/// <param name="pass">密钥</param>
/// <returns>密文或明文</returns>
public Byte[] EncryptEx(Byte[] data, String pass)
{
if (data == null || pass == null) return null;
Byte[] output = new Byte[data.Length];
Int64 i = 0;
Int64 j = 0;
Byte[] mBox = GetKey(Encoding.UTF8.GetBytes(pass), 256);
// 加密
for (Int64 offset = 0; offset < data.Length; offset++)
{
i = (i + 1) % mBox.Length;
j = (j + mBox[i]) % mBox.Length;
Byte temp = mBox[i];
mBox[i] = mBox[j];
mBox[j] = temp;
Byte a = data[offset];
//Byte b = mBox[(mBox[i] + mBox[j] % mBox.Length) % mBox.Length];
// mBox[j] 一定比 mBox.Length 小,不需要在取模
Byte b = mBox[(mBox[i] + mBox[j]) % mBox.Length];
output[offset] = (Byte)((Int32)a ^ (Int32)b);
}
return output;
}
/// <summary>
/// 解密
/// </summary>
/// <param name="data"></param>
/// <param name="pass"></param>
/// <returns></returns>
public Byte[] DecryptEx(Byte[] data, String pass)
{
return EncryptEx(data, pass);
}
/// <summary>
/// 打乱密码
/// </summary>
/// <param name="pass">密码</param>
/// <param name="kLen">密码箱长度</param>
/// <returns>打乱后的密码</returns>
static private Byte[] GetKey(Byte[] pass, Int32 kLen)
{
Byte[] mBox = new Byte[kLen];
for (Int64 i = 0; i < kLen; i++)
{
mBox[i] = (Byte)i;
}
Int64 j = 0;
for (Int64 i = 0; i < kLen; i++)
{
j = (j + mBox[i] + pass[i % pass.Length]) % kLen;
Byte temp = mBox[i];
mBox[i] = mBox[j];
mBox[j] = temp;
}
return mBox;
}
#endregion
#region AES
/// <summary>
/// 获取密钥
/// </summary>
private static string Key
{
get { return @")O[NB]6,YF}+efcaj{+oESb9d8>Z’e9M"; }
}
/// <summary>
/// 获取向量
/// </summary>
private static string IV
{
get { return @"L+\~f4,Ir)b$=pkf"; }
}
/// <summary>
/// AES加密
/// </summary>
/// <param name="plainStr">明文字符串</param>
/// <param name="returnNull">加密失败时是否返回 null,false 返回 String.Empty</param>
/// <returns>密文</returns>
责任编辑:小草