Example usage for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE

List of usage examples for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE.

Prototype

String EXCLUSIVE

To view the source code for javax.xml.crypto.dsig CanonicalizationMethod EXCLUSIVE.

Click Source Link

Document

The <a href="http://www.w3.org/2001/10/xml-exc-c14n#">Exclusive Canonical XML (without comments)</a> canonicalization method algorithm URI.

Usage

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

protected byte[] getC14nValue(List<Node> nodeList) {
    try {/*from  w ww. j a  v a 2  s .  co  m*/
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();
        for (Node node : nodeList) {
            Canonicalizer c14n = Canonicalizer.getInstance(CanonicalizationMethod.EXCLUSIVE);
            buffer.write(c14n.canonicalizeSubtree(node));
        }
        return buffer.toByteArray();
    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (InvalidCanonicalizerException e) {
        throw new RuntimeException("c14n algo error: " + e.getMessage(), e);
    } catch (CanonicalizationException e) {
        throw new RuntimeException("c14n error: " + e.getMessage(), e);
    }
}

From source file:com.bcmcgroup.flare.xmldsig.Xmldsig.java

/**
* Method used to create an enveloped digital signature for an element of a TAXII document.
*
* @param element the element to be signed
* @param keyEntry the PrivateKeyEntry/*from  w  w  w.  j  a v  a  2  s. c om*/
* @param cbIndex the index of the Content_Block if we're signing a Content_Block, otherwise set to -1 if we're signing the root element
* @return the status of the operation
*
* Usage Example:
*   String pks = config.getProperty("pathToPublisherKeyStore");
*    String pksPw = FLAREclientUtil.decrypt(config.getProperty("publisherKeyStorePassword"));
*    String keyName = config.getProperty("publisherKeyName");
*    String keyPW = FLAREclientUtil.decrypt(config.getProperty("publisherKeyPassword"));
*   PrivateKeyEntry keyEntry =  FLAREclientUtil.getKeyEntry(pks, pksPw, keyName, keyPW);
*   List<Integer> statusList = Xmldsig.sign(rootElement, keyEntry, -1);
*/
private static boolean sign(Element element, PrivateKeyEntry keyEntry, int cbIndex) {
    element.normalize();
    boolean status = false;

    //Create XML Signature Factory
    XMLSignatureFactory xmlSigFactory = XMLSignatureFactory.getInstance("DOM");
    PublicKey publicKey = ClientUtil.getPublicKey(keyEntry);
    PrivateKey privateKey = keyEntry.getPrivateKey();
    DOMSignContext dsc = new DOMSignContext(privateKey, element);
    dsc.setDefaultNamespacePrefix("ds");
    dsc.setURIDereferencer(new MyURIDereferencer(element));
    SignedInfo si = null;
    DigestMethod dm = null;
    SignatureMethod sm = null;
    KeyInfo ki = null;
    X509Data xd;
    List<Serializable> x509Content = new ArrayList<>();
    try {
        String algorithm = publicKey.getAlgorithm();
        X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
        x509Content.add(cert.getSubjectX500Principal().getName());
        x509Content.add(cert);
        String algorithmName = cert.getSigAlgName();
        if (algorithm.toUpperCase().contains("RSA")) {
            if (algorithmName.toUpperCase().contains("SHA1")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA1, null);
                sm = xmlSigFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
            } else if (algorithmName.toUpperCase().contains("SHA2")) {
                dm = xmlSigFactory.newDigestMethod(DigestMethod.SHA256, null);
                sm = xmlSigFactory.newSignatureMethod(RSA_SHA256_URI, null);
            } else {
                logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
            }
            CanonicalizationMethod cm;
            if (cbIndex != -1) {
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(//*[local-name()='Content_Block'][" + cbIndex
                        + "]/*[local-name()='Content'][1]/*)";
                List<Reference> references = Collections.singletonList(xmlSigFactory.newReference(refUri, dm));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            } else {
                List<Transform> transforms = new ArrayList<>(2);
                transforms.add(xmlSigFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
                transforms.add(xmlSigFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                        (TransformParameterSpec) null));
                cm = xmlSigFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                        (C14NMethodParameterSpec) null);
                String refUri = "#xpointer(/*)";
                List<Reference> references = Collections
                        .singletonList(xmlSigFactory.newReference(refUri, dm, transforms, null, null));
                si = xmlSigFactory.newSignedInfo(cm, sm, references);
            }
            KeyInfoFactory kif = xmlSigFactory.getKeyInfoFactory();
            xd = kif.newX509Data(x509Content);
            ki = kif.newKeyInfo(Collections.singletonList(xd));
        } else {
            logger.error("Error in digital signature application. " + algorithmName + " is not supported.");
        }
    } catch (NoSuchAlgorithmException ex) {
        logger.error("NoSuchAlgorithm Exception when attempting to digitally sign a document.");
    } catch (InvalidAlgorithmParameterException ex) {
        logger.error("InvalidAlgorithmParameter Exception when attempting to digitally sign a document.");
    }

    // Create a new XML Signature
    XMLSignature signature = xmlSigFactory.newXMLSignature(si, ki);
    try {
        // Sign the document
        signature.sign(dsc);
        status = true;
    } catch (MarshalException ex) {
        logger.error("MarshalException when attempting to digitally sign a document.");
    } catch (XMLSignatureException ex) {
        logger.error("XMLSignature Exception when attempting to digitally sign a document.");
    } catch (Exception e) {
        logger.error("General exception when attempting to digitally sign a document.");
    }
    return status;
}

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

