92 lines
2.4 KiB
C#
92 lines
2.4 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, out string salt);
|
|
return Ok($"Session Key: {Auth.CreateSessionId()}{Environment.NewLine}Password Hash: {hash}{Environment.NewLine}Salt: {salt}{Environment.NewLine}");
|
|
}
|
|
}
|
|
|
|
public class LoginInfo
|
|
{
|
|
public string UserName { get; set; }
|
|
public string Password { get; set; }
|
|
}
|
|
|
|
public static class Auth
|
|
{
|
|
public static string CreateSessionId()
|
|
{
|
|
var sessionId = new byte[32];
|
|
|
|
GetRandomBytes(ref sessionId);
|
|
|
|
return ConvertToHex(sessionId);
|
|
}
|
|
|
|
public static string HashPassword(string password, out string saltString)
|
|
{
|
|
//Generate a 128 bit salt
|
|
var salt = new byte[128 / 8];
|
|
|
|
GetRandomBytes(ref salt);
|
|
|
|
saltString = ConvertToHex(salt);
|
|
|
|
return Convert.ToBase64String(KeyDerivation.Pbkdf2(password, salt, KeyDerivationPrf.HMACSHA512, 50000, 512 / 8));
|
|
}
|
|
|
|
private static string ConvertToHex(byte[] bytes)
|
|
{
|
|
var stringBuilder = new StringBuilder();
|
|
|
|
foreach (var b in bytes)
|
|
stringBuilder.AppendFormat("{0:x2}", b);
|
|
|
|
return stringBuilder.ToString();
|
|
}
|
|
|
|
private static void GetRandomBytes(ref byte[] bytes)
|
|
{
|
|
using(var rng = RandomNumberGenerator.Create())
|
|
rng.GetBytes(bytes);
|
|
}
|
|
}
|
|
}
|