散列运算

mscorlib.dll下的System.Security.Cryptography下:
抽象类HashAlgorithm
    抽象类MD5
        MD5CryptoServiceProvider
    SHA1
        SHA1CryptoServiceProvider密封类:调用Windows Crypto API
        SHA1Managed普通类:用托管代码写的
    SHA256
        SHA256CryptoServiceProvider
        SHA256Managed
    SHA384
    SHA512

 

□ 对字节数组或流散列运算

    class Program 
    { 
        static void Main(string[] args) 
        { 
            string str = "Hello World"; 
            HashAlgorithm hashAlgorithm = HashAlgorithm.Create(HashAlgorithmType.SHA1); 
            byte[] data = Encoding.Default.GetBytes(str); 
            byte[] digest = hashAlgorithm.ComputeHash(data); 
            foreach (byte b in digest) 
            { 
                Console.Write("{0:X}",b); 
            } 
            Console.ReadKey(); 
        } 
    }
 
    public class HashAlgorithmType 
    { 
        public const string SHA1 = "SHA1"; 
        public const string SHA256 = "SHA256"; 
        public const string SHA384 = "SHA384"; 
        public const string SHA512 = "SHA512"; 
        public const string MD5 = "MD5"; 
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

□ 密匙散列运算       

            string key = "secret key"; 
            byte[] data = Encoding.Default.GetBytes(key); 
            KeyedHashAlgorithm kha = new HMACSHA1(); 
            byte[] digest = kha.ComputeHash(data); 
            foreach (byte b in digest) 
            { 
                Console.Write("{0:x}",b); 
            }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

  对称加密和解密

SymmetricAlgorithm

    DES

        DESCryptoServiceProvider

    TripleDES

        TripleDESCryptoServiceProvider

    Rijndael

        RijindaelManaged

    RC2  
        RC2CryptoServiceProvider

 

IV:Initialization vector初始化向量:

-为了解决加密字符串加密后仍然有重复部分,引入IV,加密字符串即使有重复,也会被打乱。

-IV值可以随意指定,但长度固定,通常为64位byte类型

-密匙长度也是固定的,通常为128位或196位byte类型

 

使用Encoding类将字符串转换为byte[]:

-如果使用UTF8,会变长编码

 

加密解密方法:

-加密方法:CreateEncryptor(),返回ICryptoTransform接口类型

-解密方法:CreateDecryptor(),返回ICrtyptoTransform接口类型

 

明文流和加密流的转换:

public CryptoStream(Stream stream, ICryptoTransform transform, CryptoStreamMode mode)
 
    class Program 
    { 
        static void Main(string[] args) 
        { 
            #region 对称加密和解密
 
            string key = "secret key"; 
            string str = "Hello World";
 
            //加密 
            string encryptedText = SymmetricCryptoHelper.Encrypt(str, key); 
            Console.WriteLine(encryptedText);
 
            //解密 
            string clearText = SymmetricCryptoHelper.Decrypt(encryptedText, key); 
            Console.WriteLine(clearText);
 
            Console.ReadKey();
 
            #endregion 
        } 
    }
 
    //对称加密帮助类 
    public class SymmetricCryptoHelper 
    { 
        private ICryptoTransform encryptor;  //加密器对象 
        private ICryptoTransform decryptor; //解密器对象 
        private const int BufferSize = 1024;
 
        public SymmetricCryptoHelper(string algorithmName, byte[] key) 
        { 
            SymmetricAlgorithm provider = SymmetricAlgorithm.Create(algorithmName); 
            provider.Key = key; 
            provider.IV = new byte[] { 0x12, 0x34, 0x56, 0x78, 0x90, 0xAB, 0xCD, 0xEF };
 
            encryptor = provider.CreateEncryptor(); 
            decryptor = provider.CreateDecryptor(); 
        }
 
        public SymmetricCryptoHelper(byte[] key) : this("TripleDES", key){}
 
        //加密算法 
        public string Encrypt(string clearText) 
        { 
            //创建明文流 
            byte[] clearBuffer = Encoding.UTF8.GetBytes(clearText); 
            //byte[] clearBuffer = Encoding.Default.GetBytes(clearText); 
            MemoryStream clearStream = new MemoryStream(clearBuffer);
 
            //创建空的密文流 
            MemoryStream encryptedStream = new MemoryStream();
 
            //明文流和密文流转换流,准备写到密文流中 
            CryptoStream cryptoStream = new CryptoStream(encryptedStream, encryptor, CryptoStreamMode.Write); 
           
            int bytesRead = 0; 
            byte[] buffer = new byte[BufferSize]; 
            do 
            { 
                //读取明文流到buffer中 
                bytesRead = clearStream.Read(buffer, 0, BufferSize); 
                //通过CryptoStream将buffer中的明文流字节数组写到明文流中 
                cryptoStream.Write(buffer, 0, bytesRead); 
            } while (bytesRead > 0);
 
            cryptoStream.FlushFinalBlock();
 
            //获取加密后的字节数组 
            buffer = encryptedStream.ToArray();
 
            //将加密后的字节数组转换成字符串 
            string encryptedText = Convert.ToBase64String(buffer); 
            return encryptedText; 
        }
 
        //解密算法 
        public string Decrypt(string encryptedText) 
        { 
            //把加密字符串转换为加密字节数组 
            byte[] encryptedBuffer = Convert.FromBase64String(encryptedText); 
            //创建密文流 
            Stream encryptedStream = new MemoryStream(encryptedBuffer);
 
            //创建空的明文流 
            MemoryStream clearStream = new MemoryStream();
 
            //创建明文流和密文流的转化流,读取密文流 
            CryptoStream cryptoStream = new CryptoStream(encryptedStream, decryptor, CryptoStreamMode.Read);
 
            int bytesRead = 0; 
            byte[] buffer = new byte[BufferSize];
 
            do 
            { 
                //通过CryptoStream读取密文流到Buffer 
                bytesRead = cryptoStream.Read(buffer, 0, BufferSize); 
                //把Buffer中的密文流写到明文流中 
                clearStream.Write(buffer, 0, bytesRead); 
            } while (bytesRead > 0);
 
            //将明文流转换成字节数组 
            buffer = clearStream.GetBuffer();
 
            string clearText = Encoding.UTF8.GetString(buffer, 0, (int)clearStream.Length); 
            //string clearText = Encoding.Default.GetString(buffer, 0, (int)clearStream.Length); 
            return clearText; 
        }
 
        //密匙加密 
        public static string Encrypt(string clearText, string key) 
        { 
            byte[] keyData = new byte[16]; //TripleDES密匙固定长度为16个字节
 
            //把密匙字符串转换成字节数组 
            byte[] sourceData = Encoding.Default.GetBytes(key); 
            int copyBytes = 16; 
            if (sourceData.Length < 16) 
            { 
                copyBytes = sourceData.Length; 
            }
 
            //把密匙数组复制到keyData字节数组中 
            Array.Copy(sourceData,keyData,copyBytes);
 
            SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData); 
            return helper.Encrypt(clearText); 
        }
 
        //密匙解密 
        public static string Decrypt(string encryptedText, string key) 
        { 
            byte[] keyData = new byte[16]; 
            byte[] sourceData = Encoding.Default.GetBytes(key); 
            int copyBytes = 16; 
            if (sourceData.Length < 16) 
            { 
                copyBytes = sourceData.Length; 
            } 
            Array.Copy(sourceData,keyData,copyBytes);
 
            SymmetricCryptoHelper helper = new SymmetricCryptoHelper(keyData); 
            return helper.Decrypt(encryptedText); 
        } 
    }
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

  非对称加密

