using System;
using System.Security.Cryptography;
using System.IO;
using System.Text;
//1、将字符串转换成字节数组
//2、选择加密方式
//3、不可逆加密:MD5、SHA1
//4、可逆加密:DES、RC2、Rijndael
//5、对密钥要求长度不同
//6、加密速度不同、复杂程度不同、安全性不同
public class Class10
{
public Class10()
{
CallMyDES();
}
void CallMyDES()
{
Byte[] key = { 12, 23, 34, 45, 56, 67, 78, 89 };
Byte[] iv = { 120, 230, 10, 1, 10, 20, 30, 40 };
//1、调用MD5、SHA1加密
bool result = MyMD5Crypto("123456");
//2、调用DES加密、解密
string a = MyDESCrypto("123456", key, iv);
string b = MyDESCryptoDe(a, key, iv);
//3、调用DES对文件加密、解密
MyDESCryptoFile("123456", key, iv);
string str = MyDESCryptoFileDe(key, iv);
//4、调用TripleDES加密、解密
string a1 = TripleDESCrypto("中国", "8i9o0p-[=]'/;.l,");//天津香港澳门台湾
string b1 = TripleDESCryptoDe(a1, "8i9o0p-[=]'/;.l,");
//5、调用自定义加密、解密
MyCrypto();
rsa 比 dea慢,但比dsa安全
//DSA dsa = DSA.Create();
//RSA rea = RSA.Create();
64
//DES des = DES.Create();
//TripleDES tDes = TripleDES.Create();
//RC2 rc2 = RC2.Create();
或
//RC2 rc21 = (RC2)SymmetricAlgorithm.Create("RC2");
//Rijndael rjd = Rijndael.Create();
//MD5 md5 = MD5.Create();
//SHA1 sha1 = SHA1.Create();
}
//1、MD5、SHA1加密(可用于加密后的数据以后不再显示,如加密用户密码)
bool MyMD5Crypto(string userPassword)//"123456";
{
bool result = false;
//单向加密
//1、MD5
string dbPassword = "E10ADC3949BA59ABBE56E057F20F883E";
string md5Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(userPassword, "MD5");
if (md5Password == dbPassword)
{
result = true;
}
//2、SHA1
string sha1Password = System.Web.Security.FormsAuthentication.HashPasswordForStoringInConfigFile(userPassword, "SHA1");
//"7C4A8D09CA3762AF61E59520943DC26494F8941B"
return result;
}
//2、DES对字符串加密、解密
string MyDESCrypto(string str, byte[] keys, byte[] ivs)
{
//加密
byte[] strs = Encoding.Unicode.GetBytes(str);
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
ICryptoTransform transform = desc.CreateEncryptor(keys, ivs);//加密对象
CryptoStream cStream = new CryptoStream(mStream, transform, CryptoStreamMode.Write);
cStream.Write(strs, 0, strs.Length);
cStream.FlushFinalBlock();
return Convert.ToBase64String(mStream.ToArray());
}
string MyDESCryptoDe(string str, byte[] keys, byte[] ivs)
{
//解密
byte[] strs = Convert.FromBase64String(str);
DESCryptoServiceProvider desc = new DESCryptoServiceProvider();
MemoryStream mStream = new MemoryStream();
ICryptoTransform transform = desc.CreateDecryptor(keys, ivs);//解密对象
CryptoStream cStream = new CryptoStream(mStream, transform, CryptoStreamMode.Write);
cStream.Write(strs, 0, strs.Length);
cStream.FlushFinalBlock();
return Encoding.Unicode.GetString(mStream.ToArray());
}
//3、DSA对文件加密、解密
void MyDESCryptoFile(string str, Byte[] key, Byte[] iv)
{
Byte[] inputStr = Encoding.Unicode.GetBytes(str);
//
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateEncryptor(key, iv);//加密对象
FileStream fStream = new FileStream(@"D:/a.txt", FileMode.Create, FileAccess.Write);
CryptoStream cStream = new CryptoStream(fStream, transform, CryptoStreamMode.Write);
cStream.Write(inputStr, 0, inputStr.Length);
cStream.Close();
}
string MyDESCryptoFileDe(Byte[] key, Byte[] iv)
{
DESCryptoServiceProvider provider = new DESCryptoServiceProvider();
ICryptoTransform transform = provider.CreateDecryptor(key, iv);//解密对象
FileStream fStream = new FileStream(@"D:/a.txt", FileMode.Open, FileAccess.Read);
CryptoStream cStream = new CryptoStream(fStream, transform, CryptoStreamMode.Read);
StreamReader reader = new StreamReader(cStream, new UnicodeEncoding());
string str = reader.ReadToEnd();
cStream.Close();
return str;
}
//4、TripleDES加密、解密
string TripleDESCrypto(string str, string key)
{
byte[] data = UnicodeEncoding.Unicode.GetBytes(str);//如果加密中文,不能用ASCII码
byte[] keys = ASCIIEncoding.ASCII.GetBytes(key);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = keys;//key的长度必须为16位或24位,否则报错“指定键的大小对于此算法无效。”,des.Key不支持中文
des.Mode = CipherMode.ECB;//设置运算模式
ICryptoTransform cryp = des.CreateEncryptor();//加密
return Convert.ToBase64String(cryp.TransformFinalBlock(data, 0, data.Length));
}
string TripleDESCryptoDe(string str, string key)
{
byte[] data = Convert.FromBase64String(str);
byte[] keys = ASCIIEncoding.ASCII.GetBytes(key);
TripleDESCryptoServiceProvider des = new TripleDESCryptoServiceProvider();
des.Key = keys;
des.Mode = CipherMode.ECB;//设置运算模式
des.Padding = PaddingMode.PKCS7;
ICryptoTransform cryp = des.CreateDecryptor();//解密
return UnicodeEncoding.Unicode.GetString(cryp.TransformFinalBlock(data, 0, data.Length));
}
//5、自定义加密、解密
void MyCrypto()
{
string a = "123456中国";
string b = "";
//加密
for (int i = 0; i < a.Length; i++)
{
b += (char)(a[i] + 10 - 2 * 3);
}
//解密
string c = "";
for (int i = 0; i < a.Length; i++)
{
c += (char)(b[i] - 10 + 2 * 3);
}
}
}
#region 加密,采用的是DES算法
/// <summary>
/// 加密程序,采用的是DES算法
/// </summary>
/// <param name="strEncrypt">加密字符串</param>
/// <param name="strKey">密钥必须为8位</param>
/// <returns>返回加密的字符串</returns>
public static string Encrypt(string strEncrypt, string strKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
byte[] inputByteArray = ASCIIEncoding.Unicode.GetBytes(strEncrypt);
des.Key = ASCIIEncoding.ASCII.GetBytes(strKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(strKey);
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();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
#endregion
#region 解密,采用的是DES算法
/// <summary>
/// 解密
/// </summary>
/// <param name="strDecrypt">解密字符串</param>
/// <param name="strKey">密钥必须是8位</param>
/// <returns>返回明文</returns>
public static string Decrypt(string strDecrypt, string strKey)
{
DESCryptoServiceProvider des = new DESCryptoServiceProvider();
try
{
byte[] inputByteArray = new byte[strDecrypt.Length / 2];
for (int x = 0; x < strDecrypt.Length / 2; x++)
{
int i = (Convert.ToInt32(strDecrypt.Substring(x * 2, 2), 16));
inputByteArray[x] = (byte)i;
}
des.Key = ASCIIEncoding.ASCII.GetBytes(strKey);
des.IV = ASCIIEncoding.ASCII.GetBytes(strKey);
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.ASCIIEncoding.Unicode.GetString(ms.ToArray());
}
catch
{
return "";
}
}