public async Task Post(UserModel userModel, string creditCard) { var user = await _userRepository.Get(userModel.Username); if (user != null) { var salt = PasswordEncryptor.CreateSalt(ChaCha20Poly1305.ChaCha20Poly1305.NonceSize); var key = _keyVault.Get(); var hashedCreditCard = PasswordEncryptor.EncryptSensitiveData(creditCard, salt, key); user.CreditCardHash = hashedCreditCard; user.CreditCardSalt = HexToBytesConverter.BytesArrayToHexString(salt); await _userRepository.Update(user); } }
public async Task <string> Get(string email) { var user = await _userRepository.Get(email); if (user != null) { var salt = HexToBytesConverter.HexStringToBytesArray(user.CreditCardSalt); var key = _keyVault.Get(); var hashedCreditCard = PasswordEncryptor.DecryptSensitiveData(user.CreditCardHash, salt, key); var creditCard = HexToBytesConverter.HexStringToBytesArray(hashedCreditCard); return(Encoding.Default.GetString(creditCard)); } throw new Exception("Decryption failed"); }
public static string DecryptSensitiveData(string encryptedData, byte[] salt, byte[] keyBytesArray) { var dataBytesArray = HexToBytesConverter.HexStringToBytesArray(encryptedData); var key = Key.Import(AeadAlgorithm.ChaCha20Poly1305, keyBytesArray, KeyBlobFormat.NSecSymmetricKey); var nonce = new Nonce(salt, 0); var decryptedData = AeadAlgorithm.ChaCha20Poly1305.Decrypt(key, nonce, null, dataBytesArray, out var plaintext); if (decryptedData) { var hashedEncryptedData = HexToBytesConverter.BytesArrayToHexString(plaintext); return(hashedEncryptedData); } throw new Exception("Decryption failed"); }
public async Task <bool> Register(UserModel userModel) { var salt = PasswordEncryptor.CreateSalt(SaltLength); var hashedPassword = PasswordEncryptor.HashPassword(userModel.Password, salt); var user = new User { Id = Guid.NewGuid(), Email = userModel.Username, PasswordHash = hashedPassword, PasswordSalt = HexToBytesConverter.BytesArrayToHexString(salt) }; await _userRepository.Add(user); return(true); }
public async Task <UserModel> Login(UserModel userModel) { var userEntity = await _userRepository.Get(userModel.Username); if (userEntity != null) { var salt = HexToBytesConverter.HexStringToBytesArray(userEntity.PasswordSalt); var hashedPassword = PasswordEncryptor.HashPassword(userModel.Password, salt); if (hashedPassword == userEntity.PasswordHash) { userModel.Token = "Fake-Token"; return(userModel); } } throw new Exception("Login failed"); }
public static string EncryptSensitiveData(string data, byte[] salt, byte[] keyBytesArray) { try { var dataBytesArray = Encoding.Default.GetBytes(data); var key = Key.Import(AeadAlgorithm.ChaCha20Poly1305, keyBytesArray, KeyBlobFormat.NSecSymmetricKey); var nonce = new Nonce(salt, 0); var encryptedData = AeadAlgorithm.ChaCha20Poly1305.Encrypt(key, nonce, null, dataBytesArray); var hashedEncryptedData = HexToBytesConverter.BytesArrayToHexString(encryptedData); return(hashedEncryptedData); } catch (Exception e) { Console.WriteLine(e); throw; } }