/**
 * Main constructor./* ww w .j a v  a2 s .  c o m*/
 * 
 * @param timeStampService
 *            the time-stamp service used for XAdES-T and XAdES-X.
 * @param revocationDataService
 *            the optional revocation data service used for XAdES-C and
 *            XAdES-X-L. When <code>null</code> the signature will be
 *            limited to XAdES-T only.
 * @param digestAlgorithm
 *            the digest algorithm to be used for construction of the
 *            XAdES-X-L elements.
 */
public XAdESXLSignatureFacet(TimeStampService timeStampService, RevocationDataService revocationDataService,
        DigestAlgo digestAlgorithm) {
    this.objectFactory = new ObjectFactory();
    this.c14nAlgoId = CanonicalizationMethod.EXCLUSIVE;
    this.digestAlgorithm = digestAlgorithm;
    this.timeStampService = timeStampService;
    this.revocationDataService = revocationDataService;
    this.xmldsigObjectFactory = new be.fedict.eid.applet.service.signer.jaxb.xmldsig.ObjectFactory();
    this.xades141ObjectFactory = new be.fedict.eid.applet.service.signer.jaxb.xades141.ObjectFactory();

    try {
        JAXBContext context = JAXBContext
                .newInstance(be.fedict.eid.applet.service.signer.jaxb.xades141.ObjectFactory.class);
        this.marshaller = context.createMarshaller();
        this.marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        this.marshaller.setProperty("com.sun.xml.bind.namespacePrefixMapper", new XAdESNamespacePrefixMapper());
    } catch (JAXBException e) {
        throw new RuntimeException("JAXB error: " + e.getMessage(), e);
    }

    try {
        this.certificateFactory = CertificateFactory.getInstance("X.509");
    } catch (CertificateException e) {
        throw new RuntimeException("X509 JCA error: " + e.getMessage(), e);
    }

    try {
        this.datatypeFactory = DatatypeFactory.newInstance();
    } catch (DatatypeConfigurationException e) {
        throw new RuntimeException("datatype config error: " + e.getMessage(), e);
    }
}

From source file:es.gob.afirma.signers.ooxml.be.fedict.eid.applet.service.signer.AbstractXmlSignatureService.java

protected String getCanonicalizationMethod() {
    return CanonicalizationMethod.EXCLUSIVE;
}

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

