C#加密算法汇总

来源:互联网 发布:白金数据 百度云 人人 编辑:程序博客网 时间:2024/05/16 02:12
方法一:
02    //须添加对System.Web的引用 
03    using System.Web.Security; 
04      
05    ... 
06      
07    /// <summary> 
08    /// SHA1加密字符串 
09    /// </summary> 
10    /// <param name="source">源字符串</param> 
11    /// <returns>加密后的字符串</returns> 
12    public string SHA1(string source) 
13    
14        return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1"); 
15    
16  
17  
18    /// <summary> 
19    /// MD5加密字符串 
20    /// </summary> 
21    /// <param name="source">源字符串</param> 
22    /// <returns>加密后的字符串</returns> 
23    public string MD5(string source) 
24    
25        return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");; 
26    }

 

view sourceprint?
01方法二(可逆加密解密):
02    using System.Security.Cryptography; 
03      
04    ... 
05      
06    public string Encode(string data) 
07    
08        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); 
09        byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); 
10      
11        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); 
12        int i = cryptoProvider.KeySize; 
13        MemoryStream ms = new MemoryStream(); 
14        CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write); 
15      
16        StreamWriter sw = new StreamWriter(cst); 
17        sw.Write(data); 
18        sw.Flush(); 
19        cst.FlushFinalBlock(); 
20        sw.Flush(); 
21        return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); 
22      
23    
24      
25    public string Decode(string data) 
26    
27        byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64); 
28        byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64); 
29      
30        byte[] byEnc; 
31        try 
32        
33            byEnc = Convert.FromBase64String(data); 
34        
35        catch 
36        
37            return null
38        
39      
40        DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider(); 
41        MemoryStream ms = new MemoryStream(byEnc); 
42        CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read); 
43        StreamReader sr = new StreamReader(cst); 
44        return sr.ReadToEnd(); 
45    }
view sourceprint?
01方法三(MD5不可逆):
02    using System.Security.Cryptography; 
03      
04    ... 
05      
06    //MD5不可逆加密 
07      
08    //32位加密 
09      
10    public string GetMD5_32(string s, string _input_charset) 
11    
12        MD5 md5 = new MD5CryptoServiceProvider(); 
13        byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s)); 
14        StringBuilder sb = new StringBuilder(32); 
15        for (int i = 0; i < t.Length; i++) 
16        
17            sb.Append(t[i].ToString("x").PadLeft(2, '0')); 
18        
19        return sb.ToString(); 
20    
21      
22    //16位加密 
23    public static string GetMd5_16(string ConvertString) 
24    
25        MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 
26        string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8); 
27        t2 = t2.Replace("-", ""); 
28        return t2; 
29    }
view sourceprint?
01方法四(对称加密):
02    using System.IO; 
03    using System.Security.Cryptography; 
04      
05    ... 
06      
07    private SymmetricAlgorithm mobjCryptoService; 
08    private string Key; 
09    /// <summary>    
10    /// 对称加密类的构造函数    
11    /// </summary>    
12    public SymmetricMethod() 
13    
14        mobjCryptoService = new RijndaelManaged(); 
15        Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7"
16    
17    /// <summary>    
18    /// 获得密钥    
19    /// </summary>    
20    /// <returns>密钥</returns>    
21    private byte[] GetLegalKey() 
22    
23        string sTemp = Key; 
24        mobjCryptoService.GenerateKey(); 
25        byte[] bytTemp = mobjCryptoService.Key; 
26        int KeyLength = bytTemp.Length; 
27        if (sTemp.Length > KeyLength) 
28            sTemp = sTemp.Substring(0, KeyLength); 
29        else if (sTemp.Length < KeyLength) 
30            sTemp = sTemp.PadRight(KeyLength, ' '); 
31        return ASCIIEncoding.ASCII.GetBytes(sTemp); 
32    
33    /// <summary>    
34    /// 获得初始向量IV    
35    /// </summary>    
36    /// <returns>初试向量IV</returns>    
37    private byte[] GetLegalIV() 
38    
39        string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk"
40        mobjCryptoService.GenerateIV(); 
41        byte[] bytTemp = mobjCryptoService.IV; 
42        int IVLength = bytTemp.Length; 
43        if (sTemp.Length > IVLength) 
44            sTemp = sTemp.Substring(0, IVLength); 
45        else if (sTemp.Length < IVLength) 
46            sTemp = sTemp.PadRight(IVLength, ' '); 
47        return ASCIIEncoding.ASCII.GetBytes(sTemp); 
48    
49    /// <summary>    
50    /// 加密方法    
51    /// </summary>    
52    /// <param name="Source">待加密的串</param>    
53    /// <returns>经过加密的串</returns>    
54    public string Encrypto(string Source) 
55    
56        byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source); 
57        MemoryStream ms = new MemoryStream(); 
58        mobjCryptoService.Key = GetLegalKey(); 
59        mobjCryptoService.IV = GetLegalIV(); 
60        ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor(); 
61        CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write); 
62        cs.Write(bytIn, 0, bytIn.Length); 
63        cs.FlushFinalBlock(); 
64        ms.Close(); 
65        byte[] bytOut = ms.ToArray(); 
66        return Convert.ToBase64String(bytOut); 
67    
68    /// <summary>    
69    /// 解密方法    
70    /// </summary>    
71    /// <param name="Source">待解密的串</param>    
72    /// <returns>经过解密的串</returns>    
73    public string Decrypto(string Source) 
74    
75        byte[] bytIn = Convert.FromBase64String(Source); 
76        MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length); 
77        mobjCryptoService.Key = GetLegalKey(); 
78        mobjCryptoService.IV = GetLegalIV(); 
79        ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor(); 
80        CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read); 
81        StreamReader sr = new StreamReader(cs); 
82        return sr.ReadToEnd(); 
83    }
view sourceprint?
01方法五:
02    using System.IO; 
03    using System.Security.Cryptography; 
04    using System.Text; 
05      
06    ... 
07      
08    //默认密钥向量 
09    private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF }; 
10    /// <summary> 
11    /// DES加密字符串 
12    /// </summary> 
13    /// <param name="encryptString">待加密的字符串</param> 
14    /// <param name="encryptKey">加密密钥,要求为8位</param> 
15    /// <returns>加密成功返回加密后的字符串,失败返回源串</returns> 
16    public static string EncryptDES(string encryptString, string encryptKey) 
17    
18        try 
19        
20            byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8)); 
21            byte[] rgbIV = Keys; 
22            byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString); 
23            DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider(); 
24            MemoryStream mStream = new MemoryStream(); 
25            CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); 
26            cStream.Write(inputByteArray, 0, inputByteArray.Length); 
27            cStream.FlushFinalBlock(); 
28            return Convert.ToBase64String(mStream.ToArray()); 
29        
30        catch 
31        
32            return encryptString; 
33        
34    
35      
36    /// <summary> 
37    /// DES解密字符串 
38    /// </summary> 
39    /// <param name="decryptString">待解密的字符串</param> 
40    /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param> 
41    /// <returns>解密成功返回解密后的字符串,失败返源串</returns> 
42    public static string DecryptDES(string decryptString, string decryptKey) 
43    
44        try 
45        
46            byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey); 
47            byte[] rgbIV = Keys; 
48            byte[] inputByteArray = Convert.FromBase64String(decryptString); 
49            DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider(); 
50            MemoryStream mStream = new MemoryStream(); 
51            CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write); 
52            cStream.Write(inputByteArray, 0, inputByteArray.Length); 
53            cStream.FlushFinalBlock(); 
54            return Encoding.UTF8.GetString(mStream.ToArray()); 
55        
56        catch 
57        
58            return decryptString; 
59        
60    }
view sourceprint?
01方法六(文件加密):
02    using System.IO; 
03    using System.Security.Cryptography; 
04    using System.Text; 
05      
06    ... 
07      
08    //加密文件 
09    private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV) 
10    
11        //Create the file streams to handle the input and output files. 
12        FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); 
13        FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); 
14        fout.SetLength(0); 
15      
16        //Create variables to help with read and write. 
17        byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
18        long rdlen = 0;              //This is the total number of bytes written. 
19        long totlen = fin.Length;    //This is the total length of the input file. 
20        int len;                     //This is the number of bytes to be written at a time. 
21      
22        DES des = new DESCryptoServiceProvider(); 
23        CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write); 
24      
25        //Read from the input file, then encrypt and write to the output file. 
26        while (rdlen < totlen) 
27        
28            len = fin.Read(bin, 0, 100); 
29            encStream.Write(bin, 0, len); 
30            rdlen = rdlen + len; 
31        
32      
33        encStream.Close(); 
34        fout.Close(); 
35        fin.Close(); 
36    
37      
38    //解密文件 
39    private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV) 
40    
41        //Create the file streams to handle the input and output files. 
42        FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read); 
43        FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write); 
44        fout.SetLength(0); 
45      
46        //Create variables to help with read and write. 
47        byte[] bin = new byte[100]; //This is intermediate storage for the encryption. 
48        long rdlen = 0;              //This is the total number of bytes written. 
49        long totlen = fin.Length;    //This is the total length of the input file. 
50        int len;                     //This is the number of bytes to be written at a time. 
51      
52        DES des = new DESCryptoServiceProvider(); 
53        CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write); 
54      
55        //Read from the input file, then encrypt and write to the output file. 
56        while (rdlen < totlen) 
57        
58            len = fin.Read(bin, 0, 100); 
59            encStream.Write(bin, 0, len); 
60            rdlen = rdlen + len; 
61        
62      
63        encStream.Close(); 
64        fout.Close(); 
65        fin.Close(); 
66  
67}

 

