This commit is contained in:
Bartosz Chyży 2020-06-24 00:57:30 +02:00
parent b85b295cb5
commit ea202d0a8e

View File

@ -10,6 +10,7 @@ namespace SafeMessageStorage.Services.AuthorizationService
public class AuthorizationService : IAuthorizationService
{
private readonly string _passwordKey = "86d9ee32-c00e-4b18-bb1b-a4f7d9e23ec9";
private readonly string _saltKey = "d18930d9-6aae-4e71-a700-e5d292a8724b";
private readonly IHashProvider _hashProvider;
public AuthorizationService(IHashProvider hashProvider)
@ -24,13 +25,14 @@ namespace SafeMessageStorage.Services.AuthorizationService
public bool IsPasswordSet => Xamarin.Essentials.SecureStorage.GetAsync(_passwordKey).Result != null;
public async Task<bool> AuthorizeAsync(string password)
{
//Xamarin.Essentials.SecureStorage.RemoveAll();
if (string.IsNullOrWhiteSpace(password))
return false;
var keyChainPassword = await Xamarin.Essentials.SecureStorage.GetAsync(_passwordKey);
var hash = _hashProvider.GetHashString(password);
var hash = await GetHashWithSalt(password);
var result = keyChainPassword?.Equals(hash) ?? false;
IsAuthorized = result;
AuthorizedUserHash = IsAuthorized ? keyChainPassword : null;
AuthorizedUserHash = IsAuthorized ? _hashProvider.GetHashString(password) : null;
return result;
}
@ -44,15 +46,32 @@ namespace SafeMessageStorage.Services.AuthorizationService
public async Task<bool> ChangePasswordAsync(string currentPassword, string newPassword)
{
var keyChainPassword = await Xamarin.Essentials.SecureStorage.GetAsync(_passwordKey);
var passwordMatch = keyChainPassword?.Equals(_hashProvider.GetHashString(currentPassword)) ?? true;
var passwordMatch = keyChainPassword?.Equals(await GetHashWithSalt(currentPassword)) ?? true;
if (!passwordMatch)
return false;
var passwordHash = _hashProvider.GetHashString(newPassword);
AuthorizedUserHash = passwordHash;
var passwordHash = await GetHashWithSalt(newPassword);
AuthorizedUserHash = _hashProvider.GetHashString(newPassword);
await Xamarin.Essentials.SecureStorage.SetAsync(_passwordKey, passwordHash);
return true;
}
private async Task<string> GetHashWithSalt(string password)
{
return _hashProvider.GetHashString(password + await GetSalt());
}
private async Task<string> GetSalt()
{
var salt = await Xamarin.Essentials.SecureStorage.GetAsync(_saltKey);
if (salt == null)
{
salt = Guid.NewGuid().ToString();
await Xamarin.Essentials.SecureStorage.SetAsync(_saltKey, salt);
}
return salt;
}
}
}