Search in sources :

Example 16 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_exc_signature.

static void test_create_exc_signature() throws Exception {
    System.out.println("* Generating exc_signature.xml");
    List<Reference> refs = new ArrayList<Reference>(4);
    // create reference 1
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)), null, null));
    // create reference 2
    List<String> prefixList = new ArrayList<String>(2);
    prefixList.add("bar");
    prefixList.add("#default");
    ExcC14NParameterSpec params = new ExcC14NParameterSpec(prefixList);
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, params)), null, null));
    // create reference 3
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null)), null, null));
    // create reference 4
    prefixList = new ArrayList<String>(2);
    prefixList.add("bar");
    prefixList.add("#default");
    params = new ExcC14NParameterSpec(prefixList);
    refs.add(fac.newReference("#xpointer(id('to-be-signed'))", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(CanonicalizationMethod.EXCLUSIVE_WITH_COMMENTS, params)), null, null));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
    // create KeyInfo
    List<XMLStructure> kits = new ArrayList<XMLStructure>(2);
    kits.add(kifac.newKeyValue(validatingKey));
    KeyInfo ki = kifac.newKeyInfo(kits);
    // create Objects
    Document doc = db.newDocument();
    Element baz = doc.createElementNS("urn:bar", "bar:Baz");
    Comment com = doc.createComment(" comment ");
    baz.appendChild(com);
    XMLObject obj = fac.newXMLObject(Collections.singletonList(new DOMStructure(baz)), "to-be-signed", null, null);
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki, Collections.singletonList(obj), null, null);
    Element foo = doc.createElementNS("urn:foo", "Foo");
    foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:foo");
    foo.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns:bar", "urn:bar");
    doc.appendChild(foo);
    DOMSignContext dsc = new DOMSignContext(signingKey, foo);
    dsc.putNamespacePrefix(XMLSignature.XMLNS, "dsig");
    sig.sign(dsc);
    //      dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
    DOMValidateContext dvc = new DOMValidateContext(new KeySelectors.KeyValueKeySelector(), foo.getLastChild());
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
    System.out.println();
}
Also used : URIReference(javax.xml.crypto.URIReference) XMLStructure(javax.xml.crypto.XMLStructure) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext)

Example 17 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_signature_external.

private static void test_create_signature_external(SignatureMethod sm, KeyInfo ki, Key signingKey, KeySelector ks, boolean b64) throws Exception {
    // create reference
    Reference ref;
    if (b64) {
        ref = fac.newReference(STYLESHEET_B64, sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), null, null);
    } else {
        ref = fac.newReference(STYLESHEET, sha1);
    }
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, sm, Collections.singletonList(ref));
    Document doc = db.newDocument();
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki);
    DOMSignContext dsc = new DOMSignContext(signingKey, doc);
    dsc.setURIDereferencer(httpUd);
    sig.sign(dsc);
    DOMValidateContext dvc = new DOMValidateContext(ks, doc.getDocumentElement());
    File f = new File(DATA_DIR);
    dvc.setBaseURI(f.toURI().toString());
    dvc.setURIDereferencer(httpUd);
    XMLSignature sig2 = fac.unmarshalXMLSignature(dvc);
    if (sig.equals(sig2) == false) {
        throw new Exception("Unmarshalled signature is not equal to generated signature");
    }
    if (sig2.validate(dvc) == false) {
        throw new Exception("Validation of generated signature failed");
    }
}
Also used : URIReference(javax.xml.crypto.URIReference) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 18 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project jdk8u_jdk by JetBrains.

the class DOMXMLSignature method sign.

