转发:C#加密方法汇总

    转自:C#加密方法汇总 

  方法一:

 1 //须添加对System.Web的引用
 2 using System.Web.Security;
 3 ...
 4 /// <summary>
 5 /// SHA1加密字符串
 6 /// </summary>
 7 /// <param name="source">源字符串</param>
 8 /// <returns>加密后的字符串</returns>
 9 public string SHA1(string source)
10 {
11     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "SHA1");
12 }
13 /// <summary>
14 /// MD5加密字符串
15 /// </summary>
16 /// <param name="source">源字符串</param>
17 /// <returns>加密后的字符串</returns>
18 public string MD5(string source)
19 {
20     return FormsAuthentication.HashPasswordForStoringInConfigFile(source, "MD5");;
21 }

  方法二(可逆加密解密):

 1 using System.Security.Cryptography;
 2 ...
 3 public string Encode(string data)
 4 {
 5     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
 6     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
 7     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
 8     int i = cryptoProvider.KeySize;
 9     MemoryStream ms = new MemoryStream();
10     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write);
11     StreamWriter sw = new StreamWriter(cst);
12     sw.Write(data);
13     sw.Flush();
14     cst.FlushFinalBlock();
15     sw.Flush();
16     return Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length);
17 }
18 public string Decode(string data)
19 {
20     byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(KEY_64);
21     byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(IV_64);
22     byte[] byEnc;
23     try
24     {
25         byEnc = Convert.FromBase64String(data);
26     }
27     catch
28     {
29         return null;
30     }
31     DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider();
32     MemoryStream ms = new MemoryStream(byEnc);
33     CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read);
34     StreamReader sr = new StreamReader(cst);
35     return sr.ReadToEnd();
36 }

  方法三(MD5不可逆):

 1 using System.Security.Cryptography;
 2 ...
 3 //MD5不可逆加密
 4 //32位加密
 5 public string GetMD5_32(string s, string _input_charset)
 6 {
 7     MD5 md5 = new MD5CryptoServiceProvider();
 8     byte[] t = md5.ComputeHash(Encoding.GetEncoding(_input_charset).GetBytes(s));
 9     StringBuilder sb = new StringBuilder(32);
10     for (int i = 0; i < t.Length; i++)
11     {
12         sb.Append(t[i].ToString("x").PadLeft(2, ‘0‘));
13     }
14     return sb.ToString();
15 }
16 //16位加密
17 public static string GetMd5_16(string ConvertString)
18 {
19     MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
20     string t2 = BitConverter.ToString(md5.ComputeHash(UTF8Encoding.Default.GetBytes(ConvertString)), 4, 8);
21     t2 = t2.Replace("-", "");
22     return t2;
23 }

  方法四(对称加密):

 1 using System.IO;
 2 using System.Security.Cryptography;
 3 ...
 4 private SymmetricAlgorithm mobjCryptoService;
 5 private string Key;
 6 /// <summary>
 7 /// 对称加密类的构造函数
 8 /// </summary>
 9 public SymmetricMethod()
