Example usage for javax.xml.crypto.dsig.dom DOMSignContext DOMSignContext

List of usage examples for javax.xml.crypto.dsig.dom DOMSignContext DOMSignContext

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig.dom DOMSignContext DOMSignContext.

Prototype

public DOMSignContext(KeySelector ks, Node parent) 

Source Link

Document

Creates a DOMSignContext with the specified key selector and parent node.

Usage

From source file:com.fujitsu.dc.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????./* w w w .j  a  v  a 2 s  . c  o  m*/
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

    // Dsig??
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return DcCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

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

@SuppressWarnings("unchecked")
private byte[] getXmlSignatureDigestValue(DigestAlgo digestAlgo, List<DigestInfo> digestInfos,
        List<X509Certificate> signingCertificateChain)
        throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerFactoryConfigurationError,
        TransformerException, IOException, SAXException {
    /*/*from  w  w  w. jav a  2  s. co m*/
     * DOM Document construction.
     */
    Document document = getEnvelopingDocument();
    if (null == document) {
        DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        DocumentBuilder documentBuilder = documentBuilderFactory.newDocumentBuilder();
        document = documentBuilder.newDocument();
    }

    /*
     * Signature context construction.
     */
    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;
        }
    };
    XMLSignContext xmlSignContext = new DOMSignContext(key, document);
    URIDereferencer uriDereferencer = getURIDereferencer();
    if (null != uriDereferencer) {
        xmlSignContext.setURIDereferencer(uriDereferencer);
    }

    if (null != this.signatureNamespacePrefix) {
        /*
         * OOo doesn't like ds namespaces so per default prefixing is off.
         */
        xmlSignContext.putNamespacePrefix(javax.xml.crypto.dsig.XMLSignature.XMLNS,
                this.signatureNamespacePrefix);
    }

    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM",
            new org.apache.jcp.xml.dsig.internal.dom.XMLDSigRI());

    /*
     * Add ds:References that come from signing client local files.
     */
    List<Reference> references = new LinkedList<Reference>();
    addDigestInfosAsReferences(digestInfos, signatureFactory, references);

    /*
     * Invoke the signature facets.
     */
    String localSignatureId;
    if (null == this.signatureId) {
        localSignatureId = "xmldsig-" + UUID.randomUUID().toString();
    } else {
        localSignatureId = this.signatureId;
    }
    List<XMLObject> objects = new LinkedList<XMLObject>();
    for (SignatureFacet signatureFacet : this.signatureFacets) {
        LOG.debug("invoking signature facet: " + signatureFacet.getClass().getSimpleName());
        signatureFacet.preSign(signatureFactory, document, localSignatureId, signingCertificateChain,
                references, objects);
    }

    /*
     * ds:SignedInfo
     */
    SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(getSignatureMethod(digestAlgo), null);
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(getCanonicalizationMethod(), (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);

    /*
     * JSR105 ds:Signature creation
     */
    String signatureValueId = localSignatureId + "-signature-value";
    javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, null,
            objects, localSignatureId, signatureValueId);

    /*
     * ds:Signature Marshalling.
     */
    DOMXMLSignature domXmlSignature = (DOMXMLSignature) xmlSignature;
    Node documentNode = document.getDocumentElement();
    if (null == documentNode) {
        /*
         * In case of an empty DOM document.
         */
        documentNode = document;
    }
    domXmlSignature.marshal(documentNode, this.signatureNamespacePrefix, (DOMCryptoContext) xmlSignContext);

    /*
     * Completion of undigested ds:References in the ds:Manifests.
     */
    for (XMLObject object : objects) {
        LOG.debug("object java type: " + object.getClass().getName());
        List<XMLStructure> objectContentList = object.getContent();
        for (XMLStructure objectContent : objectContentList) {
            LOG.debug("object content java type: " + objectContent.getClass().getName());
            if (false == objectContent instanceof Manifest) {
                continue;
            }
            Manifest manifest = (Manifest) objectContent;
            List<Reference> manifestReferences = manifest.getReferences();
            for (Reference manifestReference : manifestReferences) {
                if (null != manifestReference.getDigestValue()) {
                    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;
        if (null != domReference.getDigestValue()) {
            // ds:Reference with external digest value
            continue;
        }
        domReference.digest(xmlSignContext);
    }

    /*
     * Store the intermediate XML signature document.
     */
    TemporaryDataStorage temporaryDataStorage = getTemporaryDataStorage();
    OutputStream tempDocumentOutputStream = temporaryDataStorage.getTempOutputStream();
    writeDocument(document, tempDocumentOutputStream);
    temporaryDataStorage.setAttribute(SIGNATURE_ID_ATTRIBUTE, localSignatureId);

    /*
     * 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 jcaMessageDigest = MessageDigest.getInstance(digestAlgo.getAlgoId());
    byte[] digestValue = jcaMessageDigest.digest(octets);
    return digestValue;
}

From source file:io.personium.common.auth.token.TransCellAccessToken.java

/**
 * ?SAML????.// w ww.  j a v  a 2  s.c om
 * @return SAML
 */
public String toSamlString() {

    /*
     * Creation of SAML2.0 Document
     * http://docs.oasis-open.org/security/saml/v2.0/saml-core-2.0-os.pdf
     */

    DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
    dbf.setNamespaceAware(true);
    DocumentBuilder builder = null;
    try {
        builder = dbf.newDocumentBuilder();
    } catch (ParserConfigurationException e) {
        // ????????????
        throw new RuntimeException(e);
    }
    Document doc = builder.newDocument();
    Element assertion = doc.createElementNS(URN_OASIS_NAMES_TC_SAML_2_0_ASSERTION, "Assertion");
    doc.appendChild(assertion);
    assertion.setAttribute("ID", this.id);
    assertion.setAttribute("Version", "2.0");

    // Dummy Date
    DateTime dateTime = new DateTime(this.issuedAt);

    assertion.setAttribute("IssueInstant", dateTime.toString());

    // Issuer
    Element issuer = doc.createElement("Issuer");
    issuer.setTextContent(this.issuer);
    assertion.appendChild(issuer);

    // Subject
    Element subject = doc.createElement("Subject");
    Element nameId = doc.createElement("NameID");
    nameId.setTextContent(this.subject);
    Element subjectConfirmation = doc.createElement("SubjectConfirmation");
    subject.appendChild(nameId);
    subject.appendChild(subjectConfirmation);
    assertion.appendChild(subject);

    // Conditions
    Element conditions = doc.createElement("Conditions");
    Element audienceRestriction = doc.createElement("AudienceRestriction");
    for (String aud : new String[] { this.target, this.schema }) {
        Element audience = doc.createElement("Audience");
        audience.setTextContent(aud);
        audienceRestriction.appendChild(audience);
    }
    conditions.appendChild(audienceRestriction);
    assertion.appendChild(conditions);

    // AuthnStatement
    Element authnStmt = doc.createElement("AuthnStatement");
    authnStmt.setAttribute("AuthnInstant", dateTime.toString());
    Element authnCtxt = doc.createElement("AuthnContext");
    Element authnCtxtCr = doc.createElement("AuthnContextClassRef");
    authnCtxtCr.setTextContent("urn:oasis:names:tc:SAML:2.0:ac:classes:PasswordProtectedTransport");
    authnCtxt.appendChild(authnCtxtCr);
    authnStmt.appendChild(authnCtxt);
    assertion.appendChild(authnStmt);

    // AttributeStatement
    Element attrStmt = doc.createElement("AttributeStatement");
    Element attribute = doc.createElement("Attribute");
    for (Role role : this.roleList) {
        Element attrValue = doc.createElement("AttributeValue");
        Attr attr = doc.createAttributeNS("http://www.w3.org/2001/XMLSchema-instance", "type");
        attr.setPrefix("xsi");
        attr.setValue("string");
        attrValue.setAttributeNodeNS(attr);
        attrValue.setTextContent(role.schemeCreateUrlForTranceCellToken(this.issuer));
        attribute.appendChild(attrValue);
    }
    attrStmt.appendChild(attribute);
    assertion.appendChild(attrStmt);

    // Normalization 
    doc.normalizeDocument();

    // Dsig??
    // Create a DOMSignContext and specify the RSA PrivateKey and
    // location of the resulting XMLSignature's parent element.
    DOMSignContext dsc = new DOMSignContext(privKey, doc.getDocumentElement());

    // Create the XMLSignature, but don't sign it yet.
    XMLSignature signature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo);

    // Marshal, generate, and sign the enveloped signature.
    try {
        signature.sign(dsc);
        // ?
        return PersoniumCoreUtils.nodeToString(doc.getDocumentElement());
    } catch (MarshalException e1) {
        // DOM???????
        throw new RuntimeException(e1);
    } catch (XMLSignatureException e1) {
        // ??????????
        throw new RuntimeException(e1);
    }

    /*
     * ------------------------------------------------------------
     * http://tools.ietf.org/html/draft-ietf-oauth-saml2-bearer-10
     * ------------------------------------------------------------ 2.1. Using SAML Assertions as Authorization
     * Grants To use a SAML Bearer Assertion as an authorization grant, use the following parameter values and
     * encodings. The value of "grant_type" parameter MUST be "urn:ietf:params:oauth:grant-type:saml2-bearer" The
     * value of the "assertion" parameter MUST contain a single SAML 2.0 Assertion. The SAML Assertion XML data MUST
     * be encoded using base64url, where the encoding adheres to the definition in Section 5 of RFC4648 [RFC4648]
     * and where the padding bits are set to zero. To avoid the need for subsequent encoding steps (by "application/
     * x-www-form-urlencoded" [W3C.REC-html401-19991224], for example), the base64url encoded data SHOULD NOT be
     * line wrapped and pad characters ("=") SHOULD NOT be included.
     */
}

From source file:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureBST.java

/**
 * Compute the Signature over the references.
 * //  w  ww . j a va2s. c om
 * This method can be called any time after the references were set. See
 * <code>addReferencesToSign()</code>.
 * 
 * @param referenceList The list of references to sign
 * @param prepend Whether to prepend the signature element to the security header
 * @param siblingElement If prepending, then prepend before this sibling Element
 * 
 * @throws WSSecurityException
 */
public void computeSignature(List<javax.xml.crypto.dsig.Reference> referenceList, boolean prepend,
        Element siblingElement) throws WSSecurityException {
    try {
        java.security.Key key;

        if (privateKey == null)
            key = crypto.getPrivateKey(user, password);
        else
            key = privateKey;

        //            if (secretKey == null) {
        //                  key = crypto.getPrivateKey(user, password);
        //            } else {
        //                key = WSSecurityUtil.prepareSecretKey(sigAlgo, secretKey);
        //            }

        SignatureMethod signatureMethod = signatureFactory.newSignatureMethod(sigAlgo, null);
        SignedInfo signedInfo = signatureFactory.newSignedInfo(c14nMethod, signatureMethod, referenceList);

        sig = signatureFactory.newXMLSignature(signedInfo, keyInfo, null,
                getWsConfig().getIdAllocator().createId("SIG-", null), null);

        //
        // Figure out where to insert the signature element
        //
        XMLSignContext signContext = null;
        if (prepend) {
            if (siblingElement == null) {
                Node child = securityHeader.getFirstChild();
                while (child != null && child.getNodeType() != Node.ELEMENT_NODE) {
                    child = child.getNextSibling();
                }
                siblingElement = (Element) child;
            }
            if (siblingElement == null) {
                signContext = new DOMSignContext(key, securityHeader);
            } else {
                signContext = new DOMSignContext(key, securityHeader, siblingElement);
            }
        } else {
            signContext = new DOMSignContext(key, securityHeader);
        }

        signContext.putNamespacePrefix(WSConstants.SIG_NS, WSConstants.SIG_PREFIX);
        if (WSConstants.C14N_EXCL_OMIT_COMMENTS.equals(canonAlgo)) {
            signContext.putNamespacePrefix(WSConstants.C14N_EXCL_OMIT_COMMENTS,
                    WSConstants.C14N_EXCL_OMIT_COMMENTS_PREFIX);
        }
        signContext.setProperty(STRTransform.TRANSFORM_WS_DOC_INFO, wsDocInfo);
        wsDocInfo.setCallbackLookup(callbackLookup);

        // Add the elements to sign to the Signature Context
        wsDocInfo.setTokensOnContext((DOMSignContext) signContext);
        if (secRef != null && secRef.getElement() != null) {
            WSSecurityUtil.storeElementInContext((DOMSignContext) signContext, secRef.getElement());
        }
        sig.sign(signContext);

        signatureValue = sig.getSignatureValue().getValue();
    } catch (Exception ex) {
        log.error(ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, null, null, ex);
    }
}

From source file:be.fedict.eid.tsl.TrustServiceList.java

private void xmlSign(PrivateKey privateKey, X509Certificate certificate, String tslId)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException {//  ww w . j a v a2  s.  c o m
    XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM",
            new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
    LOG.debug("xml signature factory: " + signatureFactory.getClass().getName());
    LOG.debug("loader: " + signatureFactory.getClass().getClassLoader());
    XMLSignContext signContext = new DOMSignContext(privateKey, this.tslDocument.getDocumentElement());
    signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

    DigestMethod digestMethod = signatureFactory.newDigestMethod(DigestMethod.SHA256, null);
    List<Reference> references = new LinkedList<Reference>();
    List<Transform> transforms = new LinkedList<Transform>();
    transforms.add(signatureFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);

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

    String signatureId = "xmldsig-" + UUID.randomUUID().toString();
    List<XMLObject> objects = new LinkedList<XMLObject>();
    addXadesBes(signatureFactory, this.tslDocument, signatureId, certificate, references, objects);

    SignatureMethod signatureMethod;
    if (isJava6u18OrAbove()) {
        signatureMethod = signatureFactory
                .newSignatureMethod("http://www.w3.org/2001/04/xmldsig-more#rsa-sha256", null);
    } else {
        signatureMethod = signatureFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
    }
    CanonicalizationMethod canonicalizationMethod = signatureFactory
            .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
    SignedInfo signedInfo = signatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod, references);

    List<Object> keyInfoContent = new LinkedList<Object>();

    KeyInfoFactory keyInfoFactory = KeyInfoFactory.getInstance();
    List<Object> x509DataObjects = new LinkedList<Object>();
    x509DataObjects.add(certificate);
    x509DataObjects.add(keyInfoFactory.newX509IssuerSerial(certificate.getIssuerX500Principal().toString(),
            certificate.getSerialNumber()));
    X509Data x509Data = keyInfoFactory.newX509Data(x509DataObjects);
    keyInfoContent.add(x509Data);

    KeyValue keyValue;
    try {
        keyValue = keyInfoFactory.newKeyValue(certificate.getPublicKey());
    } catch (KeyException e) {
        throw new RuntimeException("key exception: " + e.getMessage(), e);
    }
    keyInfoContent.add(keyValue);

    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(keyInfoContent);

    String signatureValueId = signatureId + "-signature-value";
    XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo, keyInfo, objects, signatureId,
            signatureValueId);
    xmlSignature.sign(signContext);
}

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