protected XAdESTimeStampType createXAdESTimeStamp(DigestAlgorithm algorithm, byte[] digest) throws IOException {

    LOG.info("Create timestamp for digest " + new String(Hex.encodeHex(digest)));
    TimeStampResponse resp = tspSource.getTimeStampResponse(algorithm, digest);
    byte[] timeStampToken = resp.getTimeStampToken().getEncoded();

    XAdESTimeStampType xadesTimeStamp = xadesObjectFactory.createXAdESTimeStampType();
    CanonicalizationMethodType c14nMethod = getXmldsigObjectFactory().createCanonicalizationMethodType();
    c14nMethod.setAlgorithm(CanonicalizationMethod.EXCLUSIVE);
    xadesTimeStamp.setCanonicalizationMethod(c14nMethod);
    xadesTimeStamp.setId("time-stamp-" + UUID.randomUUID().toString());

    EncapsulatedPKIDataType encapsulatedTimeStamp = xadesObjectFactory.createEncapsulatedPKIDataType();
    encapsulatedTimeStamp.setValue(timeStampToken);
    encapsulatedTimeStamp.setId("time-stamp-token-" + UUID.randomUUID().toString());
    List<Serializable> timeStampContent = xadesTimeStamp.getEncapsulatedTimeStampOrXMLTimeStamp();
    timeStampContent.add(encapsulatedTimeStamp);

    return xadesTimeStamp;
}

From source file:com.vmware.identity.sts.ws.SignatureValidator.java

/**
 * Validate the signature reference transforms are as expected.
 * (Only the exclusive canonicalization transform is supported).
 *
 * @param reference signature reference to validate the transforms of.
 * @throws XMLSignatureException when validation fails.
 *//*from   w w w. ja  va  2s  .  c  o m*/
private void validateReferenceTransforms(Reference reference) throws XMLSignatureException {
    assert reference != null;

    List<Transform> transforms = reference.getTransforms();
    if ((transforms != null) && (transforms.size() > 1)) {
        throw new XMLSignatureException(
                "Unexpected number of transforms. Only an exclusive canonicalization is supported.");
    } else if ((transforms != null) && (transforms.size() > 0)
            && (!CanonicalizationMethod.EXCLUSIVE.equals(transforms.get(0).getAlgorithm()))) {
        throw new XMLSignatureException(
                String.format("Unexpected Transform '%s'. Only an exclusive canonicalization is supported.",
                        transforms.get(0).getAlgorithm()));
    }
}

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

protected String getCanonicalizationMethod() {
    // CanonicalizationMethod.INCLUSIVE fails for OOo
    //return CanonicalizationMethod.INCLUSIVE;
    return CanonicalizationMethod.EXCLUSIVE;
}

From source file:no.digipost.api.interceptors.Wss4jInterceptor.java

