For a project I’m working on, I need to verify signatures of data records. We have a legacy project that makes use of an imported DLL of which the source code is no longer available. We are now updating the project, and would like to also modernize the Signature verification.
The supported signature-methods are RSA 1024, ECDSA 192, ECDSA 224 and ECDSA 256.
As example data I have the following public key: MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEwhDZNphi4J1EiBCQwZ1WBCYbnf9Ne6UqPuLLGJPTj5++io9pxT3McYgFFFPb7HdfJCrPsKmTVwlw9Z1RpQru6g==
, the following signature:
BEgwRgIhAPqcBPjRROiwTBUFTF50iDXSBn+e71c3fIj9kgfxUbAZAiEAR6KM+u8D6TWtaKVdH8EjLxWJf4Vm/u2Z5YptKEjTgHs=
, and the following data that should be verified to: ;"4399901879126";"302.1302.006";"4005249001296";"20240627151654328";
I have verified with the legacy tool that these values should give a positive result.
I’ve tried some of the following, but no dice:
private static void Main(string[] args)
{
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
var publicKey = "MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEwhDZNphi4J1EiBCQwZ1WBCYbnf9Ne6UqPuLLGJPTj5++io9pxT3McYgFFFPb7HdfJCrPsKmTVwlw9Z1RpQru6g==";
var signature = "BEgwRgIhAPqcBPjRROiwTBUFTF50iDXSBn+e71c3fIj9kgfxUbAZAiEAR6KM+u8D6TWtaKVdH8EjLxWJf4Vm/u2Z5YptKEjTgHs=";
var data = ";"4399901879126";"302.1302.006";"4005249001296";"20240627151654328";";
var value = VerifyEcdsaSignature(Convert.FromBase64String(publicKey), Encoding.Latin1.GetBytes(data), Convert.FromBase64String(signature));
Console.WriteLine(value);
Console.ReadLine();
}
public static bool VerifySignature(byte[] key, byte[] data, byte[] signature)
{
var publicKey = PublicKey.CreateFromSubjectPublicKeyInfo(key, out _);
var ecdsa = publicKey.GetECDsaPublicKey() ?? ECDsa.Create();
return ecdsa.VerifyData(data, signature, HashAlgorithmName.SHA256);
}
public static byte[] GetSha224Bytes(byte[] data)
{
return Sha224.Create().ComputeHash(data);
}
public static byte[] GetSha256Bytes(byte[] data)
{
return SHA256.HashData(data);
}
private static bool VerifyEcdsaSignature(byte[] key, byte[] bytesData, byte[] bytesSignature)
{
var publicKey = PublicKey.CreateFromSubjectPublicKeyInfo(key, out _);
var ecdsa = publicKey.GetECDsaPublicKey();
var pubKey = DotNetUtilities.GetECDsaPublicKey(ecdsa);
ISigner signer = SignerUtilities.GetSigner("SHA-256withECDSA");
signer.Init(false, pubKey);
signer.BlockUpdate(bytesData);
return signer.VerifySignature(bytesSignature);
}