Files
Akari.Prototype/Akari.Prototype.Server/Utils/Security.cs
2021-06-05 10:48:33 +02:00

80 lines
2.6 KiB
C#

using Isopoh.Cryptography.Argon2;
using Isopoh.Cryptography.SecureArray;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
namespace Akari.Prototype.Server.Utils
{
public static class Security
{
public const int DefaultHashLength = 32;
public const int DefaultSaltLength = 12;
public static string NewArgon2idHash(byte[] password, int hashLength = DefaultHashLength, int saltLength = DefaultSaltLength, bool clear = false, int? threads = null)
{
int t = threads ?? Environment.ProcessorCount / 2;
if (t < 1)
{
t = 1;
}
var salt = new byte[saltLength];
RandomNumberGenerator.Fill(salt);
var config = new Argon2Config()
{
HashLength = hashLength,
Password = password,
Salt = salt,
Lanes = t,
Threads = t,
ClearPassword = clear,
ClearSecret = clear,
Type = Argon2Type.HybridAddressing,
Version = Argon2Version.Nineteen
};
return Argon2.Hash(config);
}
public static string NewArgon2idHash(string password, int hashLength = DefaultHashLength, int saltLength = DefaultSaltLength, bool clear = false, int? threads = null)
{
return NewArgon2idHash(Encoding.UTF8.GetBytes(password), hashLength, saltLength, clear, threads);
}
public static SecureArray<byte> Argon2idDeriveBytes(byte[] password, byte[] salt, int length, bool clear = false, int? threads = null)
{
int t = threads ?? Environment.ProcessorCount / 2;
if (t < 1)
{
t = 1;
}
var config = new Argon2Config()
{
HashLength = length,
Password = password,
Salt = salt,
Lanes = t,
Threads = t,
ClearPassword = clear,
ClearSecret = clear,
Type = Argon2Type.HybridAddressing,
Version = Argon2Version.Nineteen
};
return new Argon2(config).Hash();
}
public static SecureArray<byte> Argon2idDeriveBytes(string password, string salt, int length, bool clear = false, int? threads = null)
{
return Argon2idDeriveBytes(Encoding.UTF8.GetBytes(password), Encoding.UTF8.GetBytes(salt), length, clear, threads);
}
}
}