60 lines
1.6 KiB
C#
60 lines
1.6 KiB
C#
using System.Security.Cryptography;
|
|
using System.Text;
|
|
|
|
namespace IronLicensing.Client;
|
|
|
|
/// <summary>
|
|
/// RSA signature verifier for offline license validation
|
|
/// </summary>
|
|
public class RsaSignatureVerifier : ISignatureVerifier
|
|
{
|
|
public bool Verify(string publicKeyPem, string data, string signature)
|
|
{
|
|
if (string.IsNullOrEmpty(publicKeyPem) ||
|
|
string.IsNullOrEmpty(data) ||
|
|
string.IsNullOrEmpty(signature))
|
|
{
|
|
return false;
|
|
}
|
|
|
|
try
|
|
{
|
|
using var rsa = RSA.Create();
|
|
|
|
// Import the public key
|
|
var keyBytes = ParsePemPublicKey(publicKeyPem);
|
|
rsa.ImportSubjectPublicKeyInfo(keyBytes, out _);
|
|
|
|
// Verify the signature
|
|
var dataBytes = Encoding.UTF8.GetBytes(data);
|
|
var signatureBytes = Convert.FromBase64String(signature);
|
|
|
|
return rsa.VerifyData(
|
|
dataBytes,
|
|
signatureBytes,
|
|
HashAlgorithmName.SHA256,
|
|
RSASignaturePadding.Pkcs1);
|
|
}
|
|
catch
|
|
{
|
|
return false;
|
|
}
|
|
}
|
|
|
|
private static byte[] ParsePemPublicKey(string pem)
|
|
{
|
|
// Remove PEM headers/footers and whitespace
|
|
var base64 = pem
|
|
.Replace("-----BEGIN PUBLIC KEY-----", "")
|
|
.Replace("-----END PUBLIC KEY-----", "")
|
|
.Replace("-----BEGIN RSA PUBLIC KEY-----", "")
|
|
.Replace("-----END RSA PUBLIC KEY-----", "")
|
|
.Replace("\n", "")
|
|
.Replace("\r", "")
|
|
.Replace(" ", "")
|
|
.Trim();
|
|
|
|
return Convert.FromBase64String(base64);
|
|
}
|
|
}
|