zoukankan      html  css  js  c++  java
  • string扩展实现强悍的.Net不可逆加密方法 (转载)

     

    最近写加密方法,发现同类的加密方法的基类都是一直的,用泛型整合了一些加密方法,供大家参考

    实现方法:

    Code
    using System;
    using
     System.Text;
    using
     System.Security.Cryptography;

    namespace
     Zb
    {
        
    public static class
     StringExtensions
        {
            
    /// <summary>

            
    /// 不可逆加密
            
    /// </summary>

            
    /// <typeparam name="Algorithm">加密HASH算法</typeparam>
            
    /// <typeparam name="StringEncoding">字符编码</typeparam>
            
    /// <param name="str"></param>
            
    /// <returns></returns>
            public static string EncryptOneWay<Algorithm, StringEncoding>(this string str)
                
    where
     Algorithm : HashAlgorithm
                
    where
     StringEncoding : Encoding
            {
                Encoding enco 
    = Activator.CreateInstance<StringEncoding>
    ();
                
    byte[] inputBye =
     enco.GetBytes(str);

                
    byte[] bytes = Activator.CreateInstance<Algorithm>
    ().ComputeHash(inputBye);

                
    return System.BitConverter.ToString(bytes).Replace("-"""
    ); ;
            }
            
    /// <summary>

            
    /// 不可逆加密
            
    /// </summary>

            
    /// <typeparam name="Algorithm">加密HASH算法</typeparam>
            
    /// <param name="str">字符编码</param>
            
    /// <returns></returns>
            public static string EncryptOneWay<Algorithm>(this string str)
                
    where
     Algorithm : HashAlgorithm
            {
                
    return str.EncryptOneWay<Algorithm, System.Text.UTF8Encoding>
    ();
            }
        }
    }

    使用方法:

     1 MD5 : 

    string temp = "123".EncryptOneWay<System.Security.Cryptography.MD5CryptoServiceProvider, System.Text.UTF8Encoding>();
    2. sha1:
    string temp = "123".EncryptOneWay<System.Security.Cryptography.SHA1CryptoServiceProvider>();
    3 SHA256
     string temp = "123".EncryptOneWay<System.Security.Cryptography.SHA256Cng>();
    等所有的HASH算法都可以用
  • 相关阅读:
    (23)odoo中的domain表达式
    (11)lambda表达式用法
    (22)odoo 安装旧模块报错处理
    (21)odoo中的QWeb模板引擎
    (10)列表操作
    (09)异常处理
    (08)文件与目录
    (07)内存使用和变量赋值
    (06)正则表达式
    vue router路由(三)
  • 原文地址:https://www.cnblogs.com/wenjl520/p/1444678.html
Copyright © 2011-2022 走看看