tgstation-server 6.12.0
The /tg/station 13 server suite
Loading...
Searching...
No Matches
CryptographySuite.cs
Go to the documentation of this file.
1using System;
2using System.Globalization;
3using System.Security.Cryptography;
4
5using Microsoft.AspNetCore.Identity;
6
8
10{
13 {
17 const uint SecureStringLength = 30;
18
22 readonly IPasswordHasher<User> passwordHasher;
23
28 public CryptographySuite(IPasswordHasher<User> passwordHasher)
29 {
30 this.passwordHasher = passwordHasher ?? throw new ArgumentNullException(nameof(passwordHasher));
31 }
32
34 public byte[] GetSecureBytes(uint amount)
35 {
36 using var rng = RandomNumberGenerator.Create(); // uses RNGCryptoServiceProvider under the hood https://khalidabuhakmeh.com/creating-random-numbers-with-dotnet-core
37 var byt = new byte[amount];
38 rng.GetBytes(byt);
39 return byt;
40 }
41
43 public void SetUserPassword(User user, string newPassword, bool newUser)
44 {
45 ArgumentNullException.ThrowIfNull(user);
46 ArgumentNullException.ThrowIfNull(newPassword);
47 user.PasswordHash = passwordHasher.HashPassword(user, newPassword);
48 if (!newUser)
49 user.LastPasswordUpdate = DateTimeOffset.UtcNow;
50 }
51
53 public bool CheckUserPassword(User user, string password)
54 {
55 ArgumentNullException.ThrowIfNull(user);
56 ArgumentNullException.ThrowIfNull(password);
57
58 if (user.PasswordHash == null)
59 throw new ArgumentException("user must have PasswordHash!", nameof(user));
60
61 var result = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password);
62 switch (result)
63 {
64 case PasswordVerificationResult.Failed:
65 return false;
66 case PasswordVerificationResult.SuccessRehashNeeded:
67 SetUserPassword(user, password, false);
68 break;
69 case PasswordVerificationResult.Success:
70 break;
71 default:
72 throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Password hasher return unknown PasswordVerificationResult: {0}", result));
73 }
74
75 return true;
76 }
77
79 public string GetSecureString() => Convert.ToBase64String(GetSecureBytes(SecureStringLength));
80 }
81}
string? PasswordHash
The hash of the user's password.
Definition User.cs:26
bool CheckUserPassword(User user, string password)
Checks a given password matches a given user 's User.PasswordHash. This may result in User....
void SetUserPassword(User user, string newPassword, bool newUser)
Sets a User.PasswordHash for a given user .
string GetSecureString()
Generates a 40-length secure ascii string.A 40-length secure ascii string.
CryptographySuite(IPasswordHasher< User > passwordHasher)
Initializes a new instance of the CryptographySuite class.
const uint SecureStringLength
Length in bytes of generated base64 secure string.
byte[] GetSecureBytes(uint amount)
Generates a secure set of bytes.A secure set of bytes.
readonly IPasswordHasher< User > passwordHasher
The IPasswordHasher<TUser> for the CryptographySuite.
Contains various cryptographic functions.