Scenario:
Salt and Hash password
Solution:
Encrypt interface
1
2
3
4
5
public interface IPasswordEncrypt
{
string Hash(string password);
(bool IsValid, bool DoResetPassword) Validate(string hash, string password);
}
Using 128 byte salt and 256 byte key and iterations of 10000, create a hashed password. If the iterations has been updated then use the new one to rehash the password.
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
public sealed class PasswordEncrypt : IPasswordEncrypt
{
private int saltSize = 16;
private int keySize = 32;
private int iterations = 10000;
public string Hash(string password)
{
using (var algo = new Rfc2898DeriveBytes(password, saltSize, iterations, HashAlgorithmName.SHA512))
{
var key = Convert.ToBase64String(algo.GetBytes(keySize));
var salt = Convert.ToBase64String(algo.Salt);
return $"{iterations}.{salt}.{key}";
}
}
public (bool IsValid, bool DoResetPassword) Validate(string hash, string password)
{
var handle = hash.Split('.');
var iterationCount = Convert.ToInt32(handle[0]);
var salt = Convert.FromBase64String(handle[1]);
var key = Convert.FromBase64String(handle[2]);
var DoResetPassword = iterationCount != iterations;
using (var algo = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.SHA512))
{
var keyToVerify = algo.GetBytes(keySize);
var valid = keyToVerify.SequenceEqual(key);
return (valid, DoResetPassword);
}
}
}
Encrypt interface
|
Using 128 byte salt and 256 byte key and iterations of 10000, create a hashed password. If the iterations has been updated then use the new one to rehash the password.
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 | public sealed class PasswordEncrypt : IPasswordEncrypt { private int saltSize = 16; private int keySize = 32; private int iterations = 10000; public string Hash(string password) { using (var algo = new Rfc2898DeriveBytes(password, saltSize, iterations, HashAlgorithmName.SHA512)) { var key = Convert.ToBase64String(algo.GetBytes(keySize)); var salt = Convert.ToBase64String(algo.Salt); return $"{iterations}.{salt}.{key}"; } } public (bool IsValid, bool DoResetPassword) Validate(string hash, string password) { var handle = hash.Split('.'); var iterationCount = Convert.ToInt32(handle[0]); var salt = Convert.FromBase64String(handle[1]); var key = Convert.FromBase64String(handle[2]); var DoResetPassword = iterationCount != iterations; using (var algo = new Rfc2898DeriveBytes(password, salt, iterations, HashAlgorithmName.SHA512)) { var keyToVerify = algo.GetBytes(keySize); var valid = keyToVerify.SequenceEqual(key); return (valid, DoResetPassword); } } } |
Encrypt & Decrypt
|
No comments:
Post a Comment