繁体   English   中英

如何在C#中生成MD5和并执行代码?

[英]How to generate MD5 sum in C# and execute the code?

我是 C# 的新手,只是想问一些问题。

  1. 我在 C# 中得到了一个 MD5 和,我应该把代码放在 class 中,但是我要从哪里调用这个方法代码呢? ASPX,还是什么? 我记得 class 不能自己运行。

  2. 如何编写调用它的方法?

  3. 我要创建 MD5 的文件是文本文件。

这是我发现的:

public static string CalculateMD5Hash(string strInput)
{
  MD5 md5 = System.Security.Cryptography.MD5.Create();
  byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strInput);
  byte[] hash = md5.ComputeHash(inputBytes);             

  StringBuilder sb = new StringBuilder();            
  for (int i = 0; i < hash.Length; i++)            
  {                
    sb.Append(hash[i].ToString("x2")); 
  }         
  return sb.ToString();       
} 

您需要将此方法放入一些 class 中。 例如,您可以创建一个包含以下内容的控制台应用程序:

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

public class CryptoUtils
{
    public static string CalculateMD5Hash(string strInput)
    {
        MD5 md5 = System.Security.Cryptography.MD5.Create();
        byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(strInput);
        byte[] hash = md5.ComputeHash(inputBytes);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < hash.Length; i++)
        {
            sb.Append(hash[i].ToString("x2"));
        }
        return sb.ToString();
    } 
}

class Program
{
    static void Main()
    {
        var input = "some input";
        var md5 = CryptoUtils.CalculateMD5Hash(input);
        Console.WriteLine(md5);
    }
}

现在CryptoUtils class 可以放在一个单独的文件中。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM