CryptoServiceProvider - .NET下计算SHAx

在.NET框架下计算SHA1/SHA512

CryptoServiceProvider - .NET下计算SHAx

1 example

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
using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using System.Web.Hosting;

namespace Core.Common
{
/// <summary>
/// SHAUtility provides SHA hash functions for caculating signature/digest.
/// </summary>
public static class SHAUtility
{
/// <summary>
/// Compute SHA1 of a Stream instance, return the hex content string
/// </summary>
/// <param name="stream"></param>
/// <returns></returns>
public static string SHA1Hash(Stream stream)
{
SHA1 sha1 = new SHA1CryptoServiceProvider();

stream.Seek(0, SeekOrigin.Begin);
string sha1Str = BitConverter.ToString(sha1.ComputeHash(stream)).Replace("-", ""); // get SHA1 file hash as a hex string
stream.Seek(0, SeekOrigin.Begin);

return sha1Str;
}

/// <summary>
/// Compute SHA1 of a file, return the hex content string
/// </summary>
/// <param name="virtualFilePath"></param>
/// <returns></returns>
public static string SHA1Hash(string virtualFilePath)
{
if (FilePathUtility.IsExisted(virtualFilePath))
{
FileStream fs = File.OpenRead(HostingEnvironment.MapPath(virtualFilePath));
string sha1Hash = SHA1Hash(fs);
fs.Close();
return sha1Hash;
}
return "";
}

/// <summary>
/// Compute SHA1 of a HttpPostedFileBase instance, return the hex content string
/// </summary>
/// <param name="fileBase"></param>
/// <returns></returns>
public static string SHA1Hash(HttpPostedFileBase fileBase)
{
return SHA1Hash(fileBase.InputStream);
}

/// <summary>
/// Compute SHA512 of a string (mainly for hashing a password)
/// </summary>
/// <param name="plainText"></param>
/// <returns></returns>
public static string SHA512Hash(string plainText)
{
byte[] data = ASCIIEncoding.ASCII.GetBytes(plainText);
SHA512 sha512 = new SHA512CryptoServiceProvider();
byte[] result = sha512.ComputeHash(data);

return BitConverter.ToString(result).Replace("-", "");
}
}
}