AsymmetricAlgorithm

    RSA

        RSACryptoServiceProvider

    DSA

        DSACryptoServiceProvider:只能进行认证模式,即数字签名

 

对称加密中的密匙:

密匙为由开发者设定的字符串

 

非对称加密中的密匙:

● 通常是自动生成,不同的算法有不同的密匙格式   
● 在创建RSACryptoServiceProvider实例时,会自动创建一个公/私密匙对。在实例上调用ToXmlString()方法获得。

            RSACryptoServiceProvider provider = new RSACryptoServiceProvider();

            string publicPrivate = provider.ToXmlString(true);//获得公/私匙对

            //string publicOnly = provider.ToXmlString(false); //只获得公匙

            Console.Write(publicPrivate);

            Console.ReadKey();

 

□ 非对称加密帮助类

    //非对称加密帮助类 
    public class RSACryptoHelper 
    { 
        //加密 
        public static string Encrypt(string publicKeyXml, string plainText) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(publicKeyXml); //使用公匙初始化对象 
            byte[] plainData = Encoding.Default.GetBytes(plainText); 
            byte[] encryptedData = provider.Encrypt(plainData, true); 
            return Convert.ToBase64String(encryptedData); 
        }
 
        //解密 
        public static string Decrypt(string privateKeyXml, string encryptedText) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(privateKeyXml); 
            byte[] encryptedData = Convert.FromBase64String(encryptedText); 
            byte[] plainData = provider.Decrypt(encryptedData, true); 
            string plainText = Encoding.Default.GetString(plainData); 
            return plainText; 
        } 
    }

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

  数字签名

