31 lines
1.1 KiB
C#
31 lines
1.1 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace Authinator.Backend.Utils;
|
|
|
|
public static class CryptoUtils {
|
|
public static string Hmac(this string text, string key) {
|
|
using var hmac = new HMACSHA256(ConvertFromBase64WithUtf8Fallback(key));
|
|
return Convert.ToBase64String(hmac.ComputeHash(Encoding.UTF8.GetBytes(text)));
|
|
}
|
|
|
|
public static string HmacWithMessage(this string text, string key) => text + text.Hmac(key);
|
|
|
|
public static byte[] GetRandomBytes(int size) {
|
|
var random = new Random(Guid.NewGuid().GetHashCode());
|
|
var buffer = new byte[size];
|
|
random.NextBytes(buffer);
|
|
return buffer;
|
|
}
|
|
|
|
public static string GetRandomBytesBase64(int size) => Convert.ToBase64String(GetRandomBytes(size));
|
|
|
|
public static string FixUrlEncodedBase64(this string str) => str.Replace("%2F", "/").Replace("%2f", "/");
|
|
|
|
public static byte[] ConvertFromBase64WithUtf8Fallback(string text) {
|
|
var buffer = new Span<byte>(new byte[text.Length]);
|
|
var success = Convert.TryFromBase64String(text, buffer, out var bytesParsed);
|
|
return success ? buffer[..bytesParsed].ToArray() : Encoding.UTF8.GetBytes(text);
|
|
}
|
|
}
|