-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathHasher.cs
More file actions
58 lines (53 loc) · 1.69 KB
/
Hasher.cs
File metadata and controls
58 lines (53 loc) · 1.69 KB
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
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace SharpUpdate
{
/// <summary>
/// The type of hash to create
/// </summary>
internal enum HashType
{
MD5,
SHA1,
SHA512
}
/// <summary>
/// Class used to generate hash sums of files
/// </summary>
internal static class Hasher
{
/// <summary>
/// Generate a hash sum of a file
/// </summary>
/// <param name="filePath">The file to hash</param>
/// <param name="algo">The Type of hash</param>
/// <returns>The computed hash</returns>
internal static string HashFile(string filePath, HashType algo)
{
switch (algo)
{
case HashType.MD5:
return MakeHashString(MD5.Create().ComputeHash(new FileStream(filePath, FileMode.Open)));
case HashType.SHA1:
return MakeHashString(SHA1.Create().ComputeHash(new FileStream(filePath, FileMode.Open)));
case HashType.SHA512:
return MakeHashString(SHA512.Create().ComputeHash(new FileStream(filePath, FileMode.Open)));
default:
return "";
}
}
/// <summary>
/// Converts byte[] to string
/// </summary>
/// <param name="hash">The hash to convert</param>
/// <returns>Hash as string</returns>
private static string MakeHashString(byte[] hash)
{
StringBuilder s = new StringBuilder();
foreach (byte b in hash)
s.Append(b.ToString("x2").ToLower());
return s.ToString();
}
}
}