Example usage for javax.xml.crypto.dom DOMStructure DOMStructure

List of usage examples for javax.xml.crypto.dom DOMStructure DOMStructure

Introduction

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

Prototype

public DOMStructure(Node node) 

Source Link

Document

Creates a DOMStructure containing the specified node.

Usage

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

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("pre sign");

    Element dateElement = document.createElementNS("", "dc:date");
    dateElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:dc", "http://purl.org/dc/elements/1.1/");
    DateTime dateTime = new DateTime(DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String now = fmt.print(dateTime);
    now = now.substring(0, now.indexOf("Z"));
    LOG.debug("now: " + now);
    dateElement.setTextContent(now);//from  w  w  w.ja  v a  2s. c  o  m

    String signaturePropertyId = "sign-prop-" + UUID.randomUUID().toString();
    List<XMLStructure> signaturePropertyContent = new LinkedList<XMLStructure>();
    signaturePropertyContent.add(new DOMStructure(dateElement));
    SignatureProperty signatureProperty = signatureFactory.newSignatureProperty(signaturePropertyContent,
            "#" + signatureId, signaturePropertyId);

    List<XMLStructure> objectContent = new LinkedList<XMLStructure>();
    List<SignatureProperty> signaturePropertiesContent = new LinkedList<SignatureProperty>();
    signaturePropertiesContent.add(signatureProperty);
    SignatureProperties signatureProperties = signatureFactory
            .newSignatureProperties(signaturePropertiesContent, null);
    objectContent.add(signatureProperties);

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

    DigestMethod digestMethod = signatureFactory.newDigestMethod(this.digestAlgo.getXmlAlgoId(), null);
    Reference reference = signatureFactory.newReference("#" + signaturePropertyId, digestMethod);
    references.add(reference);
}

From source file:no.digipost.signature.client.asice.signature.CreateSignature.java

public Signature createSignature(final List<ASiCEAttachable> attachedFiles,
        final KeyStoreConfig keyStoreConfig) {
    XMLSignatureFactory xmlSignatureFactory = getSignatureFactory();
    SignatureMethod signatureMethod = getSignatureMethod(xmlSignatureFactory);

    // Create signature references for all files
    List<Reference> references = references(xmlSignatureFactory, attachedFiles);

    // Create signature reference for XAdES properties
    references.add(xmlSignatureFactory.newReference("#SignedProperties", sha256DigestMethod,
            singletonList(canonicalXmlTransform), signedPropertiesType, null));

    // Generate XAdES document to sign, information about the key used for signing and information about what's signed
    Document document = createXAdESProperties.createPropertiesToSign(attachedFiles,
            keyStoreConfig.getCertificate());

    KeyInfo keyInfo = keyInfo(xmlSignatureFactory, keyStoreConfig.getCertificateChain());
    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            references);//from   www. j  a  va  2 s .  c  o m

    // Define signature over XAdES document
    XMLObject xmlObject = xmlSignatureFactory
            .newXMLObject(singletonList(new DOMStructure(document.getDocumentElement())), null, null, null);
    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo,
            singletonList(xmlObject), "Signature", null);

    try {
        xmlSignature.sign(new DOMSignContext(keyStoreConfig.getPrivateKey(), document));
    } catch (MarshalException e) {
        throw new XmlConfigurationException("failed to read ASiC-E XML for signing", e);
    } catch (XMLSignatureException e) {
        throw new XmlConfigurationException("Failed to sign ASiC-E element.", e);
    }

    wrapSignatureInXADeSEnvelope(document);

    ByteArrayOutputStream outputStream;
    try {
        outputStream = new ByteArrayOutputStream();
        Transformer transformer = transformerFactory.newTransformer();
        schema.newValidator().validate(new DOMSource(document));
        transformer.transform(new DOMSource(document), new StreamResult(outputStream));
    } catch (TransformerException e) {
        throw new ConfigurationException("Unable to serialize XML.", e);
    } catch (SAXException e) {
        throw new XmlValidationException(
                "Failed to validate generated signature.xml. Verify that the input is valid and that there are no illegal symbols in file names etc.",
                e);
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
    return new Signature(outputStream.toByteArray());
}

