• 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算法都可以用
  • 相关阅读:
    搜狗输入法弹出广告
    PHP uploadify io error错误如何解决?
    读写生信流程必备的 Perl 语法
    Illumina Sequence Identifiers 序列标识符 index详解
    真核生物基因结构 & mRNA结构
    主成分分析(PCA)原理及R语言实现 | 降维dimension reduction | Principal component analysis
    CRISPR基因编辑
    表观遗传学
    Shiny+SQLite打造轻量级网页应用
    探索gff/gtf格式
  • 原文地址:https://www.cnblogs.com/wenjl520/p/1444678.html
Copyright © 2020-2023  润新知