开发者

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

开发者 https://www.devze.com 2023-03-09 16:23 出处:网络
I am new to C# just want to ask some questions. I got a MD5 sum in C#, I should put the code in a class, but where am I going to 开发者_开发问答call this method code from? ASPX, or what?. I remember

I am new to C# just want to ask some questions.

  1. I got a MD5 sum in C#, I should put the code in a class, but where am I going to 开发者_开发问答call this method code from? ASPX, or what?. I remember that class cannot run on its own.

  2. How to write the method to call that?

  3. The file that i want to create a MD5 has for is a text file.

This is what I have found:

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();       
} 


You need to put this method inside some class. For example you could create a console application with the following contents:

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);
    }
}

Now the CryptoUtils class could be placed in a separate file.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号