Example usage for javax.xml.crypto.dsig XMLSignatureFactory newDigestMethod

List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory newDigestMethod

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig XMLSignatureFactory newDigestMethod.

Prototype

public abstract DigestMethod newDigestMethod(String algorithm, DigestMethodParameterSpec params)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException;

Source Link

Document

Creates a DigestMethod for the specified algorithm URI and parameters.

Usage

From source file:be.e_contract.mycarenet.xkms.ProofOfPossessionSignatureSOAPHandler.java

private void addSignature(Element parentElement) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {
    DOMSignContext domSignContext = new DOMSignContext(this.sessionKey.getPrivate(), parentElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    Reference reference = xmlSignatureFactory.newReference("#" + this.prototypeKeyBindingId,
            xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                    (TransformParameterSpec) null)),
            null, null);//www .j  av  a  2s.  co  m

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null),
            xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
            Collections.singletonList(reference));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, null);
    xmlSignature.sign(domSignContext);
}

From source file:be.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java

private void addSignature(Element parentElement) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {
    DOMSignContext domSignContext = new DOMSignContext(this.authnPrivateKey, parentElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    Reference reference = xmlSignatureFactory.newReference(this.referenceUri,
            xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                    (TransformParameterSpec) null)),
            null, null);//from   ww  w  .jav a 2  s  .c  om

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null),
            xmlSignatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
            Collections.singletonList(reference));

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
            .singletonList(keyInfoFactory.newX509Data(Collections.singletonList(this.authnCertificate))));

    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);
    xmlSignature.sign(domSignContext);
}

From source file:be.fedict.eid.applet.service.signer.odf.ODFSignatureFacet.java

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    try {//from   ww  w. ja v a 2  s  . co  m
        URL odfUrl = this.signatureService.getOpenDocumentURL();
        InputStream odfInputStream = odfUrl.openStream();
        ZipInputStream odfZipInputStream = new ZipInputStream(odfInputStream);
        ZipEntry zipEntry;

        DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);

        while (null != (zipEntry = odfZipInputStream.getNextEntry())) {
            if (ODFUtil.isToBeSigned(zipEntry)) {
                String name = zipEntry.getName();
                /*
                 * Whitespaces are illegal in URIs
                 * 
                 * Note that OOo 3.0/3.1 seems to have a bug, seems like the
                 * OOo signature verification doesn't convert it back to
                 * whitespace, to be investigated
                 */
                String uri = name.replaceAll(" ", "%20");

                Reference reference;
                if (name.endsWith(".xml") && !isEmpty(odfZipInputStream)) {
                    /* apply transformation on non-empty XML files only */
                    List<Transform> transforms = new LinkedList<Transform>();
                    Transform transform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
                            (TransformParameterSpec) null);
                    transforms.add(transform);
                    reference = signatureFactory.newReference(uri, digestMethod, transforms, null, null);
                } else {
                    reference = signatureFactory.newReference(uri, digestMethod);
                }
                references.add(reference);
                LOG.debug("entry: " + name);
            }
        }
    } catch (IOException e) {
        LOG.error("IO error: " + e.getMessage(), e);
    } catch (Exception e) {
        LOG.error("Error: " + e.getMessage(), e);
    }
}

From source file:be.fedict.eid.idp.common.saml2.Saml2Util.java

/**
 * Sign DOM document/*from   ww  w  .  ja  v  a  2 s  .  c  o m*/
 * 
 * @param documentElement
 *            document to be signed
 * @param nextSibling
 *            next sibling in document, dsig is added before this one
 * @param identity
 *            Identity to sign with
 * @throws NoSuchAlgorithmException
 *             signing algorithm not found
 * @throws InvalidAlgorithmParameterException
 *             invalid signing algo param
 * @throws MarshalException
 *             error marshalling signature
 * @throws XMLSignatureException
 *             error during signing
 */
public static void signDocument(Element documentElement, Node nextSibling, KeyStore.PrivateKeyEntry identity)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {

    // get document ID
    String documentId = documentElement.getAttribute("ID");
    LOG.debug("document ID=" + documentId);

    // fix for recent versions of Apache xmlsec.
    documentElement.setIdAttribute("ID", true);

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");

    XMLSignContext signContext = new DOMSignContext(identity.getPrivateKey(), documentElement, nextSibling);
    signContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS, "ds");
    javax.xml.crypto.dsig.DigestMethod digestMethod = signatureFactory
            .newDigestMethod(javax.xml.crypto.dsig.DigestMethod.SHA1, null);

    List<javax.xml.crypto.dsig.Transform> transforms = new LinkedList<javax.xml.crypto.dsig.Transform>();
    transforms.add(signatureFactory.newTransform(javax.xml.crypto.dsig.Transform.ENVELOPED,
            (TransformParameterSpec) null));
    javax.xml.crypto.dsig.Transform exclusiveTransform = signatureFactory
            .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);

    Reference reference = signatureFactory.newReference("#" + documentId, digestMethod, transforms, null, null);

    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            Collections.singletonList(reference));

    List<Object> keyInfoContent = new LinkedList<Object>();
    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance();
    List<Object> x509DataObjects = new LinkedList<Object>();

    for (X509Certificate certificate : Saml2Util.getCertificateChain(identity)) {
        x509DataObjects.add(certificate);
    }
    javax.xml.crypto.dsig.keyinfo.X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
    keyInfoContent.add(x509Data);
    javax.xml.crypto.dsig.keyinfo.KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);

    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo);
    xmlSignature.sign(signContext);
}