@Override
public byte[] getArchiveTimestampData(int index, Document originalData) throws IOException {

    try {// w w  w .j av  a  2  s. co m
        ByteArrayOutputStream buffer = new ByteArrayOutputStream();

        XMLStructure s = new DOMStructure(signatureElement);
        XMLSignatureFactory factory = XMLSignatureFactory.getInstance("DOM", new XMLDSigRI());
        DOMXMLSignature signature = (DOMXMLSignature) factory.unmarshalXMLSignature(s);

        DOMSignContext signContext = new DOMSignContext(new SpecialPrivateKey(), signatureElement);
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        signContext.setProperty("javax.xml.crypto.dsig.cacheReference", true);
        signContext.setURIDereferencer(new OneExternalFileURIDereferencer("detached-file", originalData));

        // TODO naramsda: check ! Don't let met publish that without further test !!
        // DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        // dbf.setNamespaceAware(true);
        // org.w3c.dom.Document xmlDoc = dbf.newDocumentBuilder().newDocument();
        // signature.marshal(xmlDoc.createElement("test"), "ds", signContext);

        for (Object o : signature.getSignedInfo().getReferences()) {
            DOMReference r = (DOMReference) o;
            InputStream data = r.getDigestInputStream();
            if (data != null) {
                IOUtils.copy(data, buffer);
            }
        }

        List<Node> timeStampNodesXadesA = new LinkedList<Node>();

        Element signedInfo = XMLUtils.getElement(signatureElement, "./ds:SignedInfo");
        timeStampNodesXadesA.add(signedInfo);

        Element signatureValue = XMLUtils.getElement(signatureElement, "./ds:SignatureValue");
        timeStampNodesXadesA.add(signatureValue);

        Element keyInfo = XMLUtils.getElement(signatureElement, "./ds:KeyInfo");
        timeStampNodesXadesA.add(keyInfo);

        Element unsignedSignaturePropertiesNode = getUnsignedSignatureProperties(signatureElement);

        NodeList unsignedProperties = unsignedSignaturePropertiesNode.getChildNodes();
        int count = 0;
        for (int i = 0; i < unsignedProperties.getLength(); i++) {
            if (unsignedProperties.item(i).getNodeType() == Node.ELEMENT_NODE) {
                Element unsignedProperty = (Element) unsignedProperties.item(i);
                if ("ArchiveTimeStamp".equals(unsignedProperty.getLocalName())) {
                    if (count == index) {
                        LOG.info("We only need data up to ArchiveTimeStamp index " + index);
                        break;
                    }
                    count++;
                }
                timeStampNodesXadesA.add(unsignedProperty);
            }
        }

        buffer.write(getC14nValue(timeStampNodesXadesA));

        return buffer.toByteArray();
        //        } catch (ParserConfigurationException e) {
        //            throw new IOException("Error when computing the archive data", e);
    } catch (MarshalException e) {
        throw new IOException("Error when computing the archive data", e);
    } catch (XPathExpressionException e) {
        throw new EncodingException(MSG.ARCHIVE_TIMESTAMP_DATA_ENCODING);
    }
}

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

