Example usage for javax.xml.crypto.dsig XMLSignatureFactory getKeyInfoFactory

List of usage examples for javax.xml.crypto.dsig XMLSignatureFactory getKeyInfoFactory

Introduction

In this page you can find the example usage for javax.xml.crypto.dsig XMLSignatureFactory getKeyInfoFactory.

Prototype

public final KeyInfoFactory getKeyInfoFactory() 

Source Link

Document

Returns a KeyInfoFactory that creates KeyInfo objects.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {
    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair dsaKeyPair = kpg.generateKeyPair();

    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
    Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
    SignedInfo signedInfo = sigFactory.newSignedInfo(
            sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(dsaKeyPair.getPublic());
    KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

    XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo);
}

From source file:MainClass.java

public static void main(String[] args) throws Exception {

    KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
    kpg.initialize(1024, new SecureRandom());
    KeyPair dsaKeyPair = kpg.generateKeyPair();

    XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
    Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
    SignedInfo signedInfo = sigFactory.newSignedInfo(
            sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                    (C14NMethodParameterSpec) null),
            sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
    KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(dsaKeyPair.getPublic());
    KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

    XMLSignature xmlSig = sigFactory.newXMLSignature(signedInfo, keyInfo);
}

From source file:Signing.java

public static void main(String[] args) throws Exception {
        SOAPMessage soapMessage = MessageFactory.newInstance().createMessage();
        SOAPPart soapPart = soapMessage.getSOAPPart();
        SOAPEnvelope soapEnvelope = soapPart.getEnvelope();

        SOAPHeader soapHeader = soapEnvelope.getHeader();
        SOAPHeaderElement headerElement = soapHeader.addHeaderElement(soapEnvelope.createName("Signature",
                "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"));

        SOAPBody soapBody = soapEnvelope.getBody();
        soapBody.addAttribute(//from   w w w.  j a va  2 s  . co m
                soapEnvelope.createName("id", "SOAP-SEC", "http://schemas.xmlsoap.org/soap/security/2000-12"),
                "Body");
        Name bodyName = soapEnvelope.createName("FooBar", "z", "http://example.com");
        SOAPBodyElement gltp = soapBody.addBodyElement(bodyName);

        Source source = soapPart.getContent();
        Node root = null;
        if (source instanceof DOMSource) {
            root = ((DOMSource) source).getNode();
        } else if (source instanceof SAXSource) {
            InputSource inSource = ((SAXSource) source).getInputSource();
            DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
            dbf.setNamespaceAware(true);
            DocumentBuilder db = null;

            db = dbf.newDocumentBuilder();

            Document doc = db.parse(inSource);
            root = (Node) doc.getDocumentElement();
        }

        dumpDocument(root);

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("DSA");
        kpg.initialize(1024, new SecureRandom());
        KeyPair keypair = kpg.generateKeyPair();

        XMLSignatureFactory sigFactory = XMLSignatureFactory.getInstance();
        Reference ref = sigFactory.newReference("#Body", sigFactory.newDigestMethod(DigestMethod.SHA1, null));
        SignedInfo signedInfo = sigFactory.newSignedInfo(
                sigFactory.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE_WITH_COMMENTS,
                        (C14NMethodParameterSpec) null),
                sigFactory.newSignatureMethod(SignatureMethod.DSA_SHA1, null), Collections.singletonList(ref));
        KeyInfoFactory kif = sigFactory.getKeyInfoFactory();
        KeyValue kv = kif.newKeyValue(keypair.getPublic());
        KeyInfo keyInfo = kif.newKeyInfo(Collections.singletonList(kv));

        XMLSignature sig = sigFactory.newXMLSignature(signedInfo, keyInfo);

        System.out.println("Signing the message...");
        PrivateKey privateKey = keypair.getPrivate();
        Element envelope = getFirstChildElement(root);
        Element header = getFirstChildElement(envelope);
        DOMSignContext sigContext = new DOMSignContext(privateKey, header);
        sigContext.putNamespacePrefix(XMLSignature.XMLNS, "ds");
        sigContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        sig.sign(sigContext);

        dumpDocument(root);

        System.out.println("Validate the signature...");
        Element sigElement = getFirstChildElement(header);
        DOMValidateContext valContext = new DOMValidateContext(keypair.getPublic(), sigElement);
        valContext.setIdAttributeNS(getNextSiblingElement(header),
                "http://schemas.xmlsoap.org/soap/security/2000-12", "id");
        boolean valid = sig.validate(valContext);

        System.out.println("Signature valid? " + valid);
    }

From source file:Main.java

public static void signEmbeded(Node doc, String uri, PrivateKey privKey, PublicKey pubKey)
        throws InvalidAlgorithmParameterException, NoSuchAlgorithmException, KeyException, MarshalException,
        XMLSignatureException {//from  w ww .ja  va2 s.  co m

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

    Reference ref = fac.newReference(uri, fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    String method = SignatureMethod.RSA_SHA1; // default

    if ("DSA".equals(privKey.getAlgorithm()))
        method = SignatureMethod.DSA_SHA1;

    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical
            (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null),
            Collections.singletonList(ref));

    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(pubKey);

    // Create a KeyInfo and add the KeyValue to it
    List<XMLStructure> kidata = new ArrayList<XMLStructure>();
    kidata.add(kv);
    KeyInfo ki = kif.newKeyInfo(kidata);

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

    // Create the XMLSignature (but don't sign it yet)
    XMLSignature signature = fac.newXMLSignature(si, ki);

    // Marshal, generate (and sign) the enveloped signature
    signature.sign(dsc);

}

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

private KeyInfo keyInfo(final XMLSignatureFactory xmlSignatureFactory, final Certificate[] sertifikater) {
    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    X509Data x509Data = keyInfoFactory.newX509Data(asList(sertifikater));
    return keyInfoFactory.newKeyInfo(singletonList(x509Data));
}

From source file:Main.java

/**
 * Firma digitalmente usando la forma "enveloped signature" seg&uacute;n el
 * est&aacute;ndar de la W3C (<a/* w  ww.ja va 2  s. co  m*/
 * href="http://www.w3.org/TR/xmldsig-core/">http://www.w3.org/TR/xmldsig-core/</a>).
 * <p>
 * 
 * Este m&eacute;todo adem&aacute;s incorpora la informaci&oacute;n del
 * certificado a la secci&oacute;n &lt;KeyInfo&gt; opcional del
 * est&aacute;ndar, seg&uacute;n lo exige SII.
 * <p>
 * 
 * @param doc
 *            El documento a firmar
 * @param uri
 *            La referencia dentro del documento que debe ser firmada
 * @param pKey
 *            La llave privada para firmar
 * @param cert
 *            El certificado digital correspondiente a la llave privada
 * @throws NoSuchAlgorithmException
 *             Si el algoritmo de firma de la llave no est&aacute; soportado
 *             (Actualmente soportado RSA+SHA1, DSA+SHA1 y HMAC+SHA1).
 * @throws InvalidAlgorithmParameterException
 *             Si los algoritmos de canonizaci&oacute;n (parte del
 *             est&aacute;ndar XML Signature) no son soportados (actaulmente
 *             se usa el por defecto)
 * @throws KeyException
 *             Si hay problemas al incluir la llave p&uacute;blica en el
 *             &lt;KeyValue&gt;.
 * @throws MarshalException
 * @throws XMLSignatureException
 * 
 * @see javax.xml.crypto.dsig.XMLSignature#sign(javax.xml.crypto.dsig.XMLSignContext)
 */
public static void signEmbeded(Node doc, String uri, PrivateKey pKey, X509Certificate cert)
        throws NoSuchAlgorithmException, InvalidAlgorithmParameterException, KeyException, MarshalException,
        XMLSignatureException {

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

    // 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(uri, fac.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(fac.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null)),
            null, null);

    // Create the SignedInfo
    String method = SignatureMethod.RSA_SHA1; // default by SII

    if ("DSA".equals(cert.getPublicKey().getAlgorithm()))
        method = SignatureMethod.DSA_SHA1;
    else if ("HMAC".equals(cert.getPublicKey().getAlgorithm()))
        method = SignatureMethod.HMAC_SHA1;

    SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE, // Default canonical and
            // default by SII
            (C14NMethodParameterSpec) null), fac.newSignatureMethod(method, null),
            Collections.singletonList(ref));

    KeyInfoFactory kif = fac.getKeyInfoFactory();
    KeyValue kv = kif.newKeyValue(cert.getPublicKey());

    // Create a KeyInfo and add the KeyValue to it
    List<XMLStructure> kidata = new ArrayList<XMLStructure>();
    kidata.add(kv);
    kidata.add(kif.newX509Data(Collections.singletonList(cert)));
    KeyInfo ki = kif.newKeyInfo(kidata);

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

    // Create the XMLSignature (but don't sign it yet)
    XMLSignature signature = fac.newXMLSignature(si, ki);

    // Marshal, generate (and sign) the enveloped signature
    signature.sign(dsc);

}

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

