forked from Rampastring/Rampastring.Tools
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathUtilities.cs
58 lines (54 loc) · 1.77 KB
/
Utilities.cs
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;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace Rampastring.Tools
{
/// <summary>
/// A static class that contains various useful functions.
/// </summary>
public static class Utilities
{
/// <summary>
/// Calculates the SHA1 checksum of a file.
/// </summary>
/// <param name="path">The file's path.</param>
/// <returns>A string that represents the file's SHA1.</returns>
public static string CalculateSHA1ForFile(string path)
{
if (!File.Exists(path))
return String.Empty;
using (SHA1 sha1 = new SHA1CryptoServiceProvider())
{
using (Stream stream = File.OpenRead(path))
{
byte[] hash = sha1.ComputeHash(stream);
return BytesToString(hash);
}
}
}
/// <summary>
/// Calculates the SHA1 checksum of a string.
/// </summary>
/// <param name="str">The string.</param>
/// <returns>A string that represents the input string's SHA1.</returns>
public static string CalculateSHA1ForString(string str)
{
using (SHA1 sha1 = new SHA1CryptoServiceProvider())
{
byte[] buffer = Encoding.ASCII.GetBytes(str);
byte[] hash = sha1.ComputeHash(buffer);
return BytesToString(hash);
}
}
private static string BytesToString(byte[] bytes)
{
StringBuilder sb = new StringBuilder();
for (int i = 0; i < bytes.Length; i++)
{
sb.Append(bytes[i].ToString("x2"));
}
return sb.ToString();
}
}
}