Skip to content

Instantly share code, notes, and snippets.

@peteraritchie
Last active March 3, 2026 22:14
Show Gist options
  • Select an option

  • Save peteraritchie/db2e88e644b2344521e58380a3838441 to your computer and use it in GitHub Desktop.

Select an option

Save peteraritchie/db2e88e644b2344521e58380a3838441 to your computer and use it in GitHub Desktop.
Example code that models signing data then verifying data against the signature.
using System.Security.Cryptography;
using System.Security.Cryptography.X509Certificates;
namespace ProofsOfConcept.Tests;
public class SignDataAndVerifySignatureShould
{
private readonly byte[] generatedPfxBytes = CreateX509CertificatePfxBytes(PfxPassword);
private const string PfxPassword = "StrongPassword123!";
// Create cert
[Fact]
void SignAndVerifyDataCorrectly()
{
var data = "Text to be signed."u8.ToArray();
// load PFX
byte[] pfxBytes = LoadPfx();
// deserialize cert from pfx
X509Certificate2 loadedCert = new(pfxBytes, PfxPassword, X509KeyStorageFlags.MachineKeySet);
byte[] signature;
#region sign data
using (RSA? rsaPrivate = loadedCert.GetRSAPrivateKey())
{
if (rsaPrivate == null) throw new InvalidOperationException();
signature = rsaPrivate.SignData(data, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
#endregion
#region verify signature against data
bool isVerified = false;
using (RSA? rsaPublic = loadedCert.GetRSAPublicKey())
{
if (rsaPublic == null) throw new InvalidOperationException();
isVerified = rsaPublic.VerifyData(data, signature, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
}
#endregion
Assert.True(isVerified);
return;
byte[] LoadPfx()
{
return generatedPfxBytes;
}
}
private static byte[] CreateX509CertificatePfxBytes(string pfxPassword)
{
X509Certificate2 cert = CreateSelfSignedCertificate("TestCert");
// Export to PFX
return cert.Export(X509ContentType.Pfx, pfxPassword);
}
private static X509Certificate2 CreateSelfSignedCertificate(string subjectName)
{
using RSA rsa = RSA.Create(3072);
var request = new CertificateRequest($"CN={subjectName}", rsa, HashAlgorithmName.SHA256, RSASignaturePadding.Pkcs1);
// Create the certificate (valid for 10 years)
return request.CreateSelfSigned(DateTimeOffset.UtcNow.AddDays(-1), DateTimeOffset.UtcNow.AddYears(10));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment