Sign XML with ECDsa and SHA256 in .Net

2.4k views Asked by At

I'm trying to use SignedXml in .Net with ECDsa (ECDsaCng) and SHA256 and I'm getting an "CryptographicException" with message "Failed to create signing key.". Does someone knows how to achieve that goal or if I should know relevant information about .net support for ecdsa? thank you in advance.

public XmlDocument SignXml(XmlDocument xmlDoc)
    {
        CngKey cngKey = CngKey.Create(CngAlgorithm.ECDsaP256);
        ecDsaCng = new ECDsaCng(cngKey);
        ecDsaCng.HashAlgorithm = CngAlgorithm.ECDsaP256;
        ecDsaCng.KeySize = 256;

        xmlDoc.PreserveWhitespace = true;

        SignedXml signedXml = new SignedXml(xmlDoc);
        signedXml.SigningKey = ecDsaCng;

        Reference reference = new Reference();
        reference.Uri = "";
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(env);
        signedXml.AddReference(reference);

        signedXml.ComputeSignature();

        XmlElement xmlDigitalSignature = signedXml.GetXml();
        xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));
        return xmlDoc;
    }

Error appears in "signedXml.ComputeSignature();" method call.

1

There are 1 answers

5
dna On BEST ANSWER

Have a look in the assembly

[System.Security, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a]

in the method

public void ComputeSignature()

Only RSA and DSA keys are accepted. It is a shame that it isn't specified somewhere on the MSDN. You will have to pass on the SignedXml class.