Search in sources :

Example 11 with XMLStructure

use of javax.xml.crypto.XMLStructure in project jdk8u_jdk by JetBrains.

the class GenerationTests method test_create_sign_spec.

static void test_create_sign_spec() throws Exception {
    System.out.println("* Generating sign-spec.xml");
    List<Reference> refs = new ArrayList<Reference>(2);
    // create reference 1
    List<XPathType> types = new ArrayList<XPathType>(3);
    types.add(new XPathType(" //ToBeSigned ", XPathType.Filter.INTERSECT));
    types.add(new XPathType(" //NotToBeSigned ", XPathType.Filter.SUBTRACT));
    types.add(new XPathType(" //ReallyToBeSigned ", XPathType.Filter.UNION));
    XPathFilter2ParameterSpec xp1 = new XPathFilter2ParameterSpec(types);
    refs.add(fac.newReference("", fac.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(fac.newTransform(Transform.XPATH2, xp1)), null, null));
    // create reference 2
    List<Transform> trans2 = new ArrayList<Transform>(2);
    trans2.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    XPathFilter2ParameterSpec xp2 = new XPathFilter2ParameterSpec(Collections.singletonList(new XPathType(" / ", XPathType.Filter.UNION)));
    trans2.add(fac.newTransform(Transform.XPATH2, xp2));
    refs.add(fac.newReference("#signature-value", fac.newDigestMethod(DigestMethod.SHA1, null), trans2, null, null));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), refs);
    // create KeyInfo
    List<XMLStructure> kits = new ArrayList<XMLStructure>(2);
    kits.add(kifac.newKeyValue(validatingKey));
    List<Object> xds = new ArrayList<Object>(2);
    xds.add("CN=User");
    xds.add(signingCert);
    kits.add(kifac.newX509Data(xds));
    KeyInfo ki = kifac.newKeyInfo(kits);
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki, null, null, "signature-value");
    Document doc = db.newDocument();
    Element tbs1 = doc.createElementNS(null, "ToBeSigned");
    Comment tbs1Com = doc.createComment(" comment ");
    Element tbs1Data = doc.createElementNS(null, "Data");
    Element tbs1ntbs = doc.createElementNS(null, "NotToBeSigned");
    Element tbs1rtbs = doc.createElementNS(null, "ReallyToBeSigned");
    Comment tbs1rtbsCom = doc.createComment(" comment ");
    Element tbs1rtbsData = doc.createElementNS(null, "Data");
    tbs1rtbs.appendChild(tbs1rtbsCom);
    tbs1rtbs.appendChild(tbs1rtbsData);
    tbs1ntbs.appendChild(tbs1rtbs);
    tbs1.appendChild(tbs1Com);
    tbs1.appendChild(tbs1Data);
    tbs1.appendChild(tbs1ntbs);
    Element tbs2 = doc.createElementNS(null, "ToBeSigned");
    Element tbs2Data = doc.createElementNS(null, "Data");
    Element tbs2ntbs = doc.createElementNS(null, "NotToBeSigned");
    Element tbs2ntbsData = doc.createElementNS(null, "Data");
    tbs2ntbs.appendChild(tbs2ntbsData);
    tbs2.appendChild(tbs2Data);
    tbs2.appendChild(tbs2ntbs);
    Element document = doc.createElementNS(null, "Document");
    document.appendChild(tbs1);
    document.appendChild(tbs2);
    doc.appendChild(document);
    DOMSignContext dsc = new DOMSignContext(signingKey, document);
    sig.sign(dsc);
    //      dumpDocument(doc, new FileWriter("/tmp/foo.xml"));
    DOMValidateContext dvc = new DOMValidateContext(new KeySelectors.KeyValueKeySelector(), document.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 : XMLStructure(javax.xml.crypto.XMLStructure) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReference(javax.xml.crypto.URIReference) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext)

Example 12 with XMLStructure

use of javax.xml.crypto.XMLStructure 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 13 with XMLStructure

use of javax.xml.crypto.XMLStructure 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)

Example 14 with XMLStructure

use of javax.xml.crypto.XMLStructure in project poi by apache.

the class OOXMLSignatureFacet method addSignatureTime.

