This repository has been archived by the owner on Dec 13, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4k
/
HashExtensions.cs
71 lines (61 loc) · 2.01 KB
/
HashExtensions.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
59
60
61
62
63
64
65
66
67
68
69
70
71
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using IdentityServer4.Extensions;
using System;
using System.Security.Cryptography;
using System.Text;
namespace IdentityServer4.Models
{
/// <summary>
/// Extension methods for hashing strings
/// </summary>
public static class HashExtensions
{
/// <summary>
/// Creates a SHA256 hash of the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>A hash</returns>
public static string Sha256(this string input)
{
if (input.IsMissing()) return string.Empty;
using (var sha = SHA256.Create())
{
var bytes = Encoding.UTF8.GetBytes(input);
var hash = sha.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
}
/// <summary>
/// Creates a SHA256 hash of the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>A hash.</returns>
public static byte[] Sha256(this byte[] input)
{
if (input == null)
{
return null;
}
using (var sha = SHA256.Create())
{
return sha.ComputeHash(input);
}
}
/// <summary>
/// Creates a SHA512 hash of the specified input.
/// </summary>
/// <param name="input">The input.</param>
/// <returns>A hash</returns>
public static string Sha512(this string input)
{
if (input.IsMissing()) return string.Empty;
using (var sha = SHA512.Create())
{
var bytes = Encoding.UTF8.GetBytes(input);
var hash = sha.ComputeHash(bytes);
return Convert.ToBase64String(hash);
}
}
}
}