mirror of
https://github.com/CannedNet/CannedNet.git
synced 2026-10-26 23:48:58 -07:00
62 lines
1.7 KiB
C#
62 lines
1.7 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace CannedNet.Services;
|
|
|
|
public static class Signatures
|
|
{
|
|
private static RSA? _rsa;
|
|
private static bool _initialized;
|
|
|
|
public static void Init()
|
|
{
|
|
if (_initialized) return;
|
|
_initialized = true;
|
|
|
|
try
|
|
{
|
|
var pemPath = Path.Combine("Data", "PrivateKey.pem");
|
|
if (!File.Exists(pemPath))
|
|
{
|
|
Console.WriteLine("sigs - creating new sig key");
|
|
Directory.CreateDirectory("Data");
|
|
|
|
using var newKey = RSA.Create(2048);
|
|
|
|
var privatePem = newKey.ExportPkcs8PrivateKeyPem();
|
|
File.WriteAllText(pemPath, privatePem);
|
|
|
|
var publicPem = newKey.ExportSubjectPublicKeyInfoPem();
|
|
File.WriteAllText(
|
|
Path.Combine("Data", "PublicKey.pem"),
|
|
publicPem
|
|
);
|
|
|
|
Console.WriteLine("sigs - keys saved");
|
|
}
|
|
|
|
var pemContent = File.ReadAllText(pemPath);
|
|
_rsa = RSA.Create();
|
|
_rsa.ImportFromPem(pemContent.ToCharArray());
|
|
Console.WriteLine("sigs - key loaded");
|
|
}
|
|
catch (Exception ex)
|
|
{
|
|
Console.WriteLine($"sigs - failed to load key: {ex.Message}");
|
|
}
|
|
}
|
|
|
|
public static RSA? GetRsaInstance()
|
|
{
|
|
if (!_initialized) Init();
|
|
return _rsa;
|
|
}
|
|
|
|
public static string? Sign(byte[] data)
|
|
{
|
|
if (_rsa == null) return null;
|
|
var signatureBytes = _rsa.SignData(data, HashAlgorithmName.SHA1, RSASignaturePadding.Pkcs1);
|
|
return Convert.ToBase64String(signatureBytes);
|
|
}
|
|
}
|