protected void addSignatureTime(Document document, List<XMLStructure> objectContent) {
    /*
         * SignatureTime
         */
    DateFormat fmt = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.ROOT);
    fmt.setTimeZone(LocaleUtil.TIMEZONE_UTC);
    String nowStr = fmt.format(signatureConfig.getExecutionTime());
    LOG.log(POILogger.DEBUG, "now: " + nowStr);
    SignatureTimeDocument sigTime = SignatureTimeDocument.Factory.newInstance();
    CTSignatureTime ctTime = sigTime.addNewSignatureTime();
    ctTime.setFormat("YYYY-MM-DDThh:mm:ssTZD");
    ctTime.setValue(nowStr);
    Element n = (Element) document.importNode(ctTime.getDomNode(), true);
    List<XMLStructure> signatureTimeContent = new ArrayList<XMLStructure>();
    signatureTimeContent.add(new DOMStructure(n));
    SignatureProperty signatureTimeSignatureProperty = getSignatureFactory().newSignatureProperty(signatureTimeContent, "#" + signatureConfig.getPackageSignatureId(), "idSignatureTime");
    List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>();
    signaturePropertyContent.add(signatureTimeSignatureProperty);
    SignatureProperties signatureProperties = getSignatureFactory().newSignatureProperties(signaturePropertyContent, "id-signature-time-" + signatureConfig.getExecutionTime());
    objectContent.add(signatureProperties);
}
Also used : Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) XMLStructure(javax.xml.crypto.XMLStructure) SignatureProperty(javax.xml.crypto.dsig.SignatureProperty) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) CTSignatureTime(org.openxmlformats.schemas.xpackage.x2006.digitalSignature.CTSignatureTime) DOMStructure(javax.xml.crypto.dom.DOMStructure) SignatureProperties(javax.xml.crypto.dsig.SignatureProperties) SignatureTimeDocument(org.openxmlformats.schemas.xpackage.x2006.digitalSignature.SignatureTimeDocument) SimpleDateFormat(java.text.SimpleDateFormat)

Example 15 with XMLStructure

use of javax.xml.crypto.XMLStructure in project poi by apache.

the class OOXMLSignatureFacet method addSignatureInfo.

protected void addSignatureInfo(Document document, List<Reference> references, List<XMLObject> objects) throws XMLSignatureException {
    List<XMLStructure> objectContent = new ArrayList<XMLStructure>();
    SignatureInfoV1Document sigV1 = SignatureInfoV1Document.Factory.newInstance();
    CTSignatureInfoV1 ctSigV1 = sigV1.addNewSignatureInfoV1();
    ctSigV1.setManifestHashAlgorithm(signatureConfig.getDigestMethodUri());
    Element n = (Element) document.importNode(ctSigV1.getDomNode(), true);
    n.setAttributeNS(XML_NS, XMLConstants.XMLNS_ATTRIBUTE, MS_DIGSIG_NS);
    List<XMLStructure> signatureInfoContent = new ArrayList<XMLStructure>();
    signatureInfoContent.add(new DOMStructure(n));
    SignatureProperty signatureInfoSignatureProperty = getSignatureFactory().newSignatureProperty(signatureInfoContent, "#" + signatureConfig.getPackageSignatureId(), "idOfficeV1Details");
    List<SignatureProperty> signaturePropertyContent = new ArrayList<SignatureProperty>();
    signaturePropertyContent.add(signatureInfoSignatureProperty);
    SignatureProperties signatureProperties = getSignatureFactory().newSignatureProperties(signaturePropertyContent, null);
    objectContent.add(signatureProperties);
    String objectId = "idOfficeObject";
    objects.add(getSignatureFactory().newXMLObject(objectContent, objectId, null, null));
    Reference reference = newReference("#" + objectId, null, XML_DIGSIG_NS + "Object", null, null);
    references.add(reference);
}
Also used : SignatureInfoV1Document(com.microsoft.schemas.office.x2006.digsig.SignatureInfoV1Document) Reference(javax.xml.crypto.dsig.Reference) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) DOMStructure(javax.xml.crypto.dom.DOMStructure) SignatureProperties(javax.xml.crypto.dsig.SignatureProperties) CTSignatureInfoV1(com.microsoft.schemas.office.x2006.digsig.CTSignatureInfoV1) XMLStructure(javax.xml.crypto.XMLStructure) SignatureProperty(javax.xml.crypto.dsig.SignatureProperty)

Aggregations

XMLStructure (javax.xml.crypto.XMLStructure)17 ArrayList (java.util.ArrayList)8 DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)7 DOMStructure (javax.xml.crypto.dom.DOMStructure)6 Reference (javax.xml.crypto.dsig.Reference)6 XMLObject (javax.xml.crypto.dsig.XMLObject)6 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)5 Element (org.w3c.dom.Element)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)4 X509Certificate (java.security.cert.X509Certificate)4 URIReference (javax.xml.crypto.URIReference)4 URIReferenceException (javax.xml.crypto.URIReferenceException)4 Map (java.util.Map)3 Manifest (javax.xml.crypto.dsig.Manifest)3 SignatureProperties (javax.xml.crypto.dsig.SignatureProperties)3 SignatureProperty (javax.xml.crypto.dsig.SignatureProperty)3 Key (java.security.Key)2 HashMap (java.util.HashMap)2 List (java.util.List)2 CanonicalizationMethod (javax.xml.crypto.dsig.CanonicalizationMethod)2