28 lines
817 B
C#
28 lines
817 B
C#
using System;
|
|
using System.Buffers.Text;
|
|
using System.Text;
|
|
|
|
namespace Mirea.Api.Security.Services;
|
|
|
|
public static class GeneratorKey
|
|
{
|
|
public static ReadOnlySpan<byte> GenerateBytes(int size)
|
|
{
|
|
var key = new byte[size];
|
|
using var rng = System.Security.Cryptography.RandomNumberGenerator.Create();
|
|
rng.GetNonZeroBytes(key);
|
|
return key;
|
|
}
|
|
|
|
public static string GenerateBase64(int size) =>
|
|
Convert.ToBase64String(GenerateBytes(size));
|
|
|
|
public static string GenerateString(int size)
|
|
{
|
|
var randomBytes = GenerateBytes(size);
|
|
Span<byte> utf8Bytes = new byte[Base64.GetMaxEncodedToUtf8Length(randomBytes.Length)];
|
|
|
|
Base64.EncodeToUtf8(randomBytes, utf8Bytes, out _, out _);
|
|
return Encoding.UTF8.GetString(utf8Bytes);
|
|
}
|
|
} |