Search in sources :

Example 6 with DOMSignContext

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

the class GenerationTests method test_create_signature_with_attr_in_no_namespace.

static void test_create_signature_with_attr_in_no_namespace() throws Exception {
    System.out.println("* Generating signature-with-attr-in-no-namespace.xml");
    // create references
    List<Reference> refs = Collections.singletonList(fac.newReference("#unknown", sha1));
    // create SignedInfo
    SignedInfo si = fac.newSignedInfo(withoutComments, rsaSha1, refs);
    // create object-1
    Document doc = db.newDocument();
    Element nc = doc.createElementNS(null, "NonCommentandus");
    // add attribute with no namespace
    nc.setAttribute("Id", "unknown");
    XMLObject obj = fac.newXMLObject(Collections.singletonList(new DOMStructure(nc)), "object-1", null, null);
    // create XMLSignature
    XMLSignature sig = fac.newXMLSignature(si, rsa, Collections.singletonList(obj), "signature", null);
    DOMSignContext dsc = new DOMSignContext(getPrivateKey("RSA", 512), doc);
    dsc.setIdAttributeNS(nc, null, "Id");
    sig.sign(dsc);
    //      dumpDocument(doc, new PrintWriter(System.out));
    DOMValidateContext dvc = new DOMValidateContext(kvks, doc.getDocumentElement());
    dvc.setIdAttributeNS(nc, null, "Id");
    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) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) DOMValidateContext(javax.xml.crypto.dsig.dom.DOMValidateContext) URIReferenceException(javax.xml.crypto.URIReferenceException) NoSuchAlgorithmException(java.security.NoSuchAlgorithmException)

Example 7 with DOMSignContext

use of javax.xml.crypto.dsig.dom.DOMSignContext 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 8 with DOMSignContext

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

the class TestServlet method signDocument.

private static void signDocument(final Document doc, final PrivateKey privateKey) throws Exception {
    final XMLSignatureFactory xsf = XMLSignatureFactory.getInstance("DOM");
    final Reference ref = xsf.newReference("", xsf.newDigestMethod(DigestMethod.SHA256, null), Collections.singletonList(xsf.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
    final SignedInfo si = xsf.newSignedInfo(xsf.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null), xsf.newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null), Collections.singletonList(ref));
    final KeyInfo ki = KeyInfoFactory.getInstance().newKeyInfo(Collections.singletonList(KeyInfoFactory.getInstance().newKeyName("dummy")));
    xsf.newXMLSignature(si, ki).sign(new DOMSignContext(privateKey, doc.getDocumentElement()));
}
Also used : XMLSignatureFactory(javax.xml.crypto.dsig.XMLSignatureFactory) KeyInfo(javax.xml.crypto.dsig.keyinfo.KeyInfo) Reference(javax.xml.crypto.dsig.Reference) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) SignedInfo(javax.xml.crypto.dsig.SignedInfo) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

Example 9 with DOMSignContext

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

the class XmlSignerProcessor method createAndConfigureSignContext.

private DOMSignContext createAndConfigureSignContext(Node parent, KeySelector keySelector) {
    DOMSignContext dsc = new DOMSignContext(keySelector, parent);
    // set namespace prefix for "http://www.w3.org/2000/09/xmldsig#" according to best practice described in http://www.w3.org/TR/xmldsig-bestpractices/#signing-xml-without-namespaces
    if (getConfiguration().getPrefixForXmlSignatureNamespace() != null && !getConfiguration().getPrefixForXmlSignatureNamespace().isEmpty()) {
        dsc.putNamespacePrefix("http://www.w3.org/2000/09/xmldsig#", getConfiguration().getPrefixForXmlSignatureNamespace());
    }
    dsc.putNamespacePrefix("http://www.w3.org/2001/10/xml-exc-c14n#", "ec");
    setCryptoContextProperties(dsc);
    setUriDereferencerAndBaseUri(dsc);
    return dsc;
}
Also used : DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext)

Example 10 with DOMSignContext

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

the class SAMLSignature method signSAMLObject.

/**
     * Adds an enveloped signature to the given element. Then moves the
     * signature element so that it is in the correct position according to the
     * SAML assertion and protocol schema: it must immediately follow any Issuer
     * and precede everything else.
     */
public void signSAMLObject(Element target) throws GeneralSecurityException, XMLSignatureException, MarshalException {
    Reference ref = factory.newReference("#" + target.getAttribute("ID"), factory.newDigestMethod(DigestMethod.SHA1, null), Collections.singletonList(factory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)), null, null);
    SignedInfo signedInfo = factory.newSignedInfo(factory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS, (C14NMethodParameterSpec) null), factory.newSignatureMethod(SignatureMethod.RSA_SHA1, null), Collections.singletonList(ref));
    XMLSignature signature = factory.newXMLSignature(signedInfo, keyInfo);
    DOMSignContext signContext = new DOMSignContext(keyPair.getPrivate(), target);
    signature.sign(signContext);
    // For the result to be schema-valid, we have to move the signature
    // element from its place at the end of the child list to live
    // between Issuer and Subject elements.  So, deep breath, and:
    Node signatureElement = target.getLastChild();
    boolean foundIssuer = false;
    Node elementAfterIssuer = null;
    NodeList children = target.getChildNodes();
    for (int c = 0; c < children.getLength(); ++c) {
        Node child = children.item(c);
        if (foundIssuer) {
            elementAfterIssuer = child;
            break;
        }
        if (child.getNodeType() == Node.ELEMENT_NODE && child.getLocalName().equals("Issuer")) {
            foundIssuer = true;
        }
    }
    // Place after the Issuer, or as first element if no Issuer:
    if (!foundIssuer || elementAfterIssuer != null) {
        target.removeChild(signatureElement);
        target.insertBefore(signatureElement, foundIssuer ? elementAfterIssuer : target.getFirstChild());
    }
}
Also used : Reference(javax.xml.crypto.dsig.Reference) XMLSignature(javax.xml.crypto.dsig.XMLSignature) DOMSignContext(javax.xml.crypto.dsig.dom.DOMSignContext) Node(org.w3c.dom.Node) NodeList(org.w3c.dom.NodeList) SignedInfo(javax.xml.crypto.dsig.SignedInfo) C14NMethodParameterSpec(javax.xml.crypto.dsig.spec.C14NMethodParameterSpec)

Aggregations

DOMSignContext (javax.xml.crypto.dsig.dom.DOMSignContext)18 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)5 Key (java.security.Key)4 Reference (javax.xml.crypto.dsig.Reference)4 XMLSignature (javax.xml.crypto.dsig.XMLSignature)4 XMLSignatureFactory (javax.xml.crypto.dsig.XMLSignatureFactory)4 KeyInfo (javax.xml.crypto.dsig.keyinfo.KeyInfo)4 Node (org.w3c.dom.Node)4 ArrayList (java.util.ArrayList)3 GeneralSecurityException (java.security.GeneralSecurityException)2 InvalidKeyException (java.security.InvalidKeyException)2 PrivateKey (java.security.PrivateKey)2 PublicKey (java.security.PublicKey)2 Map (java.util.Map)2 SecretKey (javax.crypto.SecretKey)2