10 {
11     mobjCryptoService = new RijndaelManaged();
12     Key = "Guz(%&hj7x89H$yuBI0456FtmaT5&fvHUFCy76*h%(HilJ$lhj!y6&(*jkP87jH7";
13 }
14 /// <summary>
15 /// 获得密钥
16 /// </summary>
17 /// <returns>密钥</returns>
18 private byte[] GetLegalKey()
19 {
20     string sTemp = Key;
21     mobjCryptoService.GenerateKey();
22     byte[] bytTemp = mobjCryptoService.Key;
23     int KeyLength = bytTemp.Length;
24     if (sTemp.Length > KeyLength)
25         sTemp = sTemp.Substring(0, KeyLength);
26     else if (sTemp.Length < KeyLength)
27         sTemp = sTemp.PadRight(KeyLength, ‘ ‘);
28     return ASCIIEncoding.ASCII.GetBytes(sTemp);
29 }
30 /// <summary>
31 /// 获得初始向量IV
32 /// </summary>
33 /// <returns>初试向量IV</returns>
34 private byte[] GetLegalIV()
35 {
36     string sTemp = "E4ghj*Ghg7!rNIfb&95GUY86GfghUb#er57HBh(u%g6HJ($jhWk7&!hg4ui%$hjk";
37     mobjCryptoService.GenerateIV();
38     byte[] bytTemp = mobjCryptoService.IV;
39     int IVLength = bytTemp.Length;
40     if (sTemp.Length > IVLength)
41         sTemp = sTemp.Substring(0, IVLength);
42     else if (sTemp.Length < IVLength)
43         sTemp = sTemp.PadRight(IVLength, ‘ ‘);
44     return ASCIIEncoding.ASCII.GetBytes(sTemp);
45 }
46 /// <summary>
47 /// 加密方法
48 /// </summary>
49 /// <param name="Source">待加密的串</param>
50 /// <returns>经过加密的串</returns>
51 public string Encrypto(string Source)
52 {
53     byte[] bytIn = UTF8Encoding.UTF8.GetBytes(Source);
54     MemoryStream ms = new MemoryStream();
55     mobjCryptoService.Key = GetLegalKey();
56     mobjCryptoService.IV = GetLegalIV();
57     ICryptoTransform encrypto = mobjCryptoService.CreateEncryptor();
58     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Write);
59     cs.Write(bytIn, 0, bytIn.Length);
60     cs.FlushFinalBlock();
61     ms.Close();
62     byte[] bytOut = ms.ToArray();
63     return Convert.ToBase64String(bytOut);
64 }
65 /// <summary>
66 /// 解密方法
67 /// </summary>
68 /// <param name="Source">待解密的串</param>
69 /// <returns>经过解密的串</returns>
70 public string Decrypto(string Source)
71 {
72     byte[] bytIn = Convert.FromBase64String(Source);
73     MemoryStream ms = new MemoryStream(bytIn, 0, bytIn.Length);
74     mobjCryptoService.Key = GetLegalKey();
75     mobjCryptoService.IV = GetLegalIV();
76     ICryptoTransform encrypto = mobjCryptoService.CreateDecryptor();
77     CryptoStream cs = new CryptoStream(ms, encrypto, CryptoStreamMode.Read);
78     StreamReader sr = new StreamReader(cs);
79     return sr.ReadToEnd();
80 }

  方法五:

 1 using System.IO;
 2 using System.Security.Cryptography;
 3 using System.Text;
 4 ...
 5 //默认密钥向量
 6 private static byte[] Keys = { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
 7 /**//**//**//// <summary>
 8 /// DES加密字符串
 9 /// </summary>
10 /// <param name="encryptString">待加密的字符串</param>
11 /// <param name="encryptKey">加密密钥,要求为8位</param>
12 /// <returns>加密成功返回加密后的字符串,失败返回源串</returns>
13 public static string EncryptDES(string encryptString, string encryptKey)
14 {
15     try
16     {
17         byte[] rgbKey = Encoding.UTF8.GetBytes(encryptKey.Substring(0, 8));
18         byte[] rgbIV = Keys;
19         byte[] inputByteArray = Encoding.UTF8.GetBytes(encryptString);
20         DESCryptoServiceProvider dCSP = new DESCryptoServiceProvider();
21         MemoryStream mStream = new MemoryStream();
22         CryptoStream cStream = new CryptoStream(mStream, dCSP.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
23         cStream.Write(inputByteArray, 0, inputByteArray.Length);
24         cStream.FlushFinalBlock();
25         return Convert.ToBase64String(mStream.ToArray());
26     }
27     catch
28     {
29         return encryptString;
30     }
31 }
32 /**//**//**//// <summary>
33 /// DES解密字符串
34 /// </summary>
35 /// <param name="decryptString">待解密的字符串</param>
36 /// <param name="decryptKey">解密密钥,要求为8位,和加密密钥相同</param>
37 /// <returns>解密成功返回解密后的字符串,失败返源串</returns>
38 public static string DecryptDES(string decryptString, string decryptKey)
39 {
40     try
41     {
42         byte[] rgbKey = Encoding.UTF8.GetBytes(decryptKey);
43         byte[] rgbIV = Keys;
44         byte[] inputByteArray = Convert.FromBase64String(decryptString);
45         DESCryptoServiceProvider DCSP = new DESCryptoServiceProvider();
46         MemoryStream mStream = new MemoryStream();
47         CryptoStream cStream = new CryptoStream(mStream, DCSP.CreateDecryptor(rgbKey, rgbIV), CryptoStreamMode.Write);
48         cStream.Write(inputByteArray, 0, inputByteArray.Length);
49         cStream.FlushFinalBlock();
50         return Encoding.UTF8.GetString(mStream.ToArray());
51     }
52     catch
53     {
54         return decryptString;
55     }
56 } 

  方法六(文件加密):

 1 using System.IO;
 2 using System.Security.Cryptography;
 3 using System.Text;
 4 ...
 5 //加密文件
 6 private static void EncryptData(String inName, String outName, byte[] desKey, byte[] desIV)
 7 {
 8     //Create the file streams to handle the input and output files.
 9     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
10     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
11     fout.SetLength(0);
12     //Create variables to help with read and write.
13     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
14     long rdlen = 0;              //This is the total number of bytes written.
15     long totlen = fin.Length;    //This is the total length of the input file.
16     int len;                     //This is the number of bytes to be written at a time.
17     DES des = new DESCryptoServiceProvider();
18     CryptoStream encStream = new CryptoStream(fout, des.CreateEncryptor(desKey, desIV), CryptoStreamMode.Write);
19     //Read from the input file, then encrypt and write to the output file.
20     while (rdlen < totlen)
21     {
22         len = fin.Read(bin, 0, 100);
23         encStream.Write(bin, 0, len);
24         rdlen = rdlen + len;
25     }
26     encStream.Close();
27     fout.Close();
28     fin.Close();
29 }
30 //解密文件
31 private static void DecryptData(String inName, String outName, byte[] desKey, byte[] desIV)
32 {
33     //Create the file streams to handle the input and output files.
34     FileStream fin = new FileStream(inName, FileMode.Open, FileAccess.Read);
35     FileStream fout = new FileStream(outName, FileMode.OpenOrCreate, FileAccess.Write);
36     fout.SetLength(0);
37     //Create variables to help with read and write.
38     byte[] bin = new byte[100]; //This is intermediate storage for the encryption.
39     long rdlen = 0;              //This is the total number of bytes written.
40     long totlen = fin.Length;    //This is the total length of the input file.
41     int len;                     //This is the number of bytes to be written at a time.
42     DES des = new DESCryptoServiceProvider();
43     CryptoStream encStream = new CryptoStream(fout, des.CreateDecryptor(desKey, desIV), CryptoStreamMode.Write);
44     //Read from the input file, then encrypt and write to the output file.
45     while (rdlen < totlen)
46     {
47         len = fin.Read(bin, 0, 100);
48         encStream.Write(bin, 0, len);
49         rdlen = rdlen + len;
50     }
51     encStream.Close();
52     fout.Close();
53     fin.Close();
时间: 2024-10-05 08:52:25

转发:C#加密方法汇总的相关文章

C#加密方法汇总(SHA1加密字符串,MD5加密字符串,可逆加密等)

using System;using System.Collections.Generic;using System.Text; namespace StringEncry{ class EncodeAndDecode { /// <summary> /// Base64加密 /// </summary> /// <param name="codeName">加密采用的编码方式</param> /// <param name=&qu

加密方法汇总

1.C#加密算法总结 2.C# 常用加密方法收集 对称,非对称 3.C#使用RSA私钥加密公钥解密的改进,解决特定情况下解密后出现乱码的问题 4.Silverlight中非对称加密及数字签名RSA算法的实现 5.JavaScript DES 加密 6.各种加密解密函数(URL加密解密.sha1加密解密.des加密解密)网页版

PHP的加密方法汇总

PHP的加密主要有4种方法,除此之外还有一种是URL的加密和解密.希望可以对你们开发有用. 顺带,我会在后面把我整理的一整套CSS3,PHP,MYSQL的开发的笔记打包放到百度云,有需要可以直接去百度云下载,这样以后你们开发就可以直接翻笔记不用百度搜那么麻烦了.  笔记链接:http://pan.baidu.com/s/1qYdQdKK 密码:pvj2   一.md5()加密技术语法: string md5(string $str[,bool $raw_output=false]):计算str的

php使用N层加密eval gzinflate str_rot13 base64 破解方法汇总

php使用N层加密eval gzinflate str_rot13 base64 破解方法汇总 来源:本站转载 作者:佚名 时间:2011-02-14 TAG: 我要投稿 PHP使用eval(gzinflate(str_rot13(base64_decode('BASE64加密后内容'))))核心代码的解密 下非扩展方式的php加密方法: 这里有个在线的,还不错.木马防杀还行,要保护代码可就不行了. 对应的写了一个简单的解密的, 专门针对eval.这个原理很有用途. 特别说明:此解密程序好像一定

内网端口转发方法汇总

内网端口转发方法汇总 I. Sample Baklinks with "lcx.exe" first download lcx.exe from attach.blackbap.org/down/yclj/lcx.exe the program only can running in Windows Server, the program can backlink 3389 to another server. Opening and Listening a Port(like 333

ASP.NET(C#)常用数据加密和解密方法汇总

一.            数据加密的概念 1.  基本概念 2.  基本功能 3.  加密形式 二.            数据加密的项目应用和学习 1.  媒体加密:DRM 2.  文件加密:文本加密.pdf.word 3.  数据加密:ASP.NET(C#)中的数据加密 4.  硬件加密:加密狗 三.            数据加密的发展趋势 四.            网络数据加密算法分类 1.  根本不考虑解密问题:MD5. 2.  私用密钥加密:DES.AES 3.  公用密钥加密:

Linux ${}字符窜截取的方法汇总

Linux 字符窜截取的方法汇总 1.命令汇总 ${target-string#*sub-string} ${target-string##*sub-string} ${target-string%sub-string*} ${target-string%%*sub-string*} ---------------------------------------------------------------------------- ${target-string:start-index:st

Python字典高级使用方法汇总

Python字典高级使用方法汇总 字典(dictionary)是python中的一种非常灵活和强大的数据结构,可以完成很多操作.本文总结了一些除了基本的初始化.赋值.取值之外的常用的字典使用方法. 字典基础参考: [1]:http://www.w3cschool.cc/python/python-dictionary.html [2]:http://www.111cn.net/phper/python/56355.htm [3]:http://skyfen.iteye.com/blog/5675

Android项目:proguard混淆之常见问题及解决方法汇总

1.使用proguardgui混淆器对jar包进行混淆,出现EXCEPTION FROM SIMULATION错误: [2014-07-08 14:29:55 - Test024_HouseBox_v02_jar] Dx  EXCEPTION FROM SIMULATION: [2014-07-08 14:29:55 - Test024_HouseBox_v02_jar] Dx local variable type mismatch: attempt to set or access a va