-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSecurity.cs
More file actions
59 lines (50 loc) · 2.09 KB
/
Copy pathSecurity.cs
File metadata and controls
59 lines (50 loc) · 2.09 KB
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
using Microsoft.AspNetCore.DataProtection;
public interface ICipherService
{
string Encrypt(string cipherText);
string Decrypt(string cipherText);
}
public class Security : ICipherService
{
//Method 1 Two Way-----------------------------------------------------------------------
private readonly IDataProtectionProvider _dataProtectionProvider;
private const string Key = "cut-the-night-with-the-light";
public Security(IDataProtectionProvider dataProtectionProvider)
{
_dataProtectionProvider = dataProtectionProvider;
}
public string Encrypt(string input)
{
var protector = _dataProtectionProvider.CreateProtector(Key);
return protector.Protect(input);
}
public string Decrypt(string input)
{
var protector = _dataProtectionProvider.CreateProtector(Key);
return protector.Unprotect(input);
}
//Method 2 One Way-----------------------------------------------------------------------
public string HashCreate(string value, string salt)
{
var valueBytes = Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivation.Pbkdf2(
password: value,
salt: System.Text.Encoding.UTF8.GetBytes(salt),
prf: Microsoft.AspNetCore.Cryptography.KeyDerivation.KeyDerivationPrf.HMACSHA512,
iterationCount: 10000,
numBytesRequested: 256 / 8);
//return System.Convert.ToBase64String(valueBytes);
return System.Convert.ToBase64String(valueBytes) + "æ" + salt;
}
public bool ValidateHash(string value, string salt, string hash)
//=> HashCreate(value, salt) == hash;
=> HashCreate(value, salt).Split('æ')[0] == hash;
public string HashCreate()
{
byte[] randomBytes = new byte[128 / 8];
using (var generator = System.Security.Cryptography.RandomNumberGenerator.Create())
{
generator.GetBytes(randomBytes);
return System.Convert.ToBase64String(randomBytes);
}
}
}