signing a xml document with x509 certificate

2019-03-26 06:44发布

Every time I try to send a signed XML, the web service verifier rejects it.

To sign the document I just adapted this sample code provided by Microsoft:

http://msdn.microsoft.com/es-es/library/ms229745(v=vs.110).aspx

My implementation:

    public static XmlDocument FirmarXML(XmlDocument xmlDoc)
    {
        try
        {
            X509Certificate2 myCert = null;
            var store = new X509Store(StoreLocation.CurrentUser); //StoreLocation.LocalMachine fails too
            store.Open(OpenFlags.ReadOnly);
            var certificates = store.Certificates;
            foreach (var certificate in certificates)
            {
                if (certificate.Subject.Contains("xxx"))
                {
                    myCert = certificate;
                    break;
                }
            }

            if (myCert != null)
            {
                RSA rsaKey = ((RSA)myCert.PrivateKey);

                // Sign the XML document. 
                SignXml(xmlDoc, rsaKey);                    
            }

        }
        catch (Exception e)
        {
            MessageBox.Show(e.Message);
        }
        return xmlDoc;
    }


    // Sign an XML file. 
    // This document cannot be verified unless the verifying 
    // code has the key with which it was signed.
    public static void SignXml(XmlDocument xmlDoc, RSA Key)
    {
        // Check arguments.
        if (xmlDoc == null)
            throw new ArgumentException("xmlDoc");
        if (Key == null)
            throw new ArgumentException("Key");

        // Create a SignedXml object.
        SignedXml signedXml = new SignedXml(xmlDoc);

        // Add the key to the SignedXml document.
        signedXml.SigningKey = Key;

        // Create a reference to be signed.
        Reference reference = new Reference();
        reference.Uri = "";

        // Add an enveloped transformation to the reference.
        XmlDsigEnvelopedSignatureTransform env = new XmlDsigEnvelopedSignatureTransform();
        reference.AddTransform(env);

        // Add the reference to the SignedXml object.
        signedXml.AddReference(reference);

        // Compute the signature.
        signedXml.ComputeSignature();

        // Get the XML representation of the signature and save
        // it to an XmlElement object.
        XmlElement xmlDigitalSignature = signedXml.GetXml();

        // Append the element to the XML document.
        xmlDoc.DocumentElement.AppendChild(xmlDoc.ImportNode(xmlDigitalSignature, true));

    }

I think I am following the same steps using my own certificate, however it doesn't works as expected.

Any suggestion will be welcome.

2条回答
来,给爷笑一个
2楼-- · 2019-03-26 07:06

How does the server know what certificate the document is signed with? You seem to not to include the cert in the signed document:

    KeyInfo keyInfo = new KeyInfo();
    KeyInfoX509Data keyInfoData = new KeyInfoX509Data( Key );
    keyInfo.AddClause( keyInfoData );
    signedXml.KeyInfo = keyInfo;

If you need more details, consult my blog entry

http://www.wiktorzychla.com/2012/12/interoperable-xml-digital-signatures-c_20.html

查看更多
女痞
3楼-- · 2019-03-26 07:11

I already made some changes following the Wiktor's samples. However the signature still rejected by the web service.

The method I use to sign now is this:

public static string SignXml(XmlDocument Document, X509Certificate2 cert)
{
    SignedXml signedXml = new SignedXml(Document);
    signedXml.SigningKey = cert.PrivateKey;

    // Create a reference to be signed.
    Reference reference = new Reference();
    reference.Uri = "";

    // Add an enveloped transformation to the reference.            
    XmlDsigEnvelopedSignatureTransform env =
       new XmlDsigEnvelopedSignatureTransform(true);
    reference.AddTransform(env);

    //canonicalize
    XmlDsigC14NTransform c14t = new XmlDsigC14NTransform();
    reference.AddTransform(c14t);

    KeyInfo keyInfo = new KeyInfo();
    KeyInfoX509Data keyInfoData = new KeyInfoX509Data(cert);
    KeyInfoName kin = new KeyInfoName();
    kin.Value = "Public key of certificate";
    RSACryptoServiceProvider rsaprovider = (RSACryptoServiceProvider)cert.PublicKey.Key;
    RSAKeyValue rkv = new RSAKeyValue(rsaprovider);
    keyInfo.AddClause(kin);
    keyInfo.AddClause(rkv);
    keyInfo.AddClause(keyInfoData);
    signedXml.KeyInfo = keyInfo;

    // Add the reference to the SignedXml object.
    signedXml.AddReference(reference);

    // Compute the signature.
    signedXml.ComputeSignature();

    // Get the XML representation of the signature and save 
    // it to an XmlElement object.
    XmlElement xmlDigitalSignature = signedXml.GetXml();

    Document.DocumentElement.AppendChild(
        Document.ImportNode(xmlDigitalSignature, true));

    return Document.OuterXml;
}

And the signature appears like this in the document:

<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
    <SignedInfo>
        <CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
        <SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
        <Reference URI="">
            <Transforms>
                <Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                <Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
            </Transforms>
            <DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
            <DigestValue>zRSPtja5EtX7hVbyJ11EjoYTRDk=</DigestValue>
        </Reference>
    </SignedInfo>
    <SignatureValue>Ua1/WP28WzfXaxUj....</SignatureValue>
    <KeyInfo>
        <KeyName>Public key of certificate</KeyName>
        <KeyValue>
            <RSAKeyValue>
                <Modulus>0mmCc5Rlibh44o/C/k5....</Modulus>
                <Exponent>AQAB</Exponent>
            </RSAKeyValue>
        </KeyValue>
        <X509Data>
            <X509Certificate>MIIF3jCCBUegAwIBAgIEPQa1....</X509Certificate>
        </X509Data>
    </KeyInfo>
</Signature>

When a right document is sent to the server, this returns this signature that I used as a patter to identify the necessary fields:

<ds:Signature xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
    <ds:SignedInfo>
        <ds:CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
        <ds:SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" />
        <ds:Reference URI="">
            <ds:Transforms>
                <ds:Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" />
                <ds:Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" />
            </ds:Transforms>
            <ds:DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" />
            <ds:DigestValue>nQOtmW194/aI+hedq+Dqp+n3IuU=</ds:DigestValue>
        </ds:Reference>
    </ds:SignedInfo>
    <ds:SignatureValue>kyp+a6arETylW8ZuucKJyd....</ds:SignatureValue>
    <ds:KeyInfo>
        <ds:KeyName>Public key of certificate</ds:KeyName>
        <ds:KeyValue>
            <ds:RSAKeyValue>
                <ds:Modulus>t0Yial28LxcIoPj16PlLIzaV...</ds:Modulus>
                <ds:Exponent>AQAB</ds:Exponent>
            </ds:RSAKeyValue>
        </ds:KeyValue>
        <ds:X509Data>
            <ds:X509Certificate>MIIHOTCCBiGgAwIBAgICVJIwDQYJKo....</ds:X509Certificate>
        </ds:X509Data>
    </ds:KeyInfo>
</ds:Signature>

It seems to me right. However still not work. Any one has any clue?

查看更多
登录 后发表回答