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算法都可以用
  • 相关阅读:
    安信天行全方位信息安全态势感知平台建设与运营
    SQL基础总结——20150730
    中兴推“小兴看看”,诠释智能家电的真谛
    Java 线程第三版 第九章 Thread调度 读书笔记
    3930: [CQOI2015]选数|递推|数论
    S​D​I​与​A​S​I 接口具体解释介绍
    通过双重for循环来找到JSON中不反复的数据
    蓝桥杯 2016/3/17 測试 前6题题解...
    [疯狂Java]JDBC:事务管理、中间点、批量更新
    Linux下搭建Memcached缓存系统
  • 原文地址:https://www.cnblogs.com/wenjl520/p/1444678.html
Copyright © 2011-2022 走看看