From source file:no.difi.sdp.client.asice.signature.CreateSignature.java

public Signature createSignature(final Noekkelpar noekkelpar, final List<AsicEAttachable> attachedFiles)
        throws XmlValideringException {
    XMLSignatureFactory xmlSignatureFactory = getSignatureFactory();
    SignatureMethod signatureMethod = getSignatureMethod(xmlSignatureFactory);

    // Lag signatur-referanse for alle filer
    List<Reference> references = references(xmlSignatureFactory, attachedFiles);

    // Lag signatur-referanse for XaDES properties
    references.add(xmlSignatureFactory.newReference("#SignedProperties", sha256DigestMethod,
            singletonList(canonicalXmlTransform), signedPropertiesType, null));

    // Generer XAdES-dokument som skal signeres, informasjon om nkkel brukt til signering og informasjon om hva som er signert
    Document document = createXAdESProperties.createPropertiesToSign(attachedFiles, noekkelpar.getSertifikat());

    KeyInfo keyInfo = keyInfo(xmlSignatureFactory, noekkelpar.getCertificateChain());
    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(canonicalizationMethod, signatureMethod,
            references);//from  w w w .j  av a2s.  co m

    // Definer signatur over XAdES-dokument
    XMLObject xmlObject = xmlSignatureFactory
            .newXMLObject(singletonList(new DOMStructure(document.getDocumentElement())), null, null, null);
    XMLSignature xmlSignature = xmlSignatureFactory.newXMLSignature(signedInfo, keyInfo,
            singletonList(xmlObject), "Signature", null);

    try {
        xmlSignature.sign(new DOMSignContext(noekkelpar.getPrivateKey(), document));
    } catch (MarshalException e) {
        throw new XmlKonfigurasjonException("Klarte ikke  lese ASiC-E XML for signering", e);
    } catch (XMLSignatureException e) {
        throw new XmlKonfigurasjonException("Klarte ikke  signere ASiC-E element.", e);
    }

    // Pakk Signatur inn i XAdES-konvolutt
    wrapSignatureInXADeSEnvelope(document);

    ByteArrayOutputStream outputStream;
    try {
        outputStream = new ByteArrayOutputStream();
        Transformer transformer = transformerFactory.newTransformer();
        schema.newValidator().validate(new DOMSource(document));
        transformer.transform(new DOMSource(document), new StreamResult(outputStream));
    } catch (TransformerException e) {
        throw new KonfigurasjonException("Klarte ikke  serialisere XML", e);
    } catch (SAXException e) {
        throw new XmlValideringException(
                "Kunne ikke validere generert signatures.xml. Sjekk at input er gyldig og at det ikke er ugyldige tegn i filnavn o.l.",
                KLIENT, e);
    } catch (IOException e) {
        throw new RuntimeIOException(e);
    }
    return new Signature(outputStream.toByteArray());
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * @see #getCertificate(XMLSignature)/*from   w ww .ja  v a2s  .  c o m*/
 */
public static X509Certificate getCertificate(cl.sii.siiDte.dsig.SignatureType xml) {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    // Unmarshal the signature
    XMLSignature signature;
    try {
        signature = fac.unmarshalXMLSignature(new DOMStructure(xml.getDomNode()));
    } catch (MarshalException e) {
        return null;
    }
    return (getCertificate(signature));
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * @see #getCertificate(XMLSignature)/*from   ww  w.j  a v a2 s  .  c  om*/
 */
public static X509Certificate getCertificate(cl.sii.siiDte.libroguia.SignatureType xml) {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    // Unmarshal the signature
    XMLSignature signature;
    try {
        signature = fac.unmarshalXMLSignature(new DOMStructure(xml.getDomNode()));
    } catch (MarshalException e) {
        return null;
    }
    return (getCertificate(signature));
}

From source file:cl.nic.dte.util.XMLUtil.java

/**
 * @see #getCertificate(XMLSignature)//from w w w .j ava2s. co  m
 */
public static X509Certificate getCertificate(cl.sii.siiDte.libroboletas.SignatureType xml) {
    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");

    // Unmarshal the signature
    XMLSignature signature;
    try {
        signature = fac.unmarshalXMLSignature(new DOMStructure(xml.getDomNode()));
    } catch (MarshalException e) {
        return null;
    }
    return (getCertificate(signature));
}

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

public void preSign(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<X509Certificate> signingCertificateChain, List<Reference> references, List<XMLObject> objects)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
    LOG.debug("preSign");

    // QualifyingProperties
    QualifyingPropertiesType qualifyingProperties = this.xadesObjectFactory.createQualifyingPropertiesType();
    qualifyingProperties.setTarget("#" + signatureId);

    // SignedProperties
    SignedPropertiesType signedProperties = this.xadesObjectFactory.createSignedPropertiesType();
    String signedPropertiesId;//from  w ww  .  ja  v  a 2s  .c  om
    if (null != this.idSignedProperties) {
        signedPropertiesId = this.idSignedProperties;
    } else {
        signedPropertiesId = signatureId + "-xades";
    }
    signedProperties.setId(signedPropertiesId);
    qualifyingProperties.setSignedProperties(signedProperties);

    // SignedSignatureProperties
    SignedSignaturePropertiesType signedSignatureProperties = this.xadesObjectFactory
            .createSignedSignaturePropertiesType();
    signedProperties.setSignedSignatureProperties(signedSignatureProperties);

    // SigningTime
    GregorianCalendar signingTime = new GregorianCalendar(TimeZone.getTimeZone("Z"));
    Date currentClockValue = this.clock.getTime();
    signingTime.setTime(currentClockValue);
    XMLGregorianCalendar xmlGregorianCalendar = this.datatypeFactory.newXMLGregorianCalendar(signingTime);
    xmlGregorianCalendar.setMillisecond(DatatypeConstants.FIELD_UNDEFINED);
    signedSignatureProperties.setSigningTime(xmlGregorianCalendar);

    // SigningCertificate
    if (null == signingCertificateChain || signingCertificateChain.isEmpty()) {
        throw new RuntimeException("no signing certificate chain available");
    }
    X509Certificate signingCertificate = signingCertificateChain.get(0);
    CertIDType signingCertificateId = getCertID(signingCertificate, this.xadesObjectFactory,
            this.xmldsigObjectFactory, this.digestAlgorithm, this.issuerNameNoReverseOrder);
    CertIDListType signingCertificates = this.xadesObjectFactory.createCertIDListType();
    signingCertificates.getCert().add(signingCertificateId);
    signedSignatureProperties.setSigningCertificate(signingCertificates);

    // ClaimedRole
    if (null != this.role && false == this.role.isEmpty()) {
        SignerRoleType signerRole = this.xadesObjectFactory.createSignerRoleType();
        signedSignatureProperties.setSignerRole(signerRole);
        ClaimedRolesListType claimedRolesList = this.xadesObjectFactory.createClaimedRolesListType();
        signerRole.setClaimedRoles(claimedRolesList);
        AnyType claimedRole = this.xadesObjectFactory.createAnyType();
        claimedRole.getContent().add(this.role);
        claimedRolesList.getClaimedRole().add(claimedRole);
    }

    // XAdES-EPES
    if (null != this.signaturePolicyService) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory
                .createSignaturePolicyIdentifierType();
        signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier);

        SignaturePolicyIdType signaturePolicyId = this.xadesObjectFactory.createSignaturePolicyIdType();
        signaturePolicyIdentifier.setSignaturePolicyId(signaturePolicyId);

        ObjectIdentifierType objectIdentifier = this.xadesObjectFactory.createObjectIdentifierType();
        signaturePolicyId.setSigPolicyId(objectIdentifier);
        IdentifierType identifier = this.xadesObjectFactory.createIdentifierType();
        objectIdentifier.setIdentifier(identifier);
        identifier.setValue(this.signaturePolicyService.getSignaturePolicyIdentifier());
        objectIdentifier.setDescription(this.signaturePolicyService.getSignaturePolicyDescription());

        byte[] signaturePolicyDocumentData = this.signaturePolicyService.getSignaturePolicyDocument();
        DigestAlgAndValueType sigPolicyHash = getDigestAlgAndValue(signaturePolicyDocumentData,
                this.xadesObjectFactory, this.xmldsigObjectFactory, this.digestAlgorithm);
        signaturePolicyId.setSigPolicyHash(sigPolicyHash);

        String signaturePolicyDownloadUrl = this.signaturePolicyService.getSignaturePolicyDownloadUrl();
        if (null != signaturePolicyDownloadUrl) {
            SigPolicyQualifiersListType sigPolicyQualifiers = this.xadesObjectFactory
                    .createSigPolicyQualifiersListType();
            signaturePolicyId.setSigPolicyQualifiers(sigPolicyQualifiers);

            AnyType sigPolicyQualifier = this.xadesObjectFactory.createAnyType();
            sigPolicyQualifiers.getSigPolicyQualifier().add(sigPolicyQualifier);

            JAXBElement<String> spUriElement = this.xadesObjectFactory.createSPURI(signaturePolicyDownloadUrl);
            sigPolicyQualifier.getContent().add(spUriElement);
        }
    } else if (this.signaturePolicyImplied) {
        SignaturePolicyIdentifierType signaturePolicyIdentifier = this.xadesObjectFactory
                .createSignaturePolicyIdentifierType();
        signedSignatureProperties.setSignaturePolicyIdentifier(signaturePolicyIdentifier);

        signaturePolicyIdentifier.setSignaturePolicyImplied("");
    }

    // DataObjectFormat
    if (false == this.dataObjectFormatMimeTypes.isEmpty()) {
        SignedDataObjectPropertiesType signedDataObjectProperties = this.xadesObjectFactory
                .createSignedDataObjectPropertiesType();
        signedProperties.setSignedDataObjectProperties(signedDataObjectProperties);

        List<DataObjectFormatType> dataObjectFormats = signedDataObjectProperties.getDataObjectFormat();
        for (Map.Entry<String, String> dataObjectFormatMimeType : this.dataObjectFormatMimeTypes.entrySet()) {
            DataObjectFormatType dataObjectFormat = this.xadesObjectFactory.createDataObjectFormatType();
            dataObjectFormat.setObjectReference("#" + dataObjectFormatMimeType.getKey());
            dataObjectFormat.setMimeType(dataObjectFormatMimeType.getValue());
            dataObjectFormats.add(dataObjectFormat);
        }
    }

    // marshall XAdES QualifyingProperties
    Node qualifyingPropertiesNode = marshallQualifyingProperties(document, this.xadesObjectFactory,
            qualifyingProperties);

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

    // add XAdES ds:Reference
    DigestMethod digestMethod = signatureFactory.newDigestMethod(digestAlgorithm.getXmlAlgoId(), null);
    List<Transform> transforms = new LinkedList<Transform>();
    Transform exclusiveTransform = signatureFactory.newTransform(CanonicalizationMethod.INCLUSIVE,
            (TransformParameterSpec) null);
    transforms.add(exclusiveTransform);
    Reference reference = signatureFactory.newReference("#" + signedPropertiesId, digestMethod, transforms,
            XADES_TYPE, null);
    references.add(reference);
}

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