protected InputStream getToBeSignedStream(Document document, SignatureParameters parameters) {

    try {//from  w  ww  .j ava 2s.c o  m

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);
        DOMXMLSignature signature = createSignature(parameters, doc, document, signContext, signatureValueId);

        /* Output document */
        if (LOG.isLoggable(Level.FINE)) {
            ByteArrayOutputStream logOutput = new ByteArrayOutputStream();
            Result result = new StreamResult(logOutput);
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            Source source = new DOMSource(doc);
            xformer.transform(source, result);
            LOG.fine("Document after digest " + new String(logOutput.toByteArray()));
        }

        DOMSignedInfo domSignedInfo = (DOMSignedInfo) signature.getSignedInfo();
        ByteArrayOutputStream output = new ByteArrayOutputStream();
        domSignedInfo.canonicalize(signContext, output);
        output.close();

        return new ByteArrayInputStream(output.toByteArray());

    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue) {

    try {/* w  w  w  . j  a va2  s .c o m*/

        /* Read the document */
        DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
        dbf.setNamespaceAware(true);
        DocumentBuilder db = dbf.newDocumentBuilder();
        org.w3c.dom.Document doc = null;
        if (parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPED) {
            doc = db.parse(document.openStream());
        } else {
            doc = db.newDocument();
            doc.appendChild(doc.createElement("empty"));
        }

        /* Interceptor */
        SpecialPrivateKey dummyPrivateKey = new SpecialPrivateKey();

        /* Context */
        DOMSignContext signContext = new DOMSignContext(dummyPrivateKey, doc.getDocumentElement());
        signContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

        String signatureValueId = "value-" + computeDeterministicId(parameters);

        DOMXMLSignature domSig = createSignature(parameters, doc, document, signContext, signatureValueId);

        String xpathString = "//ds:SignatureValue[@Id='" + signatureValueId + "']";
        Element signatureValueEl = XMLUtils.getElement(doc, xpathString);

        if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.ECDSA) {
            signatureValueEl.setTextContent(
                    new String(Base64.encode(SignatureECDSA.convertASN1toXMLDSIG(signatureValue))));
        } else if (parameters.getSignatureAlgorithm() == SignatureAlgorithm.DSA) {
            signatureValueEl.setTextContent(new String(Base64.encode(convertASN1toXMLDSIG(signatureValue))));
        } else {
            signatureValueEl.setTextContent(new String(Base64.encode(signatureValue)));
        }

        UnsignedPropertiesType unsigned = createUnsignedXAdESProperties(parameters, domSig, null,
                signatureValueEl);
        if (unsigned != null) {
            JAXBContext xadesJaxbContext = JAXBContext.newInstance(getXades13ObjectFactory().getClass());
            Marshaller m = xadesJaxbContext.createMarshaller();
            JAXBElement<UnsignedPropertiesType> el = getXades13ObjectFactory()
                    .createUnsignedProperties(unsigned);
            m.marshal(el, getXAdESQualifyingProperties(parameters, doc));
        }

        /* Output document */
        ByteArrayOutputStream outputDoc = new ByteArrayOutputStream();
        Result output = new StreamResult(outputDoc);
        Transformer xformer = TransformerFactory.newInstance().newTransformer();
        Source source = new DOMSource(doc);
        xformer.transform(source, output);
        outputDoc.close();

        return new InMemoryDocument(outputDoc.toByteArray());

    } catch (IOException e) {
        throw new RuntimeException(e);
    } catch (JAXBException e) {
        throw new RuntimeException(e);
    } catch (XPathExpressionException e) {
        throw new RuntimeException(e);
    } catch (TransformerException e) {
        throw new RuntimeException(e);
    } catch (SAXException e) {
        throw new RuntimeException(e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (ParserConfigurationException e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Creates signature part of assertion. Uses digest method algorithm
 * corresponding to the signature algorithm used.
 *
 * @param assertion//from   w  w  w  . j av  a2  s  . c o  m
 * @param signatureAlgorithm
 * @return
 */
private Element createSignatureAndSignAssertion(Assertion assertion, SignatureAlgorithm signatureAlgorithm,
        SignInfo signInfo) {
    assert assertion != null;
    assert signatureAlgorithm != null;

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    Element assertionElement = marshallAssertion(assertion);
    List<Transform> transforms = createTransforms();
    Reference ref = createReference(transforms, assertionElement.getAttribute(Assertion.ID_ATTRIB_NAME),
            // here we use the digest method which is corresponding to the
            // signature algorithm used
            signatureAlgorithm.getDigestMethod().toString());
    SignedInfo signedInfo = createSignedInfo(Collections.singletonList(ref), signatureAlgorithm);

    DOMSignContext signingContext = new DOMSignContext(signInfo.getPrivateKey(), assertionElement);
    signingContext.putNamespacePrefix(SignatureConstants.TRANSFORM_C14N_EXCL_OMIT_COMMENTS, "ec");
    signingContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");

    // signature should be the second section in the assertion - after issuer
    // here we are sure that the structure of assertion is as follows:
    // 1) issuer 2) subject
    // we get subject node and enter signature before it and the result is:
    // 1) issuer 2) signature 3) subject
    Node subjectNode = assertionElement.getChildNodes().item(1);
    signingContext.setNextSibling(subjectNode);
    log.debug("Set SigningContext into assertion (after Issuer or as a first child in the assertion DOM).");

    final KeyInfo keyInfo = createKeyInfo(signInfo);
    XMLSignature xmlSignature = factory.newXMLSignature(signedInfo, keyInfo);

    try {
        final long start = System.nanoTime();
        xmlSignature.sign(signingContext);
        perfLog.trace("'signature.sign' took {} ms.", TimeUnit.NANOSECONDS.toMillis(System.nanoTime() - start));
    } catch (MarshalException e) {
        throw new IllegalStateException(e);
    } catch (XMLSignatureException e) {
        throw new IllegalStateException(e);
    }
    log.debug("Created Signature and sign it.");

    return assertionElement;
}

From source file:org.apache.cxf.ws.security.sts.provider.operation.IssueDelegate.java

private void signXML(Element target, String refId, KeyStoreInfo keyStoreInfo) {

    org.apache.xml.security.Init.init();

    XMLSignatureFactory signFactory = XMLSignatureFactory.getInstance(SIGN_FACTORY_TYPE);
    try {//from  w  w  w  . ja  va  2 s  .c  o  m
        DigestMethod method = signFactory.newDigestMethod(DigestMethod.SHA1, null);
        Transform transform = signFactory.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);
        Reference ref = signFactory.newReference('#' + refId, method, Collections.singletonList(transform),
                null, null);

        CanonicalizationMethod canonMethod = signFactory
                .newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null);
        SignatureMethod signMethod = signFactory.newSignatureMethod(SignatureMethod.RSA_SHA1, null);
        SignedInfo si = signFactory.newSignedInfo(canonMethod, signMethod, Collections.singletonList(ref));

        KeyStore.PrivateKeyEntry keyEntry = getKeyEntry(keyStoreInfo);
        if (keyEntry == null) {
            throw new IllegalStateException("Key is not found in keystore. Alias: " + keyStoreInfo.getAlias());
        }

        KeyInfo ki = getKeyInfo(signFactory, keyEntry);

        DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), target);

        XMLSignature signature = signFactory.newXMLSignature(si, ki);

        signature.sign(dsc);

    } catch (Exception e) {
        throw new STSException("Cannot sign xml document: " + e.getMessage(), e);
    }
}