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 that class cannot run on its own.
How to write the method to call that?
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.
精彩评论