Search in sources :

Example 1 with XMLStructure

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

the class GenerationTests method test_create_signature.

static void test_create_signature() throws Exception {
    System.out.println("* Generating signature.xml");
    // create references
    List<Reference> refs = new ArrayList<Reference>();
    // Reference 1
    refs.add(fac.newReference(STYLESHEET, sha1));
    // Reference 2
    refs.add(fac.newReference(STYLESHEET_B64, sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), null, null));
    // Reference 3
    refs.add(fac.newReference("#object-1", sha1, Collections.singletonList(fac.newTransform(Transform.XPATH, new XPathFilterParameterSpec("self::text()"))), XMLObject.TYPE, null));
    // Reference 4
    String expr = "\n" + " ancestor-or-self::dsig:SignedInfo                  " + "\n" + "  and                                               " + "\n" + " count(ancestor-or-self::dsig:Reference |           " + "\n" + "      here()/ancestor::dsig:Reference[1]) >         " + "\n" + " count(ancestor-or-self::dsig:Reference)            " + "\n" + "  or                                                " + "\n" + " count(ancestor-or-self::node() |                   " + "\n" + "      id('notaries')) =                             " + "\n" + " count(ancestor-or-self::node())                    " + "\n";
    XPathFilterParameterSpec xfp = new XPathFilterParameterSpec(expr, Collections.singletonMap("dsig", XMLSignature.XMLNS));
    refs.add(fac.newReference("", sha1, Collections.singletonList(fac.newTransform(Transform.XPATH, xfp)), XMLObject.TYPE, null));
    // Reference 5
    refs.add(fac.newReference("#object-2", sha1, Collections.singletonList(fac.newTransform(Transform.BASE64, (TransformParameterSpec) null)), XMLObject.TYPE, null));
    // Reference 6
    refs.add(fac.newReference("#manifest-1", sha1, null, Manifest.TYPE, null));
    // Reference 7
    refs.add(fac.newReference("#signature-properties-1", sha1, null, SignatureProperties.TYPE, null));
    // Reference 8
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    refs.add(fac.newReference("", sha1, transforms, null, null));
    // Reference 9
    transforms.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null));
    refs.add(fac.newReference("", sha1, transforms, null, null));
    // Reference 10
    Transform env = fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
    refs.add(fac.newReference("#xpointer(/)", sha1, Collections.singletonList(env), null, null));
    // Reference 11
    transforms.clear();
    transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    transforms.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null));
    refs.add(fac.newReference("#xpointer(/)", sha1, transforms, null, null));
    // Reference 12
    refs.add(fac.newReference("#object-3", sha1, null, XMLObject.TYPE, null));
    // Reference 13
    Transform withComments = fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null);
    refs.add(fac.newReference("#object-3", sha1, Collections.singletonList(withComments), XMLObject.TYPE, null));
    // Reference 14
    refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, null, XMLObject.TYPE, null));
    // Reference 15
    withComments = fac.newTransform(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (TransformParameterSpec) null);
    refs.add(fac.newReference("#xpointer(id('object-3'))", sha1, Collections.singletonList(withComments), XMLObject.TYPE, null));
    // Reference 16
    refs.add(fac.newReference("#reference-2", sha1));
    // Reference 17
    refs.add(fac.newReference("#manifest-reference-1", sha1, null, null, "reference-1"));
    // Reference 18
    refs.add(fac.newReference("#reference-1", sha1, null, null, "reference-2"));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, dsaSha1, refs);
    // create keyinfo
    XPathFilterParameterSpec xpf = new XPathFilterParameterSpec("ancestor-or-self::dsig:X509Data", Collections.singletonMap("dsig", XMLSignature.XMLNS));
    RetrievalMethod rm = kifac.newRetrievalMethod("#object-4", X509Data.TYPE, Collections.singletonList(fac.newTransform(Transform.XPATH, xpf)));
    KeyInfo ki = kifac.newKeyInfo(Collections.singletonList(rm), null);
    Document doc = db.newDocument();
    // create objects
    List<XMLStructure> objs = new ArrayList<XMLStructure>();
    // Object 1
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(doc.createTextNode("I am the text."))), "object-1", "text/plain", null));
    // Object 2
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(doc.createTextNode("SSBhbSB0aGUgdGV4dC4="))), "object-2", "text/plain", Transform.BASE64));
    // Object 3
    Element nc = doc.createElementNS(null, "NonCommentandus");
    nc.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "");
    nc.appendChild(doc.createComment(" Commentandum "));
    objs.add(fac.newXMLObject(Collections.singletonList(new DOMStructure(nc)), "object-3", null, null));
    // Manifest
    List<Reference> manRefs = new ArrayList<Reference>();
    // Manifest Reference 1
    manRefs.add(fac.newReference(STYLESHEET, sha1, null, null, "manifest-reference-1"));
    // Manifest Reference 2
    manRefs.add(fac.newReference("#reference-1", sha1));
    // Manifest Reference 3
    List<Transform> manTrans = new ArrayList<Transform>();
    Document docxslt = db.parse(new ByteArrayInputStream(xslt.getBytes()));
    Node xslElem = docxslt.getDocumentElement();
    manTrans.add(fac.newTransform(Transform.XSLT, new XSLTTransformParameterSpec(new DOMStructure(xslElem))));
    manTrans.add(fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null));
    manRefs.add(fac.newReference("#notaries", sha1, manTrans, null, null));
    objs.add(fac.newXMLObject(Collections.singletonList(fac.newManifest(manRefs, "manifest-1")), null, null, null));
    // SignatureProperties
    Element sa = doc.createElementNS("urn:demo", "SignerAddress");
    sa.setAttributeNS("http://www.w3.org/2000/xmlns/", "xmlns", "urn:demo");
    Element ip = doc.createElementNS("urn:demo", "IP");
    ip.appendChild(doc.createTextNode("192.168.21.138"));
    sa.appendChild(ip);
    SignatureProperty sp = fac.newSignatureProperty(Collections.singletonList(new DOMStructure(sa)), "#signature", null);
    SignatureProperties sps = fac.newSignatureProperties(Collections.singletonList(sp), "signature-properties-1");
    objs.add(fac.newXMLObject(Collections.singletonList(sps), null, null, null));
    // Object 4
    List<Object> xds = new ArrayList<Object>();
    xds.add("CN=User");
    xds.add(kifac.newX509IssuerSerial("CN=User", new BigInteger("45ef2729", 16)));
    xds.add(signingCert);
    objs.add(fac.newXMLObject(Collections.singletonList(kifac.newX509Data(xds)), "object-4", null, null));
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, ki, objs, "signature", null);
    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    dbf.setValidating(false);
    Document envDoc = dbf.newDocumentBuilder().parse(new FileInputStream(ENVELOPE));
    Element ys = (Element) envDoc.getElementsByTagName("YoursSincerely").item(0);
    DOMSignContext dsc = new DOMSignContext(signingKey, ys);
    dsc.setURIDereferencer(httpUd);
    sig.sign(dsc);
    //      StringWriter sw = new StringWriter();
    //        dumpDocument(envDoc, sw);
    NodeList nl = envDoc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
    if (nl.getLength() == 0) {
        throw new Exception("Couldn't find signature Element");
    }
    Element sigElement = (Element) nl.item(0);
    DOMValidateContext dvc = new DOMValidateContext(new X509KeySelector(ks), sigElement);
    dvc.setURIDereferencer(httpUd);
    File f = new File(System.getProperty("dir.test.vector.baltimore") + System.getProperty("file.separator") + "merlin-xmldsig-twenty-three" + System.getProperty("file.separator"));
    dvc.setBaseURI(f.toURI().toString());
    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) BigInteger(java.math.BigInteger)

