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

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

Introduction

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

Prototype

public void setDefaultNamespacePrefix(String defaultPrefix) 

Source Link

Usage

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// w  w  w  .  j  av  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:test.integ.be.fedict.hsm.ws.WSSecurityTestSOAPHandler.java

private void addSignature(Element wsSecurityHeaderElement, Element tsElement, Element bodyElement)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, MarshalException,
        XMLSignatureException, NoSuchProviderException, SOAPException {
    if (null == this.privateKey) {
        return;/*from w w w . j a v  a  2 s . co m*/
    }
    DOMSignContext domSignContext = new DOMSignContext(this.privateKey, wsSecurityHeaderElement);
    domSignContext.setDefaultNamespacePrefix("ds");
    domSignContext.setIdAttributeNS(tsElement, WSU_NAMESPACE, "Id");
    domSignContext.setIdAttributeNS(bodyElement, WSU_NAMESPACE, "Id");
    LOG.debug("Timestamp element found: " + (null != domSignContext.getElementById("TS")));
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

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

    List<String> tsPrefixes = new LinkedList<String>();
    tsPrefixes.add("wsse");
    tsPrefixes.add("S");
    ExcC14NParameterSpec tsTransformSpec = new ExcC14NParameterSpec(tsPrefixes);
    Reference tsReference = xmlSignatureFactory.newReference("#TS",
            xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
            Collections.singletonList(
                    xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, tsTransformSpec)),
            null, null);
    references.add(tsReference);

    if (this.signBody) {
        List<String> bodyPrefixes = new LinkedList<String>();
        ExcC14NParameterSpec bodyTransformSpec = new ExcC14NParameterSpec(bodyPrefixes);
        Reference bodyReference = xmlSignatureFactory.newReference("#Body",
                xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                Collections.singletonList(
                        xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE, bodyTransformSpec)),
                null, null);
        references.add(bodyReference);
    }

    if (this.signBinarySecurityToken) {
        Reference bstReference = xmlSignatureFactory
                .newReference("#X509", xmlSignatureFactory.newDigestMethod(this.digestAlgorithm, null),
                        Collections.singletonList(xmlSignatureFactory
                                .newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null)),
                        null, null);
        references.add(bstReference);
    }

    SignedInfo signedInfo = xmlSignatureFactory.newSignedInfo(
            xmlSignatureFactory.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE,
                    (C14NMethodParameterSpec) null),
            xmlSignatureFactory.newSignatureMethod(this.signatureAlgorithm, null), references);

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    Document document = wsSecurityHeaderElement.getOwnerDocument();
    Element securityTokenReferenceElement = document.createElementNS(WSSE_NAMESPACE,
            "wsse:SecurityTokenReference");
    Element referenceElement = document.createElementNS(WSSE_NAMESPACE, "wsse:Reference");
    referenceElement.setAttribute("ValueType",
            "http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-x509-token-profile-1.0#X509v3");
    referenceElement.setAttribute("URI", "#X509");
    securityTokenReferenceElement.appendChild(referenceElement);
    KeyInfo keyInfo = keyInfoFactory
            .newKeyInfo(Collections.singletonList(new DOMStructure(securityTokenReferenceElement)));

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