Added password and session creation functions.

This commit is contained in:
2021-01-01 13:29:10 -08:00
parent 26c59555ab
commit 5621418bd7
26 changed files with 232 additions and 56 deletions
+57 -1
View File
@@ -3,8 +3,10 @@ using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Text;
using SecureCore.Services;
using System.Security.Cryptography;
using Microsoft.AspNetCore.Cryptography.KeyDerivation;
namespace SecureCore.Controllers
{
@@ -31,5 +33,59 @@ namespace SecureCore.Controllers
{
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);
}
}
}