1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79
| public enum HashType { MD5 = 0, SHA1=1 } public class Md5Checker { public static string MD5File(string fileName) { return HashFile(fileName, HashType.MD5); }
public static string SHA1File(string fileName) { return HashFile(fileName, HashType.SHA1); } public static string HashFile(string fileName, HashType hashType) { if (!System.IO.File.Exists(fileName)) return string.Empty;
FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read); byte[] hashBytes = HashData(fs, hashType); fs.Close(); return ByteArrayToHexString(hashBytes); } public static byte[] HashData(Stream stream, HashType hashType) { HashAlgorithm algorithm = null; switch (hashType) { case HashType.MD5: algorithm = MD5.Create(); break; case HashType.SHA1: algorithm = SHA1.Create(); break; default: break; } return algorithm.ComputeHash(stream); } public static string ByteArrayToHexString(byte[] buf) { int iLen = 0;
Type type = typeof(System.Web.Configuration.MachineKeySection); MethodInfo byteArrayToHexString = type.GetMethod("ByteArrayToHexString", BindingFlags.Static | BindingFlags.NonPublic);
return (string)byteArrayToHexString.Invoke(null, new object[] { buf, iLen }); } }
|