RSACryptoServiceProvider或DSACryptoServiceProvider

SignData()对摘要进行签名,并返回签名后的摘要。

VerifyData()得出本地摘要,并解密传递进来的原始摘要,对比返回bool类型结果。

 

□ 数字签名帮助类

    public class RSACryptoHelper 
    { 
        public static string SignData(string plainText, string privateKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(privateKeyXml);
 
            byte[] plainData = Encoding.Default.GetBytes(plainText); 
            //设置获取摘要的算法 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            //获取签名过的摘要,是使用私匙加密过的摘要 
            byte[] signedDigest = provider.SignData(plainData, sha1); 
            return Convert.ToBase64String(signedDigest); 
        }
 
        public static bool VerifyData(string plainText, string signature, string publicKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(publicKeyXml);
 
            byte[] plainData = Encoding.Default.GetBytes(plainText); 
            byte[] signedDigest = Convert.FromBase64String(signature);
 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            bool isDataIntact = provider.VerifyData(plainData, sha1, signedDigest); 
            return isDataIntact; 
        }
 
        //使用SingnHash 
        public static string SignData2(string plainText, string privateKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(privateKeyXml); 
            byte[] plainData = Encoding.Default.GetBytes(plainText);
 
            //设置获取摘要的算法 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            //获得原始摘要 
            byte[] digestData = sha1.ComputeHash(plainData); 
            //对元素摘要进行签名 
            byte[] signedDigest = provider.SignHash(digestData, "SHA1"); 
            return Convert.ToBase64String(signedDigest); 
        }
 
        //使用VerifyHash 
        public static bool VerifyData2(string plainText, string signedDigest, string publicKeyXml) 
        { 
            RSACryptoServiceProvider provider = new RSACryptoServiceProvider(); 
            provider.FromXmlString(publicKeyXml);
 
            byte[] plainData = Encoding.Default.GetBytes("SHA1"); 
            byte[] signedDigestData = Convert.FromBase64String(signedDigest);
 
            //获得本地摘要 
            HashAlgorithm sha1 = HashAlgorithm.Create("SHA1"); 
            byte[] digest = sha1.ComputeHash(plainData);
 
            //解密签名 
            bool isDataIntact = provider.VerifyHash(digest, "SHA1", signedDigestData); 
            return isDataIntact; 
        } 
    }
 

