99 lines
2.9 KiB
C#
99 lines
2.9 KiB
C#
using Microsoft.AspNetCore.Http;
|
|
using Microsoft.AspNetCore.Mvc;
|
|
using System;
|
|
using System.Collections.Generic;
|
|
using System.Linq;
|
|
using System.Text;
|
|
using SecureCore.Services;
|
|
using System.Security.Cryptography;
|
|
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
|
|
|
|
namespace SecureCore.Controllers
|
|
{
|
|
[Route("api/[controller]")]
|
|
[ApiController]
|
|
public class EmployeeController : Controller
|
|
{
|
|
private readonly IDataService DataService;
|
|
|
|
|
|
public EmployeeController(IDataService dataService)
|
|
{
|
|
DataService = dataService;
|
|
}
|
|
|
|
[HttpGet]
|
|
public IActionResult Get()
|
|
{
|
|
return Ok(DataService.Get());
|
|
}
|
|
|
|
[HttpGet("{id}", Name = "Get")]
|
|
public IActionResult Get(int id)
|
|
{
|
|
return Ok(DataService.GetById(id));
|
|
}
|
|
|
|
[HttpPost("login")]
|
|
[AcceptVerbs("POST")]
|
|
public IActionResult Login(LoginInfo info)
|
|
{
|
|
var hash = Auth.HashPassword(info.Password);
|
|
var h2 = Auth.HashPassword("Nonesense", "vRWp9TP1nQDLGtDZrd2yuw==");
|
|
|
|
return Ok($"Session Key: {Auth.CreateSessionId()}{Environment.NewLine}Password Hash: {hash.Hash}{Environment.NewLine}Salt: {hash.Salt}{Environment.NewLine}{h2 == "+IGLf8scewY2LOObXqfF5IkIbhcEuPrMFc12d78jH6ZyBEMQI+Z9zixWgkQANeV3VYvURBEXIVI0/TPZrnML3w=="}");
|
|
}
|
|
}
|
|
|
|
public class LoginInfo
|
|
{
|
|
public string UserName { get; set; }
|
|
public string Password { get; set; }
|
|
}
|
|
|
|
public static class Auth
|
|
{
|
|
private static int Iterations { get; set; } = 100000;
|
|
private static KeyDerivationPrf KeyType { get; } = KeyDerivationPrf.HMACSHA512;
|
|
private static int KeySize { get; } = 512 / 8;
|
|
private static int SaltSize { get; } = 128 / 8; //128 bit salt
|
|
private static int SessionKeySize { get; } = 32; //32 bytes
|
|
|
|
public static string CreateSessionId()
|
|
{
|
|
var sessionId = new byte[SessionKeySize];
|
|
|
|
GetRandomBytes(ref sessionId);
|
|
|
|
return Convert.ToBase64String(sessionId);
|
|
}
|
|
|
|
public static (string Hash, string Salt) HashPassword(string password)
|
|
{
|
|
var salt = new byte[SaltSize];
|
|
|
|
GetRandomBytes(ref salt);
|
|
|
|
return (GetPasswordHash(password, salt), Convert.ToBase64String(salt));
|
|
}
|
|
|
|
public static string HashPassword(string password, string hash)
|
|
{
|
|
var salt = Convert.FromBase64String(hash);
|
|
|
|
return GetPasswordHash(password, salt);
|
|
}
|
|
|
|
private static string GetPasswordHash(string password, byte[] salt)
|
|
{
|
|
return Convert.ToBase64String(KeyDerivation.Pbkdf2(password, salt, KeyType, Iterations, KeySize));
|
|
}
|
|
|
|
private static void GetRandomBytes(ref byte[] bytes)
|
|
{
|
|
using var rng = RandomNumberGenerator.Create();
|
|
rng.GetBytes(bytes);
|
|
}
|
|
}
|
|
}
|