Example 2 with XMLStructure

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

the class KeyInfoKeySelector method select.

@SuppressWarnings("unchecked")
@Override
public KeySelectorResult select(KeyInfo keyInfo, Purpose purpose, AlgorithmMethod method, XMLCryptoContext context) throws KeySelectorException {
    LOG.log(POILogger.DEBUG, "select key");
    if (null == keyInfo) {
        throw new KeySelectorException("no ds:KeyInfo present");
    }
    List<XMLStructure> keyInfoContent = keyInfo.getContent();
    certChain.clear();
    for (XMLStructure keyInfoStructure : keyInfoContent) {
        if (!(keyInfoStructure instanceof X509Data)) {
            continue;
        }
        X509Data x509Data = (X509Data) keyInfoStructure;
        List<?> x509DataList = x509Data.getContent();
        for (Object x509DataObject : x509DataList) {
            if (!(x509DataObject instanceof X509Certificate)) {
                continue;
            }
            X509Certificate certificate = (X509Certificate) x509DataObject;
            LOG.log(POILogger.DEBUG, "certificate", certificate.getSubjectX500Principal());
            certChain.add(certificate);
        }
    }
    if (certChain.isEmpty()) {
        throw new KeySelectorException("No key found!");
    }
    return this;
}
Also used : KeySelectorException(javax.xml.crypto.KeySelectorException) XMLStructure(javax.xml.crypto.XMLStructure) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) X509Certificate(java.security.cert.X509Certificate)

