-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathPBKDF2.cs
243 lines (195 loc) · 8.99 KB
/
PBKDF2.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
using System;
using System.Security.Cryptography;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
namespace PBKDF2
{
[ProgId("ClassicASP.PBKDF2")]
[ClassInterface(ClassInterfaceType.AutoDual)]
[Guid("92BF1B12-81B1-476F-A787-A78C393001A7")]
[ComVisible(true)]
public class PBKDF2
{
[ComVisible(true)]
/// <summary>
/// Provides helper methods for hashing/salting and verifying passwords.
/// </summary>
/* =======================
* HASHED PASSWORD FORMATS
* =======================
*
* Version 3:
* PBKDF2 with HMAC-SHA256, 128-bit salt, 256-bit subkey, 10000 iterations.
* Format: { 0x01, prf (UInt32), iter count (UInt32), salt length (UInt32), salt, subkey }
* (All UInt32s are stored big-endian.)
*/
private const int PBKDF2IterCount = 10000;
private const int PBKDF2SubkeyLength = 256 / 8; // 256 bits
private const int SaltSize = 128 / 8; // 128 bits
/// <summary>
/// Returns a hashed representation of the specified <paramref name="password"/>.
/// </summary>
/// <param name="password">The password to generate a hash value for.</param>
/// <returns>The hash value for <paramref name="password" /> as a base-64-encoded string.</returns>
/// <exception cref="System.ArgumentNullException"><paramref name="password" /> is null.</exception>
public string Hash(string password, int iterations = PBKDF2IterCount, string hAlg = "sha1", int saltBytes = SaltSize, int keyLength = PBKDF2SubkeyLength)
{
if (password == null)
{
throw new ArgumentNullException(nameof(password));
}
return HashPasswordInternal(password, iterations, hAlg, saltBytes, keyLength);
}
/// <summary>
/// Determines whether the specified RFC 2898 hash and password are a cryptographic match.
/// </summary>
/// <param name="hashedPassword">The previously-computed RFC 2898 hash value as a base-64-encoded string.</param>
/// <param name="password">The plaintext password to cryptographically compare with hashedPassword.</param>
/// <returns>true if the hash value is a cryptographic match for the password; otherwise, false.</returns>
/// <remarks>
/// <paramref name="hashedPassword" /> must be of the format of HashPassword (salt + Hash(salt+input).
/// </remarks>
/// <exception cref="System.ArgumentNullException">
/// <paramref name="hashedPassword" /> or <paramref name="password" /> is null.
/// </exception>
public bool Verify(string password, string hashedPassword)
{
if (hashedPassword == null)
{
throw new ArgumentNullException(nameof(hashedPassword));
}
if (password == null)
{
throw new ArgumentNullException(nameof(password));
}
return VerifyHashedPasswordInternal(hashedPassword, password);
}
private static readonly RandomNumberGenerator _rng = RandomNumberGenerator.Create();
private static string HashPasswordInternal(string password, int iterations, string HMACalg, int saltBytes, int keyLength)
{
var theHMAC = KeyDerivationPrf.HMACSHA1;
string selectedAlg = "sha1";
if (HMACalg.Contains("sha2")){
theHMAC = KeyDerivationPrf.HMACSHA256;
selectedAlg = "sha256";
}
else if (HMACalg.Contains("sha5")) {
theHMAC = KeyDerivationPrf.HMACSHA512;
selectedAlg = "sha512";
}
var bytes = HashPasswordInternal(password, theHMAC, iterations, saltBytes, keyLength);
return Convert.ToBase64String(bytes);
}
private static byte[] HashPasswordInternal(
string password,
KeyDerivationPrf prf,
int iterCount,
int saltSize,
int numBytesRequested)
{
// Produce a version 3 (see comment above) text hash.
var salt = new byte[saltSize];
_rng.GetBytes(salt);
var subkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, numBytesRequested);
var outputBytes = new byte[13 + salt.Length + subkey.Length];
// Write format marker.
outputBytes[0] = 0x01;
// Write hashing algorithm version.
WriteNetworkByteOrder(outputBytes, 1, (uint)prf);
// Write iteration count of the algorithm.
WriteNetworkByteOrder(outputBytes, 5, (uint)iterCount);
// Write size of the salt.
WriteNetworkByteOrder(outputBytes, 9, (uint)saltSize);
// Write the salt.
Buffer.BlockCopy(salt, 0, outputBytes, 13, salt.Length);
// Write the subkey.
Buffer.BlockCopy(subkey, 0, outputBytes, 13 + saltSize, subkey.Length);
return outputBytes;
}
private static bool VerifyHashedPasswordInternal(string hashedPassword, string password)
{
var decodedHashedPassword = Convert.FromBase64String(hashedPassword);
if (decodedHashedPassword.Length == 0)
{
return false;
}
try
{
// Verify hashing format.
if (decodedHashedPassword[0] != 0x01)
{
// Unknown format header.
return false;
}
// Read hashing algorithm version.
var prf = (KeyDerivationPrf)ReadNetworkByteOrder(decodedHashedPassword, 1);
// Read iteration count of the algorithm.
var iterCount = (int)ReadNetworkByteOrder(decodedHashedPassword, 5);
// Read size of the salt.
var saltLength = (int)ReadNetworkByteOrder(decodedHashedPassword, 9);
// Verify the salt size: >= 128 bits.
if (saltLength < 128 / 8)
{
return false;
}
// Read the salt.
var salt = new byte[saltLength];
Buffer.BlockCopy(decodedHashedPassword, 13, salt, 0, salt.Length);
// Verify the subkey length >= 128 bits.
var subkeyLength = decodedHashedPassword.Length - 13 - salt.Length;
if (subkeyLength < 128 / 8)
{
return false;
}
// Read the subkey.
var expectedSubkey = new byte[subkeyLength];
Buffer.BlockCopy(decodedHashedPassword, 13 + salt.Length, expectedSubkey, 0, expectedSubkey.Length);
// Hash the given password and verify it against the expected subkey.
var actualSubkey = KeyDerivation.Pbkdf2(password, salt, prf, iterCount, subkeyLength);
return ByteArraysEqual(actualSubkey, expectedSubkey);
}
catch
{
// This should never occur except in the case of a malformed payload, where
// we might go off the end of the array. Regardless, a malformed payload
// implies verification failed.
return false;
}
}
private static uint ReadNetworkByteOrder(byte[] buffer, int offset)
{
return ((uint)(buffer[offset + 0]) << 24)
| ((uint)(buffer[offset + 1]) << 16)
| ((uint)(buffer[offset + 2]) << 8)
| ((uint)(buffer[offset + 3]));
}
private static void WriteNetworkByteOrder(byte[] buffer, int offset, uint value)
{
buffer[offset + 0] = (byte)(value >> 24);
buffer[offset + 1] = (byte)(value >> 16);
buffer[offset + 2] = (byte)(value >> 8);
buffer[offset + 3] = (byte)(value >> 0);
}
// Compares two byte arrays for equality.
// The method is specifically written so that the loop is not optimized.
[MethodImpl(MethodImplOptions.NoInlining | MethodImplOptions.NoOptimization)]
private static bool ByteArraysEqual(byte[] a, byte[] b)
{
if (ReferenceEquals(a, b))
{
return true;
}
if (a == null || b == null || a.Length != b.Length)
{
return false;
}
var areSame = true;
for (var i = 0; i < a.Length; i++)
{
areSame &= (a[i] == b[i]);
}
return areSame;
}
}
}