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

C#常用的加密算法的更多相关文章

  1. DotNet中几种常用的加密算法

    在.NET项目中,我们较多的使用到加密这个操作.因为在现代的项目中,对信息安全的要求越来越高,那么多信息的加密就变得至关重要.现在提供几种常用的加密/解密算法. 1.用于文本和Base64编码文本的互 ...

  2. 目前常用的加密算法有DES(Data Encryption Standard)和IDEA(International Data Encryption Algorithm)国际数据加密算法等,请用工厂方法实现加密算法系统。提交该系统的代码,该系统务必是一个可以能够直接使用的系统,查阅资料完成相应加密算法的实现;

    1.加密算法的类图结构 2.源代码 2.1代码运行截图 2.2代码的目录结构 2.3具体代码 MethodFactory.java package jiami; public interface Me ...

  3. 微信小程序及各种平台对接常用可逆加密算法aes256

    不同程序之间经常会交换数据,我们经常采用的套路是: 假设要传输的信息是json,我们假设其为json_data,通过http传递信息为 json_data_encode=json_data&s ...

  4. 常用对称加密算法(DES/AES)类(PHP)

    看注释,啥也不说了,欢迎各种跨平台测试! /** * 常用对称加密算法类 * 支持密钥:64/128/256 bit(字节长度8/16/32) * 支持算法:DES/AES(根据密钥长度自动匹配使用: ...

  5. Java中常用的加密算法MD5,SHA,RSA

    1. MD5加密,常用于加密用户名密码,当用户验证时. protected byte[] encrypt(byte[] obj){  try {  MessageDigest md5 = Messag ...

  6. C#开发中常用的加密算法总结

    相信很多人在开发过程中经常会遇到需要对一些重要的信息进行加密处理,今天给大家分享我个人总结的一些加密算法: 常见的加密方式分为可逆和不可逆两种方式 可逆:RSA,AES,DES等 不可逆:常见的MD5 ...

  7. Java中常用的加密算法小结

      散列算法(单向散列,不可逆) MD5(Message Digest Algorithm 5) SHA(Secure Hash Algorithm)   对称加密(加密解密使用同一密钥,速度快) D ...

  8. java算法----------常用的加密算法

    散列算法(单向散列,不可逆) MD5(Message Digest Algorithm 5) SHA(Secure Hash Algorithm)   对称加密(加密解密使用同一密钥,速度快) DES ...

  9. 常用加密算法的Java实现总结

    常用加密算法的Java实现(一) ——单向加密算法MD5和SHA 1.Java的安全体系架构 1.1           Java的安全体系架构介绍 Java中为安全框架提供类和接口.JDK 安全 A ...

随机推荐

  1. Sbt的使用初步和用sbt插件生成eclipse工程

    以前一直是用maven去管理java项目,现在开始写scala项目了但是在scala-ide中去编译scala项目和sbt的区别一直没弄清楚受到文章:http://my.oschina.net/yjw ...

  2. 读jQuery源码有感3

    这次的主题是,具体的库和抽象的思路. 当看到Deferred这个区块时,觉得jQuery代码设计挺复杂,得用许多脑力才能看明白. 可是把这个峰回路转十八回的代码看懂又如何,是为了使用过程中出现bug后 ...

  3. poj3855Blast the Enemy!(多边形重心)

    链接 #include <iostream> #include<cstdio> #include<cstring> #include<algorithm> ...

  4. epoll中et+多线程模式中很重要的EPOLL_ONESHOT实验

    因为et模式需要循环读取,但是在读取过程中,如果有新的事件到达,很可能触发了其他线程来处理这个socket,那就乱了. EPOLL_ONESHOT就是用来避免这种情况.注意在一个线程处理完一个sock ...

  5. Android Glide+CircleImageView实现加载圆形图片列表

    需求:要在列表中实现圆形图片的显示,控件可能和加载库会存在冲突 先上代码,至于其中源码,以后有空再分析 MainActivity public class MainActivity extends A ...

  6. 转:Effective c + + notes

    补充自己的. 转自:http://blog.csdn.net/ysu108/article/details/9853963#t0 Effective C++ 笔记 目录(?)[-] 第一章 从C转向C ...

  7. matlab 自动阈值白平衡算法 程序可编译实现

    一种效果很好的自动白平衡技术(WhiteBalance) 白平衡是图像处理的一个极重要概念.所谓白平衡(英文名称为White Balance),就是对白色物体的还原.当我们用肉眼观看这大千世界时,在不 ...

  8. MATLAB 编程风格指南及注意事项

    MATLAB编程风格指南Richard Johnson 著Genial 译MATLAB 编程风格指南Richard JohnsonVersion 1.5,Oct. 2002版权: Datatool 所 ...

  9. imageview圆角的实现

    介绍一种简单的.另类的实现,就是把图片在显示前处理成圆角的,但是不改变存储的图片.相当于经过了图像过滤. 需要调用的图像工具类是 package com.gaosi.util; /** * @auth ...

  10. Nodejs 配置+基础

    Nodejs + NPP 配置. http://blog.csdn.net/foruok/article/details/48366765 NPM的全称是Node Package Manager,它就 ...