using Microsoft.AspNetCore.Cryptography.KeyDerivation;
using System.Collections.ObjectModel;
using System.Security.Cryptography;

//-- The example by folow microsoft example: ---------------------------------------------------
//-- https://docs.asp.net/en/latest/security/data-protection/consumer-apis/password-hashing.html
//----------------------------------------------------------------------------------------------

namespace Knoks.Framework.Cryptography
{
    public class PasswordProcess : IPasswordProcess
    {
        public readonly IPasswordOptions PasswordOptions;

        public PasswordProcess(IPasswordOptions passwordOptions)
        {
            PasswordOptions = passwordOptions;
        }

        public IPasswordResult Generate(string password, byte[] salt)
        {
            return new PasswordResult
            (
                PasswordOptions.Version,
                KeyDerivation.Pbkdf2(
                        password: password + PasswordOptions.Peper,
                        salt: salt,
                        prf: PasswordOptions.Prf,
                        iterationCount: PasswordOptions.IterationCount,
                        numBytesRequested: PasswordOptions.NumBytesRequested
                    ),
                salt
            );
        }

        public IPasswordResult Generate(string password)
        {
            var salt = new byte[128 / 8];
            using (var rng = RandomNumberGenerator.Create())
            {
                rng.GetBytes(salt);
            }

            return Generate(password, salt);
        }
    }
}
