tgstation-server
The /tg/station 13 server suite
CryptographySuite.cs
Go to the documentation of this file.
1 using Microsoft.AspNetCore.Identity;
2 using System;
3 using System.Security.Cryptography;
5 
6 namespace Tgstation.Server.Host.Security
7 {
10  {
14  const uint SecureStringLength = 30;
15 
19  readonly IPasswordHasher<User> passwordHasher;
20 
25  public CryptographySuite(IPasswordHasher<User> passwordHasher)
26  {
27  this.passwordHasher = passwordHasher ?? throw new ArgumentNullException(nameof(passwordHasher));
28  }
29 
31  public byte[] GetSecureBytes(uint amount)
32  {
33  using (var rng = new RNGCryptoServiceProvider())
34  {
35  var byt = new byte[amount];
36  rng.GetBytes(byt);
37  return byt;
38  }
39  }
40 
42  public void SetUserPassword(User user, string newPassword, bool newUser)
43  {
44  if (user == null)
45  throw new ArgumentNullException(nameof(user));
46  if (newPassword == null)
47  throw new ArgumentNullException(nameof(newPassword));
48  user.PasswordHash = passwordHasher.HashPassword(user, newPassword);
49  if (!newUser)
50  user.LastPasswordUpdate = DateTimeOffset.Now;
51  }
52 
54  public bool CheckUserPassword(User user, string password)
55  {
56  switch (passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password))
57  {
58  case PasswordVerificationResult.Failed:
59  return false;
60  case PasswordVerificationResult.SuccessRehashNeeded:
61  SetUserPassword(user, password, false);
62  break;
63  }
64  return true;
65  }
66 
68  public string GetSecureString() => Convert.ToBase64String(GetSecureBytes(SecureStringLength));
69  }
70 }
string PasswordHash
The hash of the user&#39;s password
Definition: User.cs:13
readonly IPasswordHasher< User > passwordHasher
The IPasswordHasher<TUser> for the CryptographySuite
DateTimeOffset LastPasswordUpdate
When PasswordHash was last changed
Definition: User.cs:29
void SetUserPassword(User user, string newPassword, bool newUser)
Sets a User.PasswordHash for a given user
Contains various cryptographic functions
bool CheckUserPassword(User user, string password)
Checks a given password matches a given user &#39;s User.PasswordHash. This may result in User...
byte[] GetSecureBytes(uint amount)
Generates a secure set of bytes
CryptographySuite(IPasswordHasher< User > passwordHasher)
Construct a CryptographySuite