private void addSignatureTime(XMLSignatureFactory signatureFactory, Document document, String signatureId,
        List<XMLStructure> objectContent) {
    /*//  w ww  .  j ava2s .c om
     * SignatureTime
     */
    Element signatureTimeElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:SignatureTime");
    signatureTimeElement.setAttributeNS(Constants.NamespaceSpecNS, "xmlns:mdssi", OOXML_DIGSIG_NS);
    Element formatElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:Format");
    formatElement.setTextContent("YYYY-MM-DDThh:mm:ssTZD");
    signatureTimeElement.appendChild(formatElement);
    Element valueElement = document.createElementNS(OOXML_DIGSIG_NS, "mdssi:Value");
    Date now = this.clock.getTime();
    DateTime dateTime = new DateTime(now.getTime(), DateTimeZone.UTC);
    DateTimeFormatter fmt = ISODateTimeFormat.dateTimeNoMillis();
    String nowStr = fmt.print(dateTime);
    LOG.debug("now: " + nowStr);
    valueElement.setTextContent(nowStr);
    signatureTimeElement.appendChild(valueElement);

    List<XMLStructure> signatureTimeContent = new LinkedList<XMLStructure>();
    signatureTimeContent.add(new DOMStructure(signatureTimeElement));
    SignatureProperty signatureTimeSignatureProperty = signatureFactory
            .newSignatureProperty(signatureTimeContent, "#" + signatureId, "idSignatureTime");
    List<SignatureProperty> signaturePropertyContent = new LinkedList<SignatureProperty>();
    signaturePropertyContent.add(signatureTimeSignatureProperty);
    SignatureProperties signatureProperties = signatureFactory.newSignatureProperties(signaturePropertyContent,
            "id-signature-time-" + UUID.randomUUID().toString());
    objectContent.add(signatureProperties);
}

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  a  v  a  2  s  .  co m*/
        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:it.cnr.icar.eric.common.security.wss4j.WSS4JSignatureBST.java