From source file:be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java

private void addDigestInfosAsReferences(List<DigestInfo> digestInfos, XMLSignatureFactory signatureFactory,
        List<Reference> references)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MalformedURLException {
    if (null == digestInfos) {
        return;/*  w w  w. j a v a  2s.  c o  m*/
    }
    for (DigestInfo digestInfo : digestInfos) {
        byte[] documentDigestValue = digestInfo.digestValue;

        DigestMethod digestMethod = signatureFactory.newDigestMethod(getXmlDigestAlgo(digestInfo.digestAlgo),
                null);

        String uri = FilenameUtils.getName(new File(digestInfo.description).toURI().toURL().getFile());

        Reference reference = signatureFactory.newReference(uri, digestMethod, null, null, null,
                documentDigestValue);
        references.add(reference);
    }
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private void addManifestReferences(XMLSignatureFactory signatureFactory, Document document,
        List<Reference> manifestReferences)
        throws IOException, JAXBException, NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    CTTypes contentTypes = getContentTypes();
    List<String> relsEntryNames = getRelsEntryNames();
    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Set<String> digestedPartNames = new HashSet<String>();
    for (String relsEntryName : relsEntryNames) {
        CTRelationships relationships = getRelationships(relsEntryName);
        List<CTRelationship> relationshipList = relationships.getRelationship();
        RelationshipTransformParameterSpec parameterSpec = new RelationshipTransformParameterSpec();
        for (CTRelationship relationship : relationshipList) {
            String relationshipType = relationship.getType();
            STTargetMode targetMode = relationship.getTargetMode();
            if (null != targetMode) {
                LOG.debug("TargetMode: " + targetMode.name());
                if (targetMode == STTargetMode.EXTERNAL) {
                    /*//from w  w  w . ja v  a2s  .  c om
                     * ECMA-376 Part 2 - 3rd edition
                     * 
                     * 13.2.4.16 Manifest Element
                     * 
                     * "The producer shall not create a Manifest element that references any data outside of the package."
                     */
                    continue;
                }
            }
            if (false == OOXMLSignatureFacet.isSignedRelationship(relationshipType)) {
                continue;
            }
            String baseUri = "/" + relsEntryName.substring(0, relsEntryName.indexOf("_rels/"));
            String relationshipTarget = relationship.getTarget();
            String partName = FilenameUtils
                    .separatorsToUnix(FilenameUtils.normalize(baseUri + relationshipTarget));
            LOG.debug("part name: " + partName);
            String relationshipId = relationship.getId();
            parameterSpec.addRelationshipReference(relationshipId);
            String contentType = getContentType(contentTypes, partName);
            if (relationshipType.endsWith("customXml")) {
                if (false == contentType.equals("inkml+xml") && false == contentType.equals("text/xml")) {
                    LOG.debug("skipping customXml with content type: " + contentType);
                    continue;
                }
            }
            if (false == digestedPartNames.contains(partName)) {
                /*
                 * We only digest a part once.
                 */
                Reference reference = signatureFactory.newReference(partName + "?ContentType=" + contentType,
                        digestMethod);
                manifestReferences.add(reference);
                digestedPartNames.add(partName);
            }
        }
        if (false == parameterSpec.getSourceIds().isEmpty()) {
            List<Transform> transforms = new LinkedList<Transform>();
            transforms.add(
                    signatureFactory.newTransform(RelationshipTransformService.TRANSFORM_URI, parameterSpec));
            transforms.add(signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
                    (TransformParameterSpec) null));
            Reference reference = signatureFactory.newReference(
                    "/" + relsEntryName
                            + "?ContentType=application/vnd.openxmlformats-package.relationships+xml",
                    digestMethod, transforms, null, null);

            manifestReferences.add(reference);
        }
    }
}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createDetached(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, final Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    // Create references
    List<Reference> references = new ArrayList<Reference>();
    addReferences(documentIterator(inside), references, digestMethod, fac);
    // Create repository
    signContext.setURIDereferencer(new NameBasedDocumentRepository(inside, fac));

    List<XMLObject> objects = new ArrayList<XMLObject>();

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, references, inside);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");
    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);
    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);//from   www  .  j  av  a 2s . c  o m

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:eu.europa.ec.markt.dss.signature.xades.XAdESProfileBES.java