view sourceprint?
01using System;
02using System.Security.Cryptography;//这个是处理文字编码的前提
03using System.Text;
04using System.IO;
05/// <summary>
06/// DES加密方法
07/// </summary>
08/// <param name="strPlain">明文</param>
09/// <param name="strDESKey">密钥</param>
10/// <param name="strDESIV">向量</param>
11/// <returns>密文</returns>
12public string DESEncrypt(string strPlain,string strDESKey,string strDESIV)
13{
14 //把密钥转换成字节数组
15 byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
16 //把向量转换成字节数组
17 byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
18 //声明1个新的DES对象
19 DESCryptoServiceProvider desEncrypt=new DESCryptoServiceProvider();
20 //开辟一块内存流
21 MemoryStream msEncrypt=new MemoryStream();
22 //把内存流对象包装成加密流对象
23 CryptoStream csEncrypt=new CryptoStream(msEncrypt,desEncrypt.CreateEncryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Write);
24 //把加密流对象包装成写入流对象
25 StreamWriter swEncrypt=new StreamWriter(csEncrypt);
26 //写入流对象写入明文
27 swEncrypt.WriteLine(strPlain);
28 //写入流关闭
29 swEncrypt.Close();
30 //加密流关闭
31 csEncrypt.Close();
32 //把内存流转换成字节数组,内存流现在已经是密文了
33 byte[] bytesCipher=msEncrypt.ToArray();
34 //内存流关闭
35 msEncrypt.Close();
36 //把密文字节数组转换为字符串,并返回
37 return UnicodeEncoding.Unicode.GetString(bytesCipher);
38}
39  
40  
41  
42  
43/// <summary>
44/// DES解密方法
45/// </summary>
46/// <param name="strCipher">密文</param>
47/// <param name="strDESKey">密钥</param>
48/// <param name="strDESIV">向量</param>
49/// <returns>明文</returns>
50public string DESDecrypt(string strCipher,string strDESKey,string strDESIV)
51{
52 //把密钥转换成字节数组
53 byte[] bytesDESKey=ASCIIEncoding.ASCII.GetBytes(strDESKey);
54 //把向量转换成字节数组
55 byte[] bytesDESIV=ASCIIEncoding.ASCII.GetBytes(strDESIV);
56 //把密文转换成字节数组
57 byte[] bytesCipher=UnicodeEncoding.Unicode.GetBytes(strCipher);
58 //声明1个新的DES对象
59 DESCryptoServiceProvider desDecrypt=new DESCryptoServiceProvider();
60 //开辟一块内存流,并存放密文字节数组
61 MemoryStream msDecrypt=new MemoryStream(bytesCipher);
62 //把内存流对象包装成解密流对象
63 CryptoStream csDecrypt=new CryptoStream(msDecrypt,desDecrypt.CreateDecryptor(bytesDESKey,bytesDESIV),CryptoStreamMode.Read);
64 //把解密流对象包装成读出流对象
65 StreamReader srDecrypt=new StreamReader(csDecrypt);
66 //明文=读出流的读出内容
67 string strPlainText=srDecrypt.ReadLine();
68 //读出流关闭
69 srDecrypt.Close();
70 //解密流关闭
71 csDecrypt.Close();
72 //内存流关闭
73 msDecrypt.Close();
74 //返回明文
75 return strPlainText;
76}
原创粉丝点击