/**
 * Initialize a WSSec Signature.//from w  ww .jav a 2s .c  om
 * 
 * The method sets up and initializes a WSSec Signature structure after the
 * relevant information was set. After setup of the references to elements
 * to sign may be added. After all references are added they can be signed.
 * 
 * This method does not add the Signature element to the security header.
 * See <code>prependSignatureElementToHeader()</code> method.
 * 
 * @param doc The SOAP envelope as <code>Document</code>
 * @param cr An instance of the Crypto API to handle keystore and certificates
 * @param secHeader The security header that will hold the Signature. This is used
 *                   to construct namespace prefixes for Signature. This method
 * @throws WSSecurityException
 */
public void prepare(Document doc, Crypto cr, WSSecHeader secHeader) throws WSSecurityException {
    //
    // Gather some info about the document to process and store it for
    // retrieval
    //
    crypto = cr;
    document = doc;
    wsDocInfo = new WSDocInfo(doc);
    wsDocInfo.setCrypto(cr);
    securityHeader = secHeader.getSecurityHeader();

    //
    // At first get the security token (certificate) according to the parameters.
    //
    X509Certificate[] certs = getSigningCerts();

    try {
        C14NMethodParameterSpec c14nSpec = null;
        if (getWsConfig().isWsiBSPCompliant() && canonAlgo.equals(WSConstants.C14N_EXCL_OMIT_COMMENTS)) {
            List<String> prefixes = getInclusivePrefixes(secHeader.getSecurityHeader(), false);
            c14nSpec = new ExcC14NParameterSpec(prefixes);
        }

        c14nMethod = signatureFactory.newCanonicalizationMethod(canonAlgo, c14nSpec);
    } catch (Exception ex) {
        log.error("", ex);
        throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
    }

    keyInfoUri = getWsConfig().getIdAllocator().createSecureId("KI-", keyInfo);
    if (!useCustomSecRef) {
        secRef = new SecurityTokenReference(doc);
        strUri = getWsConfig().getIdAllocator().createSecureId("STR-", secRef);
        secRef.setID(strUri);

        //
        // Get an initialized XMLSignature element.
        //

        //
        // Prepare and setup the token references for this Signature
        //
        switch (keyIdentifierType) {
        case WSConstants.BST_DIRECT_REFERENCE:
            Reference ref = new Reference(document);
            ref.setURI("#" + certUri);
            if (!useSingleCert) {
                bstToken = new PKIPathSecurity(document);
                ((PKIPathSecurity) bstToken).setX509Certificates(certs, crypto);
                secRef.addTokenType(PKIPathSecurity.PKI_TYPE);
            } else {
                bstToken = new X509Security(document);
                ((X509Security) bstToken).setX509Certificate(certs[0]);
            }
            ref.setValueType(bstToken.getValueType());
            secRef.setReference(ref);
            bstToken.setID(certUri);
            wsDocInfo.addTokenElement(bstToken.getElement(), false);
            break;

        case WSConstants.ISSUER_SERIAL:
            String issuer = certs[0].getIssuerX500Principal().getName();
            java.math.BigInteger serialNumber = certs[0].getSerialNumber();
            DOMX509IssuerSerial domIssuerSerial = new DOMX509IssuerSerial(doc, issuer, serialNumber);
            DOMX509Data domX509Data = new DOMX509Data(doc, domIssuerSerial);
            secRef.setX509Data(domX509Data);
            break;

        case WSConstants.X509_KEY_IDENTIFIER:
            secRef.setKeyIdentifier(certs[0]);
            break;

        case WSConstants.SKI_KEY_IDENTIFIER:
            secRef.setKeyIdentifierSKI(certs[0], crypto);
            break;

        case WSConstants.THUMBPRINT_IDENTIFIER:
            secRef.setKeyIdentifierThumb(certs[0]);
            break;

        case WSConstants.ENCRYPTED_KEY_SHA1_IDENTIFIER:
            if (encrKeySha1value != null) {
                secRef.setKeyIdentifierEncKeySHA1(encrKeySha1value);
            } else {
                byte[] digestBytes = WSSecurityUtil.generateDigest(secretKey);
                secRef.setKeyIdentifierEncKeySHA1(Base64.encode(digestBytes));
            }
            secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
            break;

        case WSConstants.CUSTOM_SYMM_SIGNING:
            Reference refCust = new Reference(document);
            if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                refCust.setValueType(customTokenValueType);
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
            } else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
                refCust.setValueType(customTokenValueType);
            } else if (KerberosSecurity.isKerberosToken(customTokenValueType)) {
                secRef.addTokenType(customTokenValueType);
                refCust.setValueType(customTokenValueType);
            } else {
                refCust.setValueType(customTokenValueType);
            }
            refCust.setURI("#" + customTokenId);
            secRef.setReference(refCust);
            break;

        case WSConstants.CUSTOM_SYMM_SIGNING_DIRECT:
            Reference refCustd = new Reference(document);
            if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
                refCustd.setValueType(customTokenValueType);
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
            } else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
                refCustd.setValueType(customTokenValueType);
            } else if (KerberosSecurity.isKerberosToken(customTokenValueType)) {
                secRef.addTokenType(customTokenValueType);
                refCustd.setValueType(customTokenValueType);
            } else {
                refCustd.setValueType(customTokenValueType);
            }
            refCustd.setURI(customTokenId);
            secRef.setReference(refCustd);
            break;

        case WSConstants.CUSTOM_KEY_IDENTIFIER:
            if (WSConstants.WSS_SAML_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId);
                secRef.addTokenType(WSConstants.WSS_SAML_TOKEN_TYPE);
            } else if (WSConstants.WSS_SAML2_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId);
                secRef.addTokenType(WSConstants.WSS_SAML2_TOKEN_TYPE);
            } else if (WSConstants.WSS_ENC_KEY_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId, true);
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
            } else if (SecurityTokenReference.ENC_KEY_SHA1_URI.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId, true);
                secRef.addTokenType(WSConstants.WSS_ENC_KEY_VALUE_TYPE);
            } else if (WSConstants.WSS_KRB_KI_VALUE_TYPE.equals(customTokenValueType)) {
                secRef.setKeyIdentifier(customTokenValueType, customTokenId, true);
                secRef.addTokenType(WSConstants.WSS_GSS_KRB_V5_AP_REQ);
            }
            break;

        case WSConstants.KEY_VALUE:
            java.security.PublicKey publicKey = certs[0].getPublicKey();

            try {
                KeyValue keyValue = keyInfoFactory.newKeyValue(publicKey);
                keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(keyValue), keyInfoUri);
            } catch (java.security.KeyException ex) {
                log.error("", ex);
                throw new WSSecurityException(WSSecurityException.FAILED_SIGNATURE, "noXMLSig", null, ex);
            }
            break;
        default:
            throw new WSSecurityException(WSSecurityException.FAILURE, "unsupportedKeyId");
        }
    }

    if (keyIdentifierType != WSConstants.KEY_VALUE) {
        XMLStructure structure = new DOMStructure(secRef.getElement());
        wsDocInfo.addTokenElement(secRef.getElement(), false);
        keyInfo = keyInfoFactory.newKeyInfo(java.util.Collections.singletonList(structure), keyInfoUri);
    }
}