@Override
protected void validateMessage(final SoapMessage soapMessage, final MessageContext messageContext)
        throws WsSecurityValidationException {
    if (logger.isDebugEnabled()) {
        logger.debug("Validating message [" + soapMessage + "] with actions [" + validationActions + "]");
    }//w w  w . j  av  a  2  s.c  o m

    if (validationActionsVector.isEmpty() || validationActionsVector.contains(WSConstants.NO_SECURITY)) {
        return;
    }

    Document envelopeAsDocument = soapMessage.getDocument();

    // Header processing

    try {
        RequestData requestData = new RequestData();
        requestData.setAttachmentCallbackHandler(new AttachmentCallbackHandler(soapMessage));
        requestData.setWssConfig(wssConfig);
        requestData.setSigVerCrypto(validationSignatureCrypto);
        requestData.setCallbackHandler(validationCallbackHandler);
        requestData.setSubjectCertConstraints(OrgnummerExtractor.PATTERNS);
        AlgorithmSuite algorithmSuite = new AlgorithmSuite();
        algorithmSuite.addDigestAlgorithm(digestAlgorithm);
        algorithmSuite.addSignatureMethod(securementSignatureAlgorithm);
        algorithmSuite.addC14nAlgorithm(CanonicalizationMethod.EXCLUSIVE);
        //algorithmSuite.addTransformAlgorithm("http://www.w3.org/2001/10/xml-exc-c14n#");
        //algorithmSuite.addTransformAlgorithm("http://docs.oasis-open.org/wss/2004/XX/oasis-2004XX-wss-swa-profile-1.0#Attachment-Complete-Transform");
        requestData.setAlgorithmSuite(algorithmSuite);
        requestData.setEnableTimestampReplayCache(false);

        List<WSSecurityEngineResult> results = securityEngine.processSecurityHeader(envelopeAsDocument,
                validationActor, requestData);

        // Results verification
        if (CollectionUtils.isEmpty(results)) {
            throw new Wss4jSecurityValidationException("No WS-Security header found");
        }

        updateMessageContextWithCertificate(messageContext, results);

        checkResults(results, validationActionsVector);

        validateEbmsMessagingIsSigned(envelopeAsDocument, results);
        validateTimestampIsSigned(envelopeAsDocument, results);

        // puts the results in the context
        // useful for Signature Confirmation
        updateContextWithResults(messageContext, results);

        verifyCertificateTrust(results);

        verifyTimestamp(results);
    } catch (WSSecurityException ex) {
        throw new Wss4jSecurityValidationException(ex.getMessage(), ex);
    }

    soapMessage.setDocument(envelopeAsDocument);

    soapMessage.getEnvelope().getHeader().removeHeaderElement(WS_SECURITY_NAME);
}

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

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

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

    signContext.setURIDereferencer(new URIDereferencer() {

        @Override//from  ww  w . j ava  2s  .  c om
        public Data dereference(URIReference uriReference, XMLCryptoContext context)
                throws URIReferenceException {
            final XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
            Data data = fac.getURIDereferencer().dereference(uriReference, context);
            return data;
        }
    });

    Map<String, String> xpathNamespaceMap = new HashMap<String, String>();
    xpathNamespaceMap.put("ds", XMLSignature.XMLNS);

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

    /* The first reference concern the whole document */
    List<Transform> transforms = new ArrayList<Transform>();
    transforms.add(fac.newTransform(CanonicalizationMethod.ENVELOPED, (TransformParameterSpec) null));

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    org.w3c.dom.Document empty;
    try {
        empty = dbf.newDocumentBuilder().newDocument();
    } catch (ParserConfigurationException e1) {
        throw new RuntimeException(e1);
    }
    Element xpathEl = empty.createElementNS(XMLSignature.XMLNS, "XPath");
    xpathEl.setTextContent("");
    empty.adoptNode(xpathEl);
    XPathFilterParameterSpec specs = new XPathFilterParameterSpec("not(ancestor-or-self::ds:Signature)");
    DOMTransform t = (DOMTransform) fac.newTransform("http://www.w3.org/TR/1999/REC-xpath-19991116", specs);

    transforms.add(t);
    DigestMethod digestMethod = fac.newDigestMethod(params.getDigestAlgorithm().getXmlId(), null);
    Reference reference = fac.newReference("", digestMethod, transforms, null, "xml_ref_id");
    references.add(reference);

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

    String xadesSignedPropertiesId = "xades-" + computeDeterministicId(params);
    QualifyingPropertiesType qualifyingProperties = createXAdESQualifyingProperties(params,
            xadesSignedPropertiesId, reference, MimeType.XML);
    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);

    Reference xadesreference = fac.newReference("#" + xadesSignedPropertiesId, digestMethod,
            Collections.singletonList(
                    fac.newTransform(CanonicalizationMethod.INCLUSIVE, (TransformParameterSpec) null)),
            XADES_TYPE, null);
    references.add(xadesreference);

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

    CanonicalizationMethod canonicalizationMethod = fac
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (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. */
    signature.marshal(doc.getDocumentElement(), "ds", signContext);

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

    digestReferences(signContext, references);

    return signature;

}

From source file:eu.europa.ec.markt.dss.validation.xades.XAdESSignature.java

private byte[] getC14nValue(Node node) {
    try {/*  w  w  w. j  a  v a 2 s  . com*/
        Canonicalizer c14n = Canonicalizer.getInstance(CanonicalizationMethod.EXCLUSIVE);
        return c14n.canonicalizeSubtree(node);
    } catch (InvalidCanonicalizerException e) {
        throw new RuntimeException("c14n algo error: " + e.getMessage(), e);
    } catch (CanonicalizationException e) {
        throw new RuntimeException("c14n error: " + e.getMessage(), e);
    }
}