private static RegisteredUser RegisterUser(RegistrationRequest regRequest) { RegisteredUser newUserRecord = null; if (FindUserByUsernameAsync(regRequest.Username).GetAwaiter().GetResult() != null) { //BAD! Another conflicting user exists! throw new SecurityException("A user with the same username already exists!"); } var db = DatabaseAccessService.OpenOrCreateDefault(); var registeredUsers = db.GetCollection <RegisteredUser>(DatabaseAccessService.UsersCollectionDatabaseKey); using (var trans = db.BeginTrans()) { //Calculate cryptographic info var cryptoConf = PasswordCryptoConfiguration.CreateDefault(); var pwSalt = AuthCryptoHelper.GetRandomSalt(64); var encryptedPassword = AuthCryptoHelper.CalculateUserPasswordHash(regRequest.Password, pwSalt, cryptoConf); // Create user newUserRecord = new RegisteredUser { Identifier = Guid.NewGuid().ToString(), Username = regRequest.Username, PhoneNumber = regRequest.PhoneNumber, ApiKey = StringUtils.SecureRandomString(40), CryptoSalt = pwSalt, PasswordCryptoConf = cryptoConf, PasswordKey = encryptedPassword, }; // Add the user to the database registeredUsers.Insert(newUserRecord); // Index database registeredUsers.EnsureIndex(x => x.Identifier); registeredUsers.EnsureIndex(x => x.ApiKey); registeredUsers.EnsureIndex(x => x.Username); trans.Commit(); } return(newUserRecord); }
public static byte[] CalculateUserPasswordHash(string password, byte[] salt, PasswordCryptoConfiguration cryptoConf) { var passwordBytes = Encoding.UTF8.GetBytes(password); return CalculatePasswordHash(passwordBytes, salt, cryptoConf.Iterations, cryptoConf.Length); }
public static byte[] CalculateUserPasswordHash(string password, byte[] salt, PasswordCryptoConfiguration cryptoConf) { var passwordBytes = Encoding.UTF8.GetBytes(password); return(CalculatePasswordHash(passwordBytes, salt, cryptoConf.Iterations, cryptoConf.Length)); }