zoukankan      html  css  js  c++  java
  • 一种计算MD5的实现方法

    1、在需要用到加密的地方可以使用.net中的md5相关的类生成md5给文件加密。

    2、基本思路:

    将文件也好,字符串也好,转成字节数组,再利用.net的md5相关类生成md5相关字符串,再将字符串转成16进制。

    3、具体的例子:

     1 using System;
     2 using System.Collections.Generic;
     3 using System.Linq;
     4 using System.Text;
     5 using System.Runtime.InteropServices;
     6 using System.Security.Cryptography;
     7 using System.IO;
     8 using System.Diagnostics;
     9 
    10 namespace MD5
    11 {
    12     public class MD5Hash 
    13     {
    14         public MD5Hash()
    15         {
    16             this.md5 = MD5.Create();
    17         }
    18 
    19         public string CalculateFile(string filePath)
    20         {
    21             string reuslt = string.Empty;
    22 
    23             try
    24             {
    25              reuslt = Calculate(System.IO.File.ReadAllBytes(filePath));
    26             }
    27             catch (Exception e)
    28             {
    29                 reuslt = string.Empty;
    30             }
    31 
    32             return reuslt;
    33         }
    34         
    35         public string Calculate(byte[] buffer)
    36         {
    37             return Format(md5.ComputeHash(buffer));
    38         }
    39                 
    40         private string Format(byte[] source)
    41         {
    42             StringBuilder result = new StringBuilder(string.Empty);
    43 
    44             Array.ForEach(source, (value) => result.Append(value.ToString("X2")));
    45 
    46             return result.ToString();
    47         }
    48                 
    49         public string Calculate(string message)
    50         {
    51             return Calculate(message, Encoding.UTF8);
    52         }
    53 
    54         public string Calculate(string message, Encoding encoder)
    55         {
    56             return Calculate(encoder.GetBytes(message));
    57         }
    58 
    59         private MD5 md5;
    60     }
    61 }
  • 相关阅读:
    .NET面试题系列[2]
    .NET面试题系列[1]
    被淡忘的c#析构函数
    关于Spring IOC容器解释
    工作随笔记 点击除div自身之外的地方,关闭自己
    js获得控件位置
    PHP如何判断对象为空的方法分享
    PHP 网页调用本地exe程序实例
    PHP jQuery实现上传图片时预览图片的功能实例
    Yii 自带的分页实例
  • 原文地址:https://www.cnblogs.com/hshuzhao/p/4185411.html
Copyright © 2011-2022 走看看