Example 3 with XMLStructure

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

the class OOXMLSignatureFacet method addManifestObject.

protected void addManifestObject(Document document, List<Reference> references, List<XMLObject> objects) throws XMLSignatureException {
    List<Reference> manifestReferences = new ArrayList<Reference>();
    addManifestReferences(manifestReferences);
    Manifest manifest = getSignatureFactory().newManifest(manifestReferences);
    // really has to be this value.
    String objectId = "idPackageObject";
    List<XMLStructure> objectContent = new ArrayList<XMLStructure>();
    objectContent.add(manifest);
    addSignatureTime(document, objectContent);
    XMLObject xo = getSignatureFactory().newXMLObject(objectContent, objectId, null, null);
    objects.add(xo);
    Reference reference = newReference("#" + objectId, null, XML_DIGSIG_NS + "Object", null, null);
    references.add(reference);
}
Also used : Reference(javax.xml.crypto.dsig.Reference) ArrayList(java.util.ArrayList) XMLObject(javax.xml.crypto.dsig.XMLObject) XMLStructure(javax.xml.crypto.XMLStructure) Manifest(javax.xml.crypto.dsig.Manifest)

Example 4 with XMLStructure

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

the class KeyInfoSignatureFacet method postSign.

@Override
public void postSign(Document document) throws MarshalException {
    LOG.log(POILogger.DEBUG, "postSign");
    NodeList nl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "Object");
    /*
         * Make sure we insert right after the ds:SignatureValue element, just
         * before the first ds:Object element.
         */
    Node nextSibling = (nl.getLength() == 0) ? null : nl.item(0);
    /*
         * Construct the ds:KeyInfo element using JSR 105.
         */
    KeyInfoFactory keyInfoFactory = signatureConfig.getKeyInfoFactory();
    List<Object> x509DataObjects = new ArrayList<Object>();
    X509Certificate signingCertificate = signatureConfig.getSigningCertificateChain().get(0);
    List<XMLStructure> keyInfoContent = new ArrayList<XMLStructure>();
    if (signatureConfig.isIncludeKeyValue()) {
        KeyValue keyValue;
        try {
            keyValue = keyInfoFactory.newKeyValue(signingCertificate.getPublicKey());
        } catch (KeyException e) {
            throw new RuntimeException("key exception: " + e.getMessage(), e);
        }
        keyInfoContent.add(keyValue);
    }
    if (signatureConfig.isIncludeIssuerSerial()) {
        x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(signingCertificate.getIssuerX500Principal().toString(), signingCertificate.getSerialNumber()));
    }
    if (signatureConfig.isIncludeEntireCertificateChain()) {
        x509DataObjects.addAll(signatureConfig.getSigningCertificateChain());
    } else {
        x509DataObjects.add(signingCertificate);
    }
    if (!x509DataObjects.isEmpty()) {
        X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
        keyInfoContent.add(x509Data);
    }
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);
    DOMKeyInfo domKeyInfo = (DOMKeyInfo) keyInfo;
    Key key = new Key() {

        private static final long serialVersionUID = 1L;

        public String getAlgorithm() {
            return null;
        }

        public byte[] getEncoded() {
            return null;
        }

        public String getFormat() {
            return null;
        }
    };
    Element n = document.getDocumentElement();
    DOMSignContext domSignContext = (nextSibling == null) ? new DOMSignContext(key, n) : new DOMSignContext(key, n, nextSibling);
    for (Map.Entry<String, String> me : signatureConfig.getNamespacePrefixes().entrySet()) {
        domSignContext.putNamespacePrefix(me.getKey(), me.getValue());
    }
    DOMStructure domStructure = new DOMStructure(n);
    domKeyInfo.marshal(domStructure, domSignContext);
    // move keyinfo into the right place
    if (nextSibling != null) {
        NodeList kiNl = document.getElementsByTagNameNS(XML_DIGSIG_NS, "KeyInfo");
        if (kiNl.getLength() != 1) {
            throw new RuntimeException("KeyInfo wasn't set");
        }
        nextSibling.getParentNode().insertBefore(kiNl.item(0), nextSibling);
    }
}
Also used : KeyValue(javax.xml.crypto.dsig.keyinfo.KeyValue) NodeList(org.w3c.dom.NodeList) Node(org.w3c.dom.Node) Element(org.w3c.dom.Element) ArrayList(java.util.ArrayList) XMLStructure(javax.xml.crypto.XMLStructure) X509Data(javax.xml.crypto.dsig.keyinfo.X509Data) X509Certificate(java.security.cert.X509Certificate) KeyException(java.security.KeyException) KeyInfoFactory(javax.xml.crypto.dsig.keyinfo.KeyInfoFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) DOMKeyInfo(org.apache.jcp.xml.dsig.internal.dom.DOMKeyInfo) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMKeyInfo(org.apache.jcp.xml.dsig.internal.dom.DOMKeyInfo) DOMStructure(javax.xml.crypto.dom.DOMStructure) Map(java.util.Map) Key(java.security.Key)