public void sign(XMLSignContext signContext) throws MarshalException, XMLSignatureException {
    if (signContext == null) {
        throw new NullPointerException("signContext cannot be null");
    }
    DOMSignContext context = (DOMSignContext) signContext;
    marshal(context.getParent(), context.getNextSibling(), DOMUtils.getSignaturePrefix(context), context);
    // generate references and signature value
    List<Reference> allReferences = new ArrayList<Reference>();
    // traverse the Signature and register all objects with IDs that
    // may contain References
    signatureIdMap = new HashMap<String, XMLStructure>();
    signatureIdMap.put(id, this);
    signatureIdMap.put(si.getId(), si);
    @SuppressWarnings("unchecked") List<Reference> refs = si.getReferences();
    for (Reference ref : refs) {
        signatureIdMap.put(ref.getId(), ref);
    }
    for (XMLObject obj : objects) {
        signatureIdMap.put(obj.getId(), obj);
        @SuppressWarnings("unchecked") List<XMLStructure> content = obj.getContent();
        for (XMLStructure xs : content) {
            if (xs instanceof Manifest) {
                Manifest man = (Manifest) xs;
                signatureIdMap.put(man.getId(), man);
                @SuppressWarnings("unchecked") List<Reference> manRefs = man.getReferences();
                for (Reference ref : manRefs) {
                    allReferences.add(ref);
                    signatureIdMap.put(ref.getId(), ref);
                }
            }
        }
    }
    // always add SignedInfo references after Manifest references so
    // that Manifest reference are digested first
    allReferences.addAll(refs);
    // generate/digest each reference
    for (Reference ref : allReferences) {
        digestReference((DOMReference) ref, signContext);
    }
    // do final sweep to digest any references that were skipped or missed
    for (Reference ref : allReferences) {
        if (((DOMReference) ref).isDigested()) {
            continue;
        }
        ((DOMReference) ref).digest(signContext);
    }
    Key signingKey = null;
    KeySelectorResult ksr = null;
    try {
        ksr = signContext.getKeySelector().select(ki, KeySelector.Purpose.SIGN, si.getSignatureMethod(), signContext);
        signingKey = ksr.getKey();
        if (signingKey == null) {
            throw new XMLSignatureException("the keySelector did not " + "find a signing key");
        }
    } catch (KeySelectorException kse) {
        throw new XMLSignatureException("cannot find signing key", kse);
    }
    // calculate signature value
    try {
        byte[] val = ((AbstractDOMSignatureMethod) si.getSignatureMethod()).sign(signingKey, si, signContext);
        ((DOMSignatureValue) sv).setValue(val);
    } catch (InvalidKeyException ike) {
        throw new XMLSignatureException(ike);
    }
    this.localSigElem = sigElem;
    this.ksr = ksr;
}
Also used : ArrayList(java.util.ArrayList) InvalidKeyException(java.security.InvalidKeyException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) Key(java.security.Key)

Example 19 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext in project poi by apache.

the class SignatureInfo method preSign.

/**
     * Helper method for adding informations before the signing.
     * Normally {@link #confirmSignature()} is sufficient to be used.
     */
