Main.java Source code

Java tutorial

Introduction

Here is the source code for Main.java

Source

//package com.java2s;
/**
 * Copyright [2009] [NIC Labs]
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file
 * except in compliance with the License. You may obtain a copy of the    License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or 
 * agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
 * specific language governing permissions and limitations under the License.
 * 
 **/

import java.security.InvalidAlgorithmParameterException;

import java.security.KeyException;

import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;

import java.security.cert.X509Certificate;

import java.util.ArrayList;
import java.util.Collections;

import java.util.List;

import javax.xml.crypto.MarshalException;

import javax.xml.crypto.XMLStructure;

import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureException;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;

import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.KeyValue;

import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;

import org.w3c.dom.Node;

public class Main {
    /**
     * Firma digitalmente usando la forma "enveloped signature" según el
     * est&aacute;ndar de la W3C (<a
     * 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);

    }
}