tgstation-server  4.4.0
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.Globalization;
4 using System.Security.Cryptography;
6 
7 namespace Tgstation.Server.Host.Security
8 {
11  {
15  const uint SecureStringLength = 30;
16 
20  readonly IPasswordHasher<User> passwordHasher;
21 
26  public CryptographySuite(IPasswordHasher<User> passwordHasher)
27  {
28  this.passwordHasher = passwordHasher ?? throw new ArgumentNullException(nameof(passwordHasher));
29  }
30 
32  public byte[] GetSecureBytes(uint amount)
33  {
34  using (var rng = new RNGCryptoServiceProvider())
35  {
36  var byt = new byte[amount];
37  rng.GetBytes(byt);
38  return byt;
39  }
40  }
41 
43  public void SetUserPassword(User user, string newPassword, bool newUser)
44  {
45  if (user == null)
46  throw new ArgumentNullException(nameof(user));
47  if (newPassword == null)
48  throw new ArgumentNullException(nameof(newPassword));
49  user.PasswordHash = passwordHasher.HashPassword(user, newPassword);
50  if (!newUser)
51  user.LastPasswordUpdate = DateTimeOffset.Now;
52  }
53 
55  public bool CheckUserPassword(User user, string password)
56  {
57  var result = passwordHasher.VerifyHashedPassword(user, user.PasswordHash, password);
58  switch (result)
59  {
60  case PasswordVerificationResult.Failed:
61  return false;
62  case PasswordVerificationResult.SuccessRehashNeeded:
63  SetUserPassword(user, password, false);
64  break;
65  case PasswordVerificationResult.Success:
66  break;
67  default:
68  throw new InvalidOperationException(String.Format(CultureInfo.InvariantCulture, "Password hasher return unknown PasswordVerificationResult: {0}", result));
69  }
70 
71  return true;
72  }
73 
75  public string GetSecureString() => Convert.ToBase64String(GetSecureBytes(SecureStringLength));
76  }
77 }
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