using System.Security.Cryptography; using var publicKey = ECDsa.Create();publicKey.ImportFromPem(File.ReadAllText("pub.pem")); // "BEGIN PUBLIC KEY" (SPKI) byte[] message = File.ReadAllBytes("message.txt");byte[] signature = File.ReadAllBytes("sig.der"); // ASN.1 DER, as OpenSSL, Java and Go produce bool valid = publicKey.VerifyData(message, signature, HashAlgorithmName.SHA256, DSASignatureFormat.Rfc3279DerSequence); // the default would be raw r‖sConsole.WriteLine(valid ? "valid" : "INVALID"); // r‖s from a JWS, WebCrypto or a hardware token: .NET's default format, no flag neededbyte[] raw = File.ReadAllBytes("sig.raw"); // 64 bytes on P-256Console.WriteLine(publicKey.VerifyData(message, raw, HashAlgorithmName.SHA256) ? "valid" : "INVALID"); How it works
ImportFromPemreads the PEM label and picks the decoder:PUBLIC KEY(SPKI),PRIVATE KEY(PKCS#8) orEC PRIVATE KEY(SEC 1). The curve comes from the key.VerifyDatahashes the message itself — pass the original bytes and the hash name, not a digest. For a precomputed digest there isVerifyHash.DSASignatureFormat.Rfc3279DerSequenceselects ASN.1 DER. Without it, .NET usesIeeeP1363FixedFieldConcatenation, the 64-byter‖sof JWS and WebCrypto.ECDsaholds native resources:using vardisposes the key handle when the scope ends.
Gotchas
- A signature in the wrong format is not an error in .NET: a DER signature checked with the default format returns
false(the run shows it), exactly like a forged one. When a valid-looking signature fails, check the format first. ImportFromPemtakes the PEM text, not a path.ImportFromPem("pub.pem")throwsNo supported key formats were found— the same error a certificate PEM produces; load certificates withX509CertificateLoaderand callGetECDsaPublicKey().- A file with two keys throws
The input contains multiple keys, and an encrypted private key needsImportFromEncryptedPemwith its password. - Curves are platform-dependent: on Linux, .NET calls OpenSSL and on Windows, CNG.
ECCurve.NamedCurves.nistP256works everywhere, while a friendly name such as"P-256"throwsPlatformNotSupportedExceptionon Linux.