1.加密模块首先要添加引用
using Microsoft.Practices.EnterpriseLibrary.Security.Cryptography;
2.创建配置文件
通过Enterprise Library Configuration工具打开app.config文件,如图
创建Cryptography Application Block节。系统会自动添加两个子节。Hash Providers和Symmetric Providers.
1)前一个是Hash算法加密,后者是对称算法加密。

Enterprise Library 4.1 学习笔记( 三)加密模块
2)删除Hash Providers节下SHA1Managed节,添加新节
Enterprise Library 4.1 学习笔记( 三)加密模块
Enterprise Library 4.1 学习笔记( 三)加密模块
选择偏好的加密方法。点击确定。
3)定义对称加密算法,操作类似hash加密算法
   选择加密程序提供者

Enterprise Library 4.1 学习笔记( 三)加密模块

   选择加密算法

Enterprise Library 4.1 学习笔记( 三)加密模块

创建密匙

Enterprise Library 4.1 学习笔记( 三)加密模块

生成密匙

Enterprise Library 4.1 学习笔记( 三)加密模块

 指定密匙文件

Enterprise Library 4.1 学习笔记( 三)加密模块

指定加密模式(机器模式/用户模式)。完成加密

Enterprise Library 4.1 学习笔记( 三)加密模块

文件配置结束
3.代码
1)首先指定加密配置信息
        static string hashName = "SHA1Managed";
        
static string symmetricName = "TripleDESCryptoServiceProvider";
其中hashName对应配置文件中加密模块子节hash providers 中hash算法名称
symmetricName对应配置文件中加密模块子节symmetric providers中对称算法的名称
2)实现对称算法验证
Enterprise Library 4.1 学习笔记( 三)加密模块
        static void Symmetric()
        {
            
//待加密字符串
            string test = "123456";
            
//加密后字符串
            string oldstring;
            
//解密后字符串
            string newstring;
            
//加密
            oldstring = Cryptographer.EncryptSymmetric(symmetricName, test);
            
//解密
            newstring = Cryptographer.DecryptSymmetric(symmetricName, oldstring);
            
            
//打印

            Console.WriteLine(test);
            Console.WriteLine(oldstring.ToString());
            Console.WriteLine(newstring);

        }
Cryptographer.EncryptSymmetric方法需要两个参数(加密算法名称和待加密字符串)
Cryptographer.decryptSymmetric方法需要两个参数(加密算法名称和待解密字符串)
输出
Enterprise Library 4.1 学习笔记( 三)加密模块

3)实现hash算法验证
Enterprise Library 4.1 学习笔记( 三)加密模块
        static void Hash()
        {
            
//待加密字符串
            string test = "123456";
            
//转换为byte数组
            byte[] oldstring;
            
//加密后的byte数组
            byte[] newstring;

            oldstring 
= System.Text.Encoding.UTF8.GetBytes(test);
            
//加密
            newstring = Cryptographer.CreateHash(hashName, oldstring);
            
//判断输入字符串是否与待加密支付串一致
            bool ok = Cryptographer.CompareHash(hashName, System.Text.Encoding.UTF8.GetBytes("123456"), newstring);
            Console.WriteLine(
"test : "+test);
            Console.WriteLine(
"result : "+ok.ToString());
            Console.WriteLine();
        }
Cryptographer.CreateHash()方法需要两个参数(加密算法名称和待加密字符串转换的字符数组)
Cryptographer.CompareHash()方法需要三个参数(加密算法名称和待比较字符串转换为字符数组以及待加密字符串转换的字符数组)
结果
Enterprise Library 4.1 学习笔记( 三)加密模块

相关文章: