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, Node nextSibling) 

Source Link

Document

Creates a DOMSignContext with the specified key selector, parent and next sibling nodes.

Usage

From source file:no.digipost.api.SdpMeldingSigner.java

public Document sign(final StandardBusinessDocument sbd) {
    try {//www. j a  v  a2s  . c  om
        PrivateKey privateKey = keystoreInfo.getPrivateKey();
        X509Certificate certificate = keystoreInfo.getCertificate();

        DOMResult result = new DOMResult();
        Marshalling.marshal(marshaller, sbd, result);
        Document doc = (Document) result.getNode();
        Marshalling.trimNamespaces(doc);

        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");
        Reference ref = fac.newReference("", fac.newDigestMethod(DigestMethod.SHA256, null),
                Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
                null, null);

        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(Constants.RSA_SHA256, null), Collections.singletonList(ref));
        KeyInfoFactory kif = fac.getKeyInfoFactory();
        X509Data xd = kif.newX509Data(Collections.singletonList(certificate));
        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
        XMLSignature signature = fac.newXMLSignature(si, ki);

        Node digitalPostNode = doc.getDocumentElement().getFirstChild().getNextSibling();
        Node avsenderNode = digitalPostNode.getFirstChild();

        DOMSignContext dsc = new DOMSignContext(privateKey, digitalPostNode, avsenderNode);
        signature.sign(dsc);

        doc.normalizeDocument();
        return doc;
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    } catch (UnrecoverableKeyException e) {
        throw new RuntimeException(e);
    } catch (XMLSignatureException e) {
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    } catch (MarshalException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

/**
 * Compute the Signature over the references.
 * //from  w w w.j a va  2  s.  c  o  m
 * After references are set this method computes the Signature for them.
 * This method can be called any time after the references were set. See
 * <code>addReferencesToSign()</code>.
 * 
 * @throws WSSecurityException
 */
public void computeSignature(List<javax.xml.crypto.dsig.Reference> referenceList, WSSecHeader secHeader,
        Element siblingElement) throws WSSecurityException {
    try {
        java.security.Key key;
        if (senderVouches) {
            key = issuerCrypto.getPrivateKey(issuerKeyName, issuerKeyPW);
        } else if (secretKey != null) {
            key = WSSecurityUtil.prepareSecretKey(sigAlgo, secretKey);
        } else {
            key = userCrypto.getPrivateKey(user, password);
        }
        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);

        org.w3c.dom.Element securityHeaderElement = secHeader.getSecurityHeader();
        //
        // Prepend the signature element to the security header (after the assertion)
        //
        XMLSignContext signContext = null;
        if (siblingElement != null && siblingElement.getNextSibling() != null) {
            signContext = new DOMSignContext(key, securityHeaderElement, siblingElement.getNextSibling());
        } else {
            signContext = new DOMSignContext(key, securityHeaderElement);
        }
        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 (secRefSaml != null && secRefSaml.getElement() != null) {
            WSSecurityUtil.storeElementInContext((DOMSignContext) signContext, secRefSaml.getElement());
        }
        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.idp.common.saml2.Saml2Util.java

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

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

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

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

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

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

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

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

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

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

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

From source file:org.atricore.idbus.capabilities.sso.support.core.signature.JSR105SamlR2SignerImpl.java

/**
 * This will sign a SAMLR2 Identity artifact (assertion, request or response) represeted as a DOM tree
 * The signature will be inserted as the first child of the root element.
 *
 * @param doc/* ww w  . j  av  a2 s  .  com*/
 * @param id
 * @return
 */
protected Document sign(Document doc, String id) throws SamlR2SignatureException {
    try {

        Certificate cert = keyResolver.getCertificate();

        // Create a DOM XMLSignatureFactory that will be used to generate the
        // enveloped signature
        XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", provider);

        if (logger.isDebugEnabled())
            logger.debug("Creating XML DOM Digital Siganture (not signing yet!)");

        // Create a Reference to the enveloped document and
        // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
        // The URI must be the assertion ID

        List<Transform> transforms = new ArrayList<Transform>();
        transforms.add(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null));
        // Magically, this solves assertion DS validation when embedded in a signed response :)
        transforms.add(fac.newTransform(CanonicalizationMethod.EXCLUSIVE, (TransformParameterSpec) null));

        Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transforms,
                null, null);

        // Use signature method based on key algorithm.
        String signatureMethod = SignatureMethod.DSA_SHA1;
        if (keyResolver.getPrivateKey().getAlgorithm().equals("RSA"))
            signatureMethod = SignatureMethod.RSA_SHA1;

        logger.debug("Using signature method " + signatureMethod);

        // Create the SignedInfo, with the X509 Certificate
        /*
        SignedInfo si = fac.newSignedInfo
            (fac.newCanonicalizationMethod
                    (CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                            (C14NMethodParameterSpec) null),
                    fac.newSignatureMethod(signatureMethod, null),
                    Collections.singletonList(ref));
         */
        SignedInfo si = fac.newSignedInfo(
                fac.newCanonicalizationMethod(CanonicalizationMethod.EXCLUSIVE, (C14NMethodParameterSpec) null),
                fac.newSignatureMethod(signatureMethod, null), Collections.singletonList(ref));

        // Create a KeyInfo and add the Certificate to it
        KeyInfoFactory kif = fac.getKeyInfoFactory();

        X509Data kv = kif.newX509Data(Collections.singletonList(cert));
        //KeyValue kv = kif.newKeyValue(keyResolver.getCertificate().getPublicKey());

        KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));
        javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

        if (logger.isDebugEnabled())
            logger.debug("Signing SAMLR2 Identity Artifact ...");

        // Create a DOMSignContext and specify the DSA PrivateKey and
        // location of the resulting XMLSignature's parent element
        DOMSignContext dsc = new DOMSignContext(keyResolver.getPrivateKey(), doc.getDocumentElement(),
                doc.getDocumentElement().getFirstChild());

        // Sign the assertion
        signature.sign(dsc);

        if (logger.isDebugEnabled())
            logger.debug("Signing SAMLR2 Identity Artifact ... DONE!");

        return doc;

    } catch (NoSuchAlgorithmException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (XMLSignatureException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (MarshalException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    } catch (SSOKeyResolverException e) {
        throw new SamlR2SignatureException(e.getMessage(), e);
    }
}

From source file:org.atricore.idbus.capabilities.sso.support.test.XmlDsigTest.java

/**
 * Sign a SAMLR2 Assertion using the configured JSR 105 Provider
 *//*w w  w. j a  v  a2  s . c  om*/
@Test
public void assertionSign() throws Exception {
    //All the parameters for the keystore
    String keystoreType = "JKS";
    String keystoreFile = "src/test/resources/keystore.jks";
    String keystorePass = "xmlsecurity";
    String privateKeyAlias = "test";
    String privateKeyPass = "xmlsecurity";
    String certificateAlias = "test";
    File assertionFile = new File("src/test/resources/assertion-001.xml");
    File signatureFile = new File("target/assertion-signed-001.xml");

    JAXBContext context = JAXBContext.newInstance("oasis.names.tc.saml._2_0.assertion");
    Unmarshaller um = context.createUnmarshaller();

    JAXBElement jaxbElement = (JAXBElement) um.unmarshal(assertionFile);

    AssertionType assertion = (AssertionType) jaxbElement.getValue();

    // Unmarshall the assertion
    KeyStore ks = KeyStore.getInstance(keystoreType);
    FileInputStream fis = new FileInputStream(keystoreFile);

    //load the keystore
    ks.load(fis, keystorePass.toCharArray());

    //get the private key for signing.
    PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());

    X509Certificate cert = (X509Certificate) ks.getCertificate(certificateAlias);
    PublicKey publicKey = cert.getPublicKey();

    // Create a DOM XMLSignatureFactory that will be used to generate the
    // enveloped signature
    String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");

    XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",
            (Provider) Class.forName(providerName).newInstance());

    // Create a Reference to the enveloped document (in this case we are
    // signing the whole document, so a URI of "" signifies that) and
    // also specify the SHA1 digest algorithm and the ENVELOPED Transform.
    Reference ref = fac.newReference("#" + assertion.getID(), fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    SignedInfo si = fac.newSignedInfo(
            fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            fac.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));

    // Instantiate the document to be signed
    javax.xml.parsers.DocumentBuilderFactory dbf = javax.xml.parsers.DocumentBuilderFactory.newInstance();

    //XML Signature needs to be namespace aware
    dbf.setNamespaceAware(true);

    javax.xml.parsers.DocumentBuilder db = dbf.newDocumentBuilder();
    org.w3c.dom.Document doc = db.newDocument();

    Marshaller m = context.createMarshaller();
    m.marshal(jaxbElement, doc);

    // Create a DOMSignContext and specify the DSA PrivateKey and
    // location of the resulting XMLSignature's parent element
    DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement(),
            doc.getDocumentElement().getFirstChild());

    // Create the XMLSignature (but don't sign it yet)
    KeyInfoFactory kif = fac.getKeyInfoFactory();

    X509Data kv = kif.newX509Data(Collections.singletonList(cert));

    // Create a KeyInfo and add the KeyValue to it
    KeyInfo ki = kif.newKeyInfo(Collections.singletonList(kv));

    javax.xml.crypto.dsig.XMLSignature signature = fac.newXMLSignature(si, ki);

    signature.sign(dsc);
    // output the resulting document

    FileOutputStream f = new FileOutputStream(signatureFile);
    XMLUtils.outputDOMc14nWithComments(doc, f);
    f.close();
}