@SuppressWarnings("unchecked")
public DigestInfo preSign(Document document, List<DigestInfo> digestInfos) throws XMLSignatureException, MarshalException {
    signatureConfig.init(false);
    // it's necessary to explicitly set the mdssi namespace, but the sign() method has no
    // normal way to interfere with, so we need to add the namespace under the hand ...
    EventTarget target = (EventTarget) document;
    EventListener creationListener = signatureConfig.getSignatureMarshalListener();
    if (creationListener != null) {
        if (creationListener instanceof SignatureMarshalListener) {
            ((SignatureMarshalListener) creationListener).setEventTarget(target);
        }
        SignatureMarshalListener.setListener(target, creationListener, true);
    }
    /*
         * Signature context construction.
         */
    XMLSignContext xmlSignContext = new DOMSignContext(signatureConfig.getKey(), document);
    URIDereferencer uriDereferencer = signatureConfig.getUriDereferencer();
    if (null != uriDereferencer) {
        xmlSignContext.setURIDereferencer(uriDereferencer);
    }
    for (Map.Entry<String, String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
        xmlSignContext.putNamespacePrefix(me.getKey(), me.getValue());
    }
    xmlSignContext.setDefaultNamespacePrefix("");
    // signatureConfig.getNamespacePrefixes().get(XML_DIGSIG_NS));
    brokenJvmWorkaround(xmlSignContext);
    XMLSignatureFactory signatureFactory = signatureConfig.getSignatureFactory();
    /*
         * Add ds:References that come from signing client local files.
         */
    List<Reference> references = new ArrayList<Reference>();
    for (DigestInfo digestInfo : safe(digestInfos)) {
        byte[] documentDigestValue = digestInfo.digestValue;
        String uri = new File(digestInfo.description).getName();
        Reference reference = SignatureFacet.newReference(uri, null, null, null, documentDigestValue, signatureConfig);
        references.add(reference);
    }
    /*
         * Invoke the signature facets.
         */
    List<XMLObject> objects = new ArrayList<XMLObject>();
    for (SignatureFacet signatureFacet : signatureConfig.getSignatureFacets()) {
        LOG.log(POILogger.DEBUG, "invoking signature facet: " + signatureFacet.getClass().getSimpleName());
        signatureFacet.preSign(document, references, objects);
    }
    /*
         * ds:SignedInfo
         */
    SignedInfo signedInfo;
    try {
        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(signatureConfig.getSignatureMethodUri(), null);
        CanonicalizationMethod canonicalizationMethod = signatureFactory.newCanonicalizationMethod(signatureConfig.getCanonicalizationMethod(), (C14NMethodParameterSpec) null);
        signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);
    } catch (GeneralSecurityException e) {
        throw new XMLSignatureException(e);
    }
    /*
         * JSR105 ds:Signature creation
         */
    String signatureValueId = signatureConfig.getPackageSignatureId() + "-signature-value";
    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null, objects, signatureConfig.getPackageSignatureId(), signatureValueId);
    /*
         * ds:Signature Marshalling.
         */
    xmlSignature.sign(xmlSignContext);
    /*
         * Completion of undigested ds:References in the ds:Manifests.
         */
    for (XMLObject object : objects) {
        LOG.log(POILogger.DEBUG, "object java type: " + object.getClass().getName());
        List<XMLStructure> objectContentList = object.getContent();
        for (XMLStructure objectContent : objectContentList) {
            LOG.log(POILogger.DEBUG, "object content java type: " + objectContent.getClass().getName());
            if (!(objectContent instanceof Manifest))
                continue;
            Manifest manifest = (Manifest) objectContent;
            List<Reference> manifestReferences = manifest.getReferences();
            for (Reference manifestReference : manifestReferences) {
                if (manifestReference.getDigestValue() != null)
                    continue;
                DOMReference manifestDOMReference = (DOMReference) manifestReference;
                manifestDOMReference.digest(xmlSignContext);
            }
        }
    }
    /*
         * Completion of undigested ds:References.
         */
    List<Reference> signedInfoReferences = signedInfo.getReferences();
    for (Reference signedInfoReference : signedInfoReferences) {
        DOMReference domReference = (DOMReference) signedInfoReference;
        // ds:Reference with external digest value
        if (domReference.getDigestValue() != null)
            continue;
        domReference.digest(xmlSignContext);
    }
    /*
         * Calculation of XML signature digest value.
         */
    DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(xmlSignContext, dataStream);
    byte[] octets = dataStream.toByteArray();
    /*
         * TODO: we could be using DigestOutputStream here to optimize memory
         * usage.
         */
    MessageDigest md = CryptoFunctions.getMessageDigest(signatureConfig.getDigestAlgo());
    byte[] digestValue = md.digest(octets);
    String description = signatureConfig.getSignatureDescription();
    return new DigestInfo(digestValue, signatureConfig.getDigestAlgo(), description);
}
Also used : ArrayList(java.util.ArrayList) XMLStructure(javax.xml.crypto.XMLStructure) URIDereferencer(javax.xml.crypto.URIDereferencer) XMLSignContext(javax.xml.crypto.dsig.XMLSignContext) EventListener(org.w3c.dom.events.EventListener) MessageDigest(java.security.MessageDigest) EventTarget(org.w3c.dom.events.EventTarget) XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) DOMSignedInfo(org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) Reference(javax.xml.crypto.dsig.Reference) GeneralSecurityException(java.security.GeneralSecurityException) CanonicalizationMethod(javax.xml.crypto.dsig.CanonicalizationMethod) XMLObject(javax.xml.crypto.dsig.XMLObject) ByteArrayOutputStream(java.io.ByteArrayOutputStream) Manifest(javax.xml.crypto.dsig.Manifest) DOMReference(org.apache.jcp.xml.dsig.internal.dom.DOMReference) DOMSignedInfo(org.apache.jcp.xml.dsig.internal.dom.DOMSignedInfo) SignedInfo(javax.xml.crypto.dsig.SignedInfo) SignatureFacet(org.apache.poi.poifs.crypt.dsig.facets.SignatureFacet) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) SignatureMethod(javax.xml.crypto.dsig.SignatureMethod) Map(java.util.Map) HashMap(java.util.HashMap) File(java.io.File) XMLSignatureException(javax.xml.crypto.dsig.XMLSignatureException) XMLSignature(javax.xml.crypto.dsig.XMLSignature)

Aggregations

DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)19 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)9 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)8 URIReference (javax.xml.crypto.URIReference)8 URIReferenceException (javax.xml.crypto.URIReferenceException)8 XMLStructure (javax.xml.crypto.XMLStructure)6 SignedInfo (javax.xml.crypto.dsig.SignedInfo)6 Reference (javax.xml.crypto.dsig.Reference)5 XMLSignature (javax.xml.crypto.dsig.XMLSignature)5 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)5 Key (java.security.Key)4 ArrayList (java.util.ArrayList)4 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)4 Node (org.w3c.dom.Node)4 KeyInfoFactory (javax.xml.crypto.dsig.keyinfo.KeyInfoFactory)3 C14NMethodParameterSpec (javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)3 GeneralSecurityException (java.security.GeneralSecurityException)2 InvalidKeyException (java.security.InvalidKeyException)2 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2