Example 5 with XMLStructure

use of javax.xml.crypto.XMLStructure in project santuario-java by apache.

the class DOMKeyInfo method marshalInternal.

private static void marshalInternal(XmlWriter xwriter, KeyInfo ki, String dsPrefix, XMLCryptoContext context, boolean declareNamespace) throws MarshalException {
    xwriter.writeStartElement(dsPrefix, "KeyInfo", XMLSignature.XMLNS);
    if (declareNamespace) {
        xwriter.writeNamespace(dsPrefix, XMLSignature.XMLNS);
    }
    xwriter.writeIdAttribute("", "", "Id", ki.getId());
    // create and append KeyInfoType elements
    List<XMLStructure> keyInfoTypes = getContent(ki);
    for (XMLStructure kiType : keyInfoTypes) {
        xwriter.marshalStructure(kiType, dsPrefix, context);
    }
    // "KeyInfo"
    xwriter.writeEndElement();
}
Also used : XMLStructure(javax.xml.crypto.XMLStructure)

Aggregations

XMLStructure (javax.xml.crypto.XMLStructure)19 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 X509Certificate (java.security.cert.X509Certificate)5 DOMValidateContext (javax.xml.crypto.dsig.dom.DOMValidateContext)5 Element (org.w3c.dom.Element)5 NoSuchAlgorithmException (java.security.NoSuchAlgorithmException)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 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)3 X509Data (javax.xml.crypto.dsig.keyinfo.X509Data)3 InputStream (java.io.InputStream)2 Key (java.security.Key)2