public Document sign(final StandardBusinessDocument sbd) {
    try {/*from  w  ww .  j  ava 2s  .  co  m*/
        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:be.e_contract.mycarenet.xkms2.KeyBindingAuthenticationSignatureSOAPHandler.java

private void addSignature(Element parentElement) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException, MarshalException, XMLSignatureException {
    DOMSignContext domSignContext = new DOMSignContext(this.authnPrivateKey, parentElement);
    XMLSignatureFactory xmlSignatureFactory = XMLSignatureFactory.getInstance("DOM");

    Reference reference = xmlSignatureFactory.newReference(this.referenceUri,
            xmlSignatureFactory.newDigestMethod(DigestMethod.SHA1, null),
            Collections.singletonList(xmlSignatureFactory.newTransform(CanonicalizationMethod.EXCLUSIVE,
                    (TransformParameterSpec) null)),
            null, null);/*from ww  w. jav a2  s .  c o m*/

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

    KeyInfoFactory keyInfoFactory = xmlSignatureFactory.getKeyInfoFactory();
    KeyInfo keyInfo = keyInfoFactory.newKeyInfo(Collections
            .singletonList(keyInfoFactory.newX509Data(Collections.singletonList(this.authnCertificate))));

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

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

/**
 * Create KeyInfo section representation.
 *
 * @return KeyInfo/* www  . j  a  v a  2s  .com*/
 */
private KeyInfo createKeyInfo(SignInfo signInfo) {
    List<? extends Certificate> stsCertificates = signInfo.getCertificationPath().getCertificates();

    XMLSignatureFactory factory = XMLSignatureFactory.getInstance();
    KeyInfoFactory keyInfoFactory = factory.getKeyInfoFactory();
    X509Data certificatesData = keyInfoFactory.newX509Data(stsCertificates);

    log.debug("Created KeyInfo section from certificates: {}", stsCertificates);
    return keyInfoFactory.newKeyInfo(Collections.singletonList(certificatesData));
}

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

@SuppressWarnings("unchecked")
private byte[] getSignedXML(final String digestAlgo, final List<DigestInfo> digestInfos,
        final List<X509Certificate> signingCertificateChain, final PrivateKey signingKey)
        throws ParserConfigurationException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        MarshalException, javax.xml.crypto.dsig.XMLSignatureException, TransformerException, IOException,
        SAXException {/*from  ww w .j  a  v a2  s .  com*/
    // DOM Document construction.
    Document document = getEnvelopingDocument();
    if (null == document) {
        final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
        documentBuilderFactory.setNamespaceAware(true);
        document = documentBuilderFactory.newDocumentBuilder().newDocument();
    }

    final XMLSignContext xmlSignContext = new DOMSignContext(signingKey, document);
    final URIDereferencer uriDereferencer = getURIDereferencer();
    if (null != uriDereferencer) {
        xmlSignContext.setURIDereferencer(uriDereferencer);
    }

    final XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM", //$NON-NLS-1$
            new org.jcp.xml.dsig.internal.dom.XMLDSigRI());

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

    // Invoke the signature facets.
    final String signatureId = "xmldsig-" + UUID.randomUUID().toString(); //$NON-NLS-1$
    final List<XMLObject> objects = new LinkedList<XMLObject>();
    for (final SignatureFacet signatureFacet : this.signatureFacets) {
        signatureFacet.preSign(signatureFactory, document, signatureId, signingCertificateChain, references,
                objects);
    }

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

    // Creamos el KeyInfo
    final KeyInfoFactory kif = signatureFactory.getKeyInfoFactory();
    final List<Object> x509Content = new ArrayList<Object>();
    x509Content.add(signingCertificateChain.get(0));

    final List<Object> content = new ArrayList<Object>();
    try {
        content.add(kif.newKeyValue(signingCertificateChain.get(0).getPublicKey()));
    } catch (final Exception e) {
        Logger.getLogger("es.gob.afirma") //$NON-NLS-1$
                .severe("Error creando el KeyInfo, la informacion puede resultar incompleta: " + e); //$NON-NLS-1$
    }
    content.add(kif.newX509Data(x509Content));

    // JSR105 ds:Signature creation
    final String signatureValueId = signatureId + "-signature-value"; //$NON-NLS-1$
    final javax.xml.crypto.dsig.XMLSignature xmlSignature = signatureFactory.newXMLSignature(signedInfo,
            kif.newKeyInfo(content), // KeyInfo
            objects, signatureId, signatureValueId);

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

    // Completion of undigested ds:References in the ds:Manifests.
    for (final XMLObject object : objects) {

        final List<XMLStructure> objectContentList = object.getContent();
        for (final XMLStructure objectContent : objectContentList) {
            if (!(objectContent instanceof Manifest)) {
                continue;
            }
            final Manifest manifest = (Manifest) objectContent;
            final List<Reference> manifestReferences = manifest.getReferences();
            for (final Reference manifestReference : manifestReferences) {
                if (null != manifestReference.getDigestValue()) {
                    continue;
                }
                final DOMReference manifestDOMReference = (DOMReference) manifestReference;
                manifestDOMReference.digest(xmlSignContext);
            }
        }
    }

    // Completion of undigested ds:References.
    final List<Reference> signedInfoReferences = signedInfo.getReferences();
    for (final Reference signedInfoReference : signedInfoReferences) {
        final DOMReference domReference = (DOMReference) signedInfoReference;
        if (null != domReference.getDigestValue()) {
            // ds:Reference with external digest value
            continue;
        }
        domReference.digest(xmlSignContext);
    }

    // Calculation of signature
    final DOMSignedInfo domSignedInfo = (DOMSignedInfo) signedInfo;
    final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
    domSignedInfo.canonicalize(xmlSignContext, dataStream);
    final byte[] octets = dataStream.toByteArray();
    final Signature sig = Signature.getInstance(digestAlgo.replace("-", "") + "withRSA"); //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
    final byte[] sigBytes;
    try {
        sig.initSign(signingKey);
        sig.update(octets);
        sigBytes = sig.sign();
    } catch (final Exception e) {
        throw new javax.xml.crypto.dsig.XMLSignatureException(
                "Error en la firma PKCS#1 ('" + digestAlgo + "withRSA): " + e); //$NON-NLS-1$ //$NON-NLS-2$
    }

    // Sacamos el pre-XML a un OutputStream
    final ByteArrayOutputStream baos = new ByteArrayOutputStream();
    writeDocument(document, baos);

    // Ya tenemos el XML, con la firma vacia y el SignatureValue, cada uno
    // por su lado...
    return postSign(baos.toByteArray(), signingCertificateChain, signatureId, sigBytes);

}