using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace SanCeng
{
class Program
{
static void Main(string[] args)
{
while (true)
{
//Console.WriteLine("请输入一个字符串:");
//string str = Console.ReadLine();
//string md5str=MD5Encrypt(str);
//Console.WriteLine(md5str);
//Console.WriteLine("OK");
Console.WriteLine("请输入一个文件路径");
string filepath = Console.ReadLine();
string md5file = MD5EncryptFromFile(filepath);
Console.WriteLine(md5file);
Console.WriteLine("OK");
Console.ReadKey();
}
}
/// <summary>
/// 文件MD5加密
/// </summary>
/// <returns></returns>
private static string MD5EncryptFromFile(string path)
{
MD5 md5 = MD5.Create();
using(FileStream fs=File.OpenRead(path)){
byte[] buffer = md5.ComputeHash(fs);
md5.Clear();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
//x2:把每个数字转换为16进制,并保留两位数字。
sb.Append(buffer[i].ToString("x2"));
}
return sb.ToString();
}
}
/// <summary>
/// 字符串加密
/// </summary>
/// <param name="str"></param>
/// <returns></returns>
private static string MD5Encrypt(string str)
{
Byte[] buffer = Encoding.Default.GetBytes(str);
MD5 md5 = MD5.Create();
Byte[] comBuffer = md5.ComputeHash(buffer);
md5.Clear();
StringBuilder sb = new StringBuilder();
for (int i = 0; i < comBuffer.Length; i++)
{
sb.Append(comBuffer[i].ToString("x2"));
}
return sb.ToString();
}
}
}