.csharpcode, .csharpcode pre
{
font-size: small;
color: black;
font-family: consolas, "Courier New", courier, monospace;
background-color: #ffffff;
/*white-space: pre;*/
}
.csharpcode pre { margin: 0em; }
.csharpcode .rem { color: #008000; }
.csharpcode .kwrd { color: #0000ff; }
.csharpcode .str { color: #006080; }
.csharpcode .op { color: #0000c0; }
.csharpcode .preproc { color: #cc6633; }
.csharpcode .asp { background-color: #ffff00; }
.csharpcode .html { color: #800000; }
.csharpcode .attr { color: #ff0000; }
.csharpcode .alt
{
background-color: #f4f4f4;
width: 100%;
margin: 0em;
}
.csharpcode .lnum { color: #606060; }

 

参考资料:

《.NET之美》--张子阳,感谢写了这么好的书!   

33.NET对加密和解密的支持的更多相关文章

  1. php+js的 authcode 混淆加密和解密,php和js可以通用加密和解密

    <script> //md5.js var hexcase = 0; function hex_md5(a) { return rstr2hex(rstr_md5(str2rstr_utf ...

  2. iOS,一行代码进行RSA、DES 、AES、MD5加密、解密

    本文为投稿文章,作者:Flying_Einstein(简书) 加密的Demo,欢迎下载 JAVA端的加密解密,读者可以看我同事的这篇文章:http://www.jianshu.com/p/98569e ...

  3. 如何对web.config进行加密和解密

    http://blog.csdn.net/jf_jifei/article/details/6527390 在WEB网站开发过程中,如果我们将数据库连接字符串封装到.DLL文件中,将会给数据库和程序的 ...

  4. JS URL 使用base64加密与解密

    JS编码方式: <script type="text/javascript"> document.write(encodeURI("http://www.w3 ...

  5. 基于私钥加密公钥解密的RSA算法C#实现

    RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一 ...

  6. (转)DES、RSA、MD5、SHA、随机生成加密与解密

    一.数据加密/编码算法列表   常见用于保证安全的加密或编码算法如下:   1.常用密钥算法   密钥算法用来对敏感数据.摘要.签名等信息进行加密,常用的密钥算法包括:   DES(Data Encr ...

  7. 银联手机支付(.Net Csharp),3DES加密解密,RSA加密解密,RSA私钥加密公钥解密,.Net RSA 3DES C#

    前段时间做的银联支付,折腾了好久,拼凑的一些代码,有需要的朋友可以参考,本人.Net新手,不保证准确性! 这个银联手机支付没有SDK提供,技术支持也没有.Net的,真心不好搞! RSA加解密,这里有个 ...

  8. RSA不对称加密,公钥加密私钥解密,私钥加密公钥解密

    RSA算法是第一个能同时用于加密和数字签名的算法,也易于理解和操作. RSA是被研究得最广泛的公钥算法,从提出到现在已近二十年,经历了各种攻击的考验,逐渐为人们接受,普遍认为是目前最优秀的公钥方案之一 ...

  9. DES加密和解密PHP,Java,ObjectC统一的方法

    原文:DES加密和解密PHP,Java,ObjectC统一的方法 PHP的加解密函数 <?php class DesComponent { var $key = '12345678'; func ...

随机推荐

  1. POJ 3280 Cheapest Palindrome(区间DP求改成回文串的最小花费)

    题目链接:http://poj.org/problem?id=3280 题目大意:给你一个字符串,你可以删除或者增加任意字符,对应有相应的花费,让你通过这些操作使得字符串变为回文串,求最小花费.解题思 ...

  2. mysql慢sql报警系统

    前言:最近有同事反应有的接口响应时间时快时慢,经过排查有的数据层响应时间过长,为了加快定位定位慢sql的准确性,决定简单地搭建一个慢sql报警系统 具体流程如下架构图 第一步:记录日志 每个业务系统都 ...

  3. Ubuntu 搭建ELK

    一.简介 官网地址:https://www.elastic.co/cn/ 官网权威指南:https://www.elastic.co/guide/cn/elasticsearch/guide/curr ...

  4. linux下nc提交web报文问题

    1.用wireshark截取访问百度首页拿到的请求数据包: GET /index.php?tn=newbdie_bd_dg&bar= HTTP/1.1 Host: www.baidu.com ...

  5. sicily 1046. Plane Spotting(排序求topN)

    DescriptionCraig is fond of planes. Making photographs of planes forms a major part of his daily lif ...

  6. 解析文本文件 "r" 与 "rb" 模式的区别(Python)

    r,rb 那么在读文件时,有无b标识的的主要区别在哪里呢? 1.文件使用方式标识 'r':默认值,表示从文件读取数据.'b':表示要读写二进制数据 2.读文件 进行读文件操作时,直到读到文档结束符(E ...

  7. Mysql安装(绿色版安装)

    一:下载 1.官网 https://dev.mysql.com/ 2.下载 3.下载 二:安装 1.将官网上下载的包进行解压 2.以管理员的身份运行DOS安装 进入mysql的bin目录 运行mysq ...

  8. java中int和Integer比较

    java中int和Integer比较 一,类型区别 我们知道java中由两种数据类型,即基本类型和对象类型,int就是基本数据类型,而Integer是一个class,也习惯把Integer叫做int的 ...

  9. Android与GPL、BSD和Apache之间的关系

    参考资料 Android ,在争议中逃离 Linux 内核的 GPL 约束 | 爱范儿 简介 众所周知,Linux内核基于GPL v2发行.GPL规定,基于GPL的软件产品的衍生产品,也必须使用GPL ...

  10. 深入理解Python生成器(Generator)

    我们可以通过列表生成式简单直接地创建一个列表,但是受到内存限制,列表容量肯定是有限的.而且,创建一个包含100万个元素的列表,不仅占用很大的存储空间,而且如果我们仅仅需要访问前面几个元素,那后面绝大多 ...