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算法都可以用
posted @   温景良(Jason)  Views(563)  Comments(2Edit  收藏  举报
编辑推荐:
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
阅读排行:
· 周边上新:园子的第一款马克杯温暖上架
· Open-Sora 2.0 重磅开源!
· 分享 3 个 .NET 开源的文件压缩处理库,助力快速实现文件压缩解压功能!
· Ollama——大语言模型本地部署的极速利器
· DeepSeek如何颠覆传统软件测试?测试工程师会被淘汰吗?
点击右上角即可分享
微信分享提示