private DOMXMLSignature createEnveloping(SignatureParameters params, DOMSignContext signContext,
        org.w3c.dom.Document doc, String signatureId, String signatureValueId, Document inside)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, JAXBException, MarshalException,
        XMLSignatureException, ParserConfigurationException, IOException {

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());

    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);

    List<XMLObject> objects = new ArrayList<XMLObject>();
    List<Reference> references = new ArrayList<Reference>();

    byte[] b64data = Base64.encode(IOUtils.toByteArray(inside.openStream()));

    List<Transform> transforms = new ArrayList<Transform>();
    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", "http://www.w3.org/2000/09/xmldsig#");
    Transform exclusiveTransform = fac.newTransform(CanonicalizationMethod.BASE64,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);/*w w  w  .java 2 s  . c  o  m*/

    /* The first reference concern the whole document */
    Reference reference = fac.newReference("#signed-data-" + computeDeterministicId(params), digestMethod,
            transforms, null, "signed-data-ref");
    references.add(reference);

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.PLAIN);
    qualifyingProperties.setTarget("#" + signatureId);

    Node marshallNode = doc.createElement("marshall-node");

    JAXBContext jaxbContext = JAXBContext.newInstance(ObjectFactory.class);
    Marshaller marshaller = jaxbContext.createMarshaller();
    marshaller.marshal(xades13ObjectFactory.createQualifyingProperties(qualifyingProperties), marshallNode);

    Element qualifier = (Element) marshallNode.getFirstChild();

    // add XAdES ds:Object
    List<XMLStructure> xadesObjectContent = new LinkedList<XMLStructure>();
    xadesObjectContent.add(new DOMStructure(marshallNode.getFirstChild()));
    XMLObject xadesObject = fac.newXMLObject(xadesObjectContent, null, null, null);
    objects.add(xadesObject);

    List<Transform> xadesTranforms = new ArrayList<Transform>();
    Transform exclusiveTransform2 = fac.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    xadesTranforms.add(exclusiveTransform2);
    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod, xadesTranforms,
            XADES_TYPE, null);
    references.add(xadesreference);

    /* Signed Info */
    SignatureMethod sm = fac.newSignatureMethod(
            params.getSignatureAlgorithm().getXMLSignatureAlgorithm(params.getDigestAlgorithm()), null);

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = fac.newSignedInfo(canonicalizationMethod, sm, references);

    /* Creation of signature */
    KeyInfoFactory keyFactory = KeyInfoFactory.getInstance("DOM", new XMLDSigRI());

    List<Object> infos = new ArrayList<Object>();
    List<X509Certificate> certs = new ArrayList<X509Certificate>();
    certs.add(params.getSigningCertificate());
    if (params.getCertificateChain() != null) {
        for (X509Certificate c : params.getCertificateChain()) {
            if (!c.getSubjectX500Principal().equals(params.getSigningCertificate().getSubjectX500Principal())) {
                certs.add(c);
            }
        }
    }
    infos.add(keyFactory.newX509Data(certs));
    KeyInfo keyInfo = keyFactory.newKeyInfo(infos);

    DOMXMLSignature signature = (DOMXMLSignature) fac.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);

    /* Marshall the signature to permit the digest. Need to be done before digesting the references. */
    doc.removeChild(doc.getDocumentElement());
    signature.marshal(doc, "ds", signContext);

    Element dsObject = doc.createElementNS(XMLSignature.XMLNS, "Object");
    dsObject.setAttribute("Id", "signed-data-" + computeDeterministicId(params));
    dsObject.setTextContent(new String(b64data));
    doc.getDocumentElement().appendChild(dsObject);

    signContext.setIdAttributeNS((Element) qualifier.getFirstChild(), null, "Id");
    signContext.setIdAttributeNS(dsObject, null, "Id");

    digestReferences(signContext, references);

    return signature;

}

From source file:com.vmware.identity.saml.impl.TokenAuthorityImpl.java

/**
 * Creates a Reference part of Signature section
 *
 * @param transforms// ww  w  . j a  v a2  s. c  o m
 * @param id
 * @param digestMethod
 * @return
 * @throws NoSuchAlgorithmException
 * @throws InvalidAlgorithmParameterException
 */
private Reference createReference(List<Transform> transforms, String id, String digestMethod) {
    assert transforms != null;
    assert id != null;
    assert digestMethod != null;

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();

    javax.xml.crypto.dsig.DigestMethod digestAlgorithm;
    try {
        digestAlgorithm = factory.newDigestMethod(digestMethod, null);
    } catch (Exception e) {
        throw new IllegalStateException("Cannot create digest method object.", e);
    }

    log.debug("Created reference with id: {} and digestMethod: {}", id, digestMethod);
    return factory.newReference("#" + id, digestAlgorithm, transforms, null, null);
}

From source file:be.fedict.eid.applet.service.signer.ooxml.OOXMLSignatureFacet.java

private void addManifestObject(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    Manifest manifest = constructManifest(signatureFactory, document);
    String objectId = "idPackageObject"; // really has to be this value.
    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
    objectContent.add(manifest);// w ww.j av  a 2 s  .  c om

    addSignatureTime(signatureFactory, document, signatureId, objectContent);

    objects.add(signatureFactory.newXMLObject(objectContent, objectId, null, null));

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + objectId, digestMethod, null,
            "http://www.w3.org/2000/09/xmldsig#Object", null);
    references.add(reference);
}