最近在学习一些加密的东西,现在对C#加密代码进行整理:
1、对称加密;
///
/// 加密
///
///
///
///
public static string Encrypt(string pToEncrypt, string sKey)
{
System.Security.Cryptography.DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = Encoding.Default.GetBytes(pToEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateEncryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
foreach (byte b in ms.ToArray())
{
ret.AppendFormat("{0:X2}", b);
}
ret.ToString();
return ret.ToString();
}
///解密
public static string Decrypt(string pToDecrypt, string sKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
byte[] inputByteArray = new byte[pToDecrypt.Length / 2];
for (int x = 0; x < pToDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(pToDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(sKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(sKey);
MemoryStream ms = new MemoryStream();
CryptoStream cs = new CryptoStream(ms, des.CreateDecryptor(), CryptoStreamMode.Write);
cs.Write(inputByteArray, 0, inputByteArray.Length);
cs.FlushFinalBlock();
StringBuilder ret = new StringBuilder();
return System.Text.Encoding.Default.GetString(ms.ToArray());
}
3、MD5加密
//md5 加密
public static string MD5Encrypt(string strText)
{
// Create a new instance of the MD5CryptoServiceProvider object.
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hasher.ComputeHash(Encoding.Default.GetBytes(strText));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
4、通过流路径得到MD5值
public static string GetMd5Hash(Stream input)
{
MD5CryptoServiceProvider md5Hasher = new MD5CryptoServiceProvider();
byte[] data = md5Hasher.ComputeHash(input);
input.Seek(0, SeekOrigin.Begin);
StringBuilder sBuilder = new StringBuilder();
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
return sBuilder.ToString();
}
public static string GetMD5HashFromFile(string fileName)
{
try
{
FileStream file = new FileStream(fileName, FileMode.Open);
System.Security.Cryptography.MD5 md5 = new System.Security.Cryptography.MD5CryptoServiceProvider();
byte[] retVal = md5.ComputeHash(file);
file.Close();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < retVal.Length; i++)
{
sb.Append(retVal[i].ToString("x2"));
}
return sb.ToString();
}
catch (Exception ex)
{
throw new Exception("GetMD5HashFromFile() fail,error:" + ex.Message);
}
}
6、字符串MD5比较
// Verify a hash against a string. md5值不区分大小写
public static bool VerifyMd5Hash(string input, string hash)
{
// Hash the input.
string hashOfInput = getMd5Hash(input);
// Create a StringComparer an compare the hashes.
StringComparer comparer = StringComparer.OrdinalIgnoreCase;
if (0 == comparer.Compare(hashOfInput, hash))
{
return true;
}
else
{
return false;
}
}
7、RSA非对称加密
//RSA加密,随机生成公私钥对并作为出参返回
public static string RSA_Encrypt(string str_Plain_Text, out string str_Public_Key, out string str_Private_Key)
{
str_Public_Key = "";
str_Private_Key = "";
UnicodeEncoding ByteConverter = new UnicodeEncoding();
byte[] DataToEncrypt = ByteConverter.GetBytes(str_Plain_Text);
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
//OAEP padding is only available on Microsoft Windows XP or later.
byte[] bytes_Cypher_Text = RSA.Encrypt(DataToEncrypt, false);
str_Public_Key = Convert.ToBase64String(RSA.ExportCspBlob(false));
str_Private_Key = Convert.ToBase64String(RSA.ExportCspBlob(true));
string str_Cypher_Text = Convert.ToBase64String(bytes_Cypher_Text);
return str_Cypher_Text;
}
catch (CryptographicException e)
{
Console.WriteLine(e.Message);
return null;
}
}
//RSA解密
static public string RSA_Decrypt(string str_Cypher_Text, string str_Private_Key)
{
byte[] DataToDecrypt = Convert.FromBase64String(str_Cypher_Text);
try
{
RSACryptoServiceProvider RSA = new RSACryptoServiceProvider();
//RSA.ImportParameters(RSAKeyInfo);
byte[] bytes_Public_Key = Convert.FromBase64String(str_Private_Key);
RSA.ImportCspBlob(bytes_Public_Key);
//OAEP padding is only available on Microsoft Windows XP or later.
byte[] bytes_Plain_Text = RSA.Decrypt(DataToDecrypt, false);
UnicodeEncoding ByteConverter = new UnicodeEncoding();
string str_Plain_Text = ByteConverter.GetString(bytes_Plain_Text);
return str_Plain_Text;
}
catch (CryptographicException e)
{
Console.WriteLine(e.ToString());
return null;
}
}
更多内容请参考:
http://www.cnblogs.com/jfzhu/p/4020928.html
http://www.cnblogs.com/tongyi/p/4274092.html
http://blog.sina.com.cn/s/blog_4dd7300501008b5x.html
http://pmd5.com/?action=getpwd# MD5解密地址