Assinar XML em Java

Bom dia.

Estou com um programinha feito em java que pega um xml (compativel com os padroes da nota fiscal eletronica) e assina, e após, devolve um xml novo (assinado).

Entretanto, tive um problema ao rodar o programa.

A seguir posto as classes para ficar mais claro.

import java.io.IOException;
import java.security.Key;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.PublicKey;
import java.security.cert.*;
import java.util.Enumeration;
import java.util.Iterator;
import javax.security.auth.x500.X500Principal;
import javax.xml.crypto.*;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.keyinfo.*;

/**
 * A <code>KeySelector</code> that returns {@link PublicKey}s of trusted
 * {@link X509Certificate}s stored in a {@link KeyStore}.
 * 
 * <p>
 * This <code>KeySelector</code> uses the specified <code>KeyStore</code> to
 * find a trusted <code>X509Certificate</code> that matches information
 * specified in the {@link KeyInfo} passed to the {@link #select} method. The
 * public key from the first match is returned. If no match, <code>null</code>
 * is returned. See the <code>select</code> method for more information.
 * 
 * <p>
 * NOTE!: This X509KeySelector requires J2SE 1.4 because it uses the
 * java.security.cert.X509CertSelector & javax.security.auth.x500.X500Principal
 * classes to parse X.500 DNs and match on certificate attributes.
 * 
 * @author Sean Mullan
 */
public class X509KeySelector extends KeySelector {

	private KeyStore ks;

	/**
	 * Creates an <code>X509KeySelector</code>.
	 * 
	 * @param keyStore
	 *            the keystore
	 * @throws KeyStoreException
	 *             if the keystore has not been initialized
	 * @throws NullPointerException
	 *             if <code>keyStore</code> is <code>null</code>
	 */
	public X509KeySelector(KeyStore keyStore) throws KeyStoreException {
		if (keyStore == null) {
			throw new NullPointerException("keyStore is null");
		}
		this.ks = keyStore;
		// test to see if KeyStore has been initialized
		this.ks.size();
	}

	/**
	 * Finds a key from the keystore satisfying the specified constraints.
	 * 
	 * <p>
	 * This method compares data contained in {@link KeyInfo} entries with
	 * information stored in the <code>KeyStore</code>. The implementation
	 * iterates over the KeyInfo types and returns the first {@link PublicKey}
	 * of an X509Certificate in the keystore that is compatible with the
	 * specified AlgorithmMethod according to the following rules for each
	 * keyinfo type:
	 * 
	 * X509Data X509Certificate: if it contains a <code>KeyUsage</code>
	 * extension that asserts the <code>digitalSignature</code> bit and matches
	 * an <code>X509Certificate</code> in the <code>KeyStore</code>. X509Data
	 * X509IssuerSerial: if the serial number and issuer DN match an
	 * <code>X509Certificate</code> in the <code>KeyStore</code>. X509Data
	 * X509SubjectName: if the subject DN matches an
	 * <code>X509Certificate</code> in the <code>KeyStore</code>. X509Data
	 * X509SKI: if the subject key identifier matches an
	 * <code>X509Certificate</code> in the <code>KeyStore</code>. KeyName: if
	 * the keyname matches an alias in the <code>KeyStore</code>.
	 * RetrievalMethod: supports rawX509Certificate and X509Data types. If
	 * rawX509Certificate type, it must match an <code>X509Certificate</code> in
	 * the <code>KeyStore</code>.
	 * 
	 * @param keyInfo
	 *            a <code>KeyInfo</code> (may be <code>null</code>
	 * @param purpose
	 *            the key's purpose
	 * @param method
	 *            the algorithm method that this key is to be used for. Only
	 *            keys that are compatible with the algorithm and meet the
	 *            constraints of the specified algorithm should be returned.
	 * @param an
	 *            <code>XMLCryptoContext</code> that may contain additional
	 *            useful information for finding an appropriate key
	 * @return a key selector result
	 * @throws KeySelectorException
	 *             if an exceptional condition occurs while attempting to find a
	 *             key. Note that an inability to find a key is not considered
	 *             an exception (<code>null</code> should be returned in that
	 *             case). However, an error condition (ex: network
	 *             communications failure) that prevented the
	 *             <code>KeySelector</code> from finding a potential key should
	 *             be considered an exception.
	 * @throws ClassCastException
	 *             if the data type of <code>method</code> is not supported by
	 *             this key selector
	 */
	public KeySelectorResult select(KeyInfo keyInfo,
			KeySelector.Purpose purpose, AlgorithmMethod method,
			XMLCryptoContext context) throws KeySelectorException {

		SignatureMethod sm = (SignatureMethod) method;

		try {
			// return null if keyinfo is null or keystore is empty
			if (keyInfo == null || ks.size() == 0) {
				return new SimpleKeySelectorResult(null);
			}

			// Iterate through KeyInfo types
			Iterator i = keyInfo.getContent().iterator();
			while (i.hasNext()) {
				XMLStructure kiType = (XMLStructure) i.next();
				// check X509Data
				if (kiType instanceof X509Data) {
					X509Data xd = (X509Data) kiType;
					KeySelectorResult ksr = x509DataSelect(xd, sm);
					if (ksr != null) {
						return ksr;
					}
					// check KeyName
				} else if (kiType instanceof KeyName) {
					KeyName kn = (KeyName) kiType;
					Certificate cert = ks.getCertificate(kn.getName());
					if (cert != null
							&& algEquals(sm.getAlgorithm(), cert.getPublicKey()
									.getAlgorithm())) {
						return new SimpleKeySelectorResult(cert.getPublicKey());
					}
					// check RetrievalMethod
				} else if (kiType instanceof RetrievalMethod) {
					RetrievalMethod rm = (RetrievalMethod) kiType;
					try {
						KeySelectorResult ksr = null;
						if (rm.getType().equals(
								X509Data.RAW_X509_CERTIFICATE_TYPE)) {
							OctetStreamData data = (OctetStreamData) rm
									.dereference(context);
							CertificateFactory cf = CertificateFactory
									.getInstance("X.509");
							X509Certificate cert = (X509Certificate) cf
									.generateCertificate(data.getOctetStream());
							ksr = certSelect(cert, sm);
						} else if (rm.getType().equals(X509Data.TYPE)) {
							@SuppressWarnings("unused")
							NodeSetData nd = (NodeSetData) rm
									.dereference(context);
							// convert nd to X509Data
							// ksr = x509DataSelect(xd, sm);
						} else {
							// skip; keyinfo type is not supported
							continue;
						}
						if (ksr != null) {
							return ksr;
						}
					} catch (Exception e) {
						throw new KeySelectorException(e);
					}
				}
			}
		} catch (KeyStoreException kse) {
			// throw exception if keystore is uninitialized
			throw new KeySelectorException(kse);
		}

		// return null since no match could be found
		return new SimpleKeySelectorResult(null);
	}

	/**
	 * Searches the specified keystore for a certificate that matches the
	 * criteria specified in the CertSelector.
	 * 
	 * @return a KeySelectorResult containing the cert's public key if there is
	 *         a match; otherwise null
	 */
	@SuppressWarnings("unchecked")
	private KeySelectorResult keyStoreSelect(CertSelector cs)
			throws KeyStoreException {
		Enumeration aliases = ks.aliases();
		while (aliases.hasMoreElements()) {
			String alias = (String) aliases.nextElement();
			Certificate cert = ks.getCertificate(alias);
			if (cert != null && cs.match(cert)) {
				return new SimpleKeySelectorResult(cert.getPublicKey());
			}
		}
		return null;
	}

	/**
	 * Searches the specified keystore for a certificate that matches the
	 * specified X509Certificate and contains a public key that is compatible
	 * with the specified SignatureMethod.
	 * 
	 * @return a KeySelectorResult containing the cert's public key if there is
	 *         a match; otherwise null
	 */
	private KeySelectorResult certSelect(X509Certificate xcert,
			SignatureMethod sm) throws KeyStoreException {
		// skip non-signer certs
		boolean[] keyUsage = xcert.getKeyUsage();
		if (keyUsage[0] == false) {
			return null;
		}
		String alias = ks.getCertificateAlias(xcert);
		if (alias != null) {
			PublicKey pk = ks.getCertificate(alias).getPublicKey();
			// make sure algorithm is compatible with method
			if (algEquals(sm.getAlgorithm(), pk.getAlgorithm())) {
				return new SimpleKeySelectorResult(pk);
			}
		}
		return null;
	}

	/**
	 * Returns an OID of a public-key algorithm compatible with the specified
	 * signature algorithm URI.
	 */
	private String getPKAlgorithmOID(String algURI) {
		if (algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
			return "1.2.840.10040.4.1";
		} else if (algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
			return "1.2.840.113549.1.1";
		} else {
			return null;
		}
	}

	/**
	 * A simple KeySelectorResult containing a public key.
	 */
	private static class SimpleKeySelectorResult implements KeySelectorResult {
		private final Key key;

		SimpleKeySelectorResult(Key key) {
			this.key = key;
		}

		public Key getKey() {
			return key;
		}
	}

	/**
	 * Checks if a JCA/JCE public key algorithm name is compatible with the
	 * specified signature algorithm URI.
	 */
	// @@@FIXME: this should also work for key types other than DSA/RSA
	private boolean algEquals(String algURI, String algName) {
		if (algName.equalsIgnoreCase("DSA")
				&& algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) {
			return true;
		} else if (algName.equalsIgnoreCase("RSA")
				&& algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1)) {
			return true;
		} else {
			return false;
		}
	}

	/**
	 * Searches the specified keystore for a certificate that matches an entry
	 * of the specified X509Data and contains a public key that is compatible
	 * with the specified SignatureMethod.
	 * 
	 * @return a KeySelectorResult containing the cert's public key if there is
	 *         a match; otherwise null
	 */
	@SuppressWarnings("unchecked")
	private KeySelectorResult x509DataSelect(X509Data xd, SignatureMethod sm)
			throws KeyStoreException, KeySelectorException {

		// convert signature algorithm to compatible public-key alg OID
		String algOID = getPKAlgorithmOID(sm.getAlgorithm());

		KeySelectorResult ksr = null;
		Iterator xi = xd.getContent().iterator();
		while (xi.hasNext()) {
			ksr = null;
			Object o = xi.next();
			// check X509Certificate
			if (o instanceof X509Certificate) {
				X509Certificate xcert = (X509Certificate) o;
				ksr = certSelect(xcert, sm);
				// check X509IssuerSerial
			} else if (o instanceof X509IssuerSerial) {
				X509IssuerSerial xis = (X509IssuerSerial) o;
				X509CertSelector xcs = new X509CertSelector();
				try {
					xcs.setSubjectPublicKeyAlgID(algOID);
					xcs.setSerialNumber(xis.getSerialNumber());
					xcs.setIssuer(new X500Principal(xis.getIssuerName())
							.getName());
				} catch (IOException ioe) {
					throw new KeySelectorException(ioe);
				}
				ksr = keyStoreSelect(xcs);
				// check X509SubjectName
			} else if (o instanceof String) {
				String sn = (String) o;
				X509CertSelector xcs = new X509CertSelector();
				try {
					xcs.setSubjectPublicKeyAlgID(algOID);
					xcs.setSubject(new X500Principal(sn).getName());
				} catch (IOException ioe) {
					throw new KeySelectorException(ioe);
				}
				ksr = keyStoreSelect(xcs);
				// check X509SKI
			} else if (o instanceof byte[]) {
				byte[] ski = (byte[]) o;
				X509CertSelector xcs = new X509CertSelector();
				try {
					xcs.setSubjectPublicKeyAlgID(algOID);
				} catch (IOException ioe) {
					throw new KeySelectorException(ioe);
				}
				// DER-encode ski - required by X509CertSelector
				byte[] encodedSki = new byte[ski.length + 2];
				encodedSki[0] = 0x04; // OCTET STRING tag value
				encodedSki[1] = (byte) ski.length; // length
				System.arraycopy(ski, 0, encodedSki, 2, ski.length);
				xcs.setSubjectKeyIdentifier(encodedSki);
				ksr = keyStoreSelect(xcs);
				// check X509CRL
				// not supported: should use CertPath API
			} else {
				// skip all other entries
				continue;
			}
			if (ksr != null) {
				return ksr;
			}
		}
		return null;
	}
}

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.xml.crypto.dsig.*;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.dom.DOMValidateContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.jcp.xml.dsig.internal.dom.XMLDSigRI;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

public class Assinador {
	private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";

	public void assinar(String caminhoXml, String caminhoCertificado,
			String senha, String caminhoXmlNovo, String tipo) throws Exception {

		String tag = "infNFe";//  infInut
		// if (tipo.equals("1"))
		// tag = "infNFe";
		// else if (tipo.equals("2"))
		// tag = "infCanc";
		// else if (tipo.equals("3"))
		// tag = "infInut";

		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
		factory.setNamespaceAware(false);
		DocumentBuilder builder = factory.newDocumentBuilder();
		Document docs = builder.parse(new File(caminhoXml));
		// Document docs = builder.parse(new
		// File("c:/xml/430802017886010001735500000000010000030371-nfe.xml"));

		// Obtem elemento do documento a ser assinado, será criado uma
		// REFERENCE para o mesmo
		NodeList elements = docs.getElementsByTagName(tag);
		Element el = (Element) elements.item(0);
		String id = el.getAttribute("Id");

		System.out.println("el "+el.getAttribute("Id"));

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

		// Create a Reference to the enveloped document (in this case,
		// you are signing the whole document, so a URI of "" signifies
		// that, and also specify the SHA1 digest algorithm and
		// the ENVELOPED Transform.
		ArrayList transformList = new ArrayList();
		TransformParameterSpec tps = null;
		Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,
				tps);
		Transform c14NTransform = fac.newTransform(C14N_TRANSFORM_METHOD, tps);
		transformList.add(envelopedTransform);
		transformList.add(c14NTransform);

		Reference ref = fac.newReference("#" + id, fac.newDigestMethod(
				DigestMethod.SHA1, null), transformList, null, null);
		// Create the SignedInfo.
		SignedInfo si = fac
				.newSignedInfo(fac.newCanonicalizationMethod(
						CanonicalizationMethod.INCLUSIVE,
						(C14NMethodParameterSpec) null), fac
						.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
						Collections.singletonList(ref));

		// Load the KeyStore and get the signing key and certificate.
		// Provider p = new
		// sun.security.pkcs11.SunPKCS11("C:\\NFE_\\CERT\\DzyonA1.pfx");
		// Security.addProvider(p);
		// KeyStore ks = KeyStore.getInstance("PKCS11");
		// ks.load(null, new String("safeweb").toCharArray());
		// KeyStore ks = KeyStore.getInstance("PKCS12");

		KeyStore ks = KeyStore.getInstance("Windows-MY");
		// ks.load(null,null);
		ks.load(new FileInputStream(caminhoCertificado), senha.toCharArray());

		Enumeration aliasesEnum = ks.aliases();
		String alias = "";
		while (aliasesEnum.hasMoreElements()) {
			alias = (String) aliasesEnum.nextElement();

			if (ks.isKeyEntry(alias)) {
				System.out.println(alias);
				break;
			}
		}

		// Original
		// KeyStore ks = KeyStore.getInstance("JKS");
		// ks.load(new
		// FileInputStream("C:\\nfe\\KEYSTORE\\a3.jks"),"fran6263".toCharArray());
		//		
		KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks
				.getEntry(alias, new KeyStore.PasswordProtection(senha
						.toCharArray()));

		X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
		// Create the KeyInfo containing the X509Data.
		KeyInfoFactory kif = fac.getKeyInfoFactory();
		List x509Content = new ArrayList();
		// x509Content.add(cert.getSubjectX500Principal().getName());

		x509Content.add(cert);
		X509Data xd = kif.newX509Data(x509Content);
		KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));

		// Instantiate the document to be signed.
		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
		dbf.setNamespaceAware(false);
		Document doc = dbf.newDocumentBuilder().parse(
				new FileInputStream(caminhoXml));

		// Create a DOMSignContext and specify the RSA PrivateKey and
		// location of the resulting XMLSignature's parent element.
		// DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(),
		// doc.getDocumentElement());
		System.out.println(doc.getDocumentElement().getLastChild());// ).getLastChild()
		DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc
				.getDocumentElement().getLastChild());

		// 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);

		// Output the resulting document.
		OutputStream os = new FileOutputStream(caminhoXmlNovo);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer trans = tf.newTransformer();
		trans.transform(new DOMSource(doc), new StreamResult(os));

		// Find Signature element.
		NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS,
				"Signature");

		if (nl.getLength() == 0) {
			throw new Exception("Cannot find Signature element");
		}
		// Create a DOMValidateContext and specify a KeySelector and document
		// context.
		DOMValidateContext valContext = new DOMValidateContext(
				new X509KeySelector(ks), nl.item(0));
		// Unmarshal the XMLSignature.
		XMLSignature signatures = fac.unmarshalXMLSignature(valContext);
		// Validate the XMLSignature.
		boolean coreValidity = signatures.validate(valContext);
		// Check core validation status.
		if (coreValidity == false) {
			System.err.println("Falha na Assinatura!");
		} else {
			System.out.println("Assinatura Correta!");
		}
	}
}

A classe Main para executar o programa

import java.io.File;
import javax.swing.JOptionPane;
public class Main {
	public static void main(String[] args) throws Exception {
			
		String caminhoXml = "D:\\thiago\\NFe.xml";
		String caminhoCertificado = "D:\\thiago\\dzyonA1_2011.pfx";
		String senha = "dzyonerp";
		String arquivoXmlNovo = "D:\\thiago\\arq_assinado.xml";
		
		String tipo = "1";
//		String caminhoXml = "" ;
//		String caminhoCertificado = "" ;
//		String senha = "" ;
//		String arquivoXmlNovo = "" ;
		
		File file = new File(caminhoXml);
		if (!file.exists()) {
			JOptionPane.showMessageDialog(null, "Arquivo " + caminhoXml
					+ " não encontrado!", "Atenção",
					JOptionPane.INFORMATION_MESSAGE);
			return;
		}
		file = new File(caminhoCertificado);
		if (!file.exists()) {
			JOptionPane.showMessageDialog(null, "Arquivo " + caminhoCertificado
					+ " não encontrado!", "Atenção",
					JOptionPane.INFORMATION_MESSAGE);
			return;
		}
		try {
			Assinador t = new Assinador();
			t.assinar(caminhoXml, caminhoCertificado, senha, arquivoXmlNovo,
					tipo);
			 JOptionPane.showMessageDialog(null,
			 "Arquivo xml assinado com sucesso!", "Atenção",
			 JOptionPane.INFORMATION_MESSAGE);
		} catch (Exception e) {
			JOptionPane.showMessageDialog(null,
					"Erro ao tentar assinar arquivo xml! \n\n" + e.toString(),
					"Atenção", JOptionPane.INFORMATION_MESSAGE);
			e.printStackTrace();
		}
	}
}

E claro, o xml (peguei este na internet como exemplo).

<?xml version="1.0" encoding="utf-8"?>
<NFe xmlns="http://www.portalfiscal.inf.br/nfe">
  <infNFe Id="NFe35080599999090910270550010000000015180051273" versao="1.10">
    <ide>
      <cUF>35</cUF>
      <cNF>518005127</cNF>
      <natOp>Venda a vista</natOp>
      <indPag>0</indPag>
      <mod>55</mod>
      <serie>1</serie>
      <nNF>1</nNF>
      <dEmi>2008-05-06</dEmi>
      <dSaiEnt>2008-05-06</dSaiEnt>
      <tpNF>0</tpNF>
      <cMunFG>3550308</cMunFG>
      <tpImp>1</tpImp>
      <tpEmis>1</tpEmis>
      <cDV>3</cDV>
      <tpAmb>2</tpAmb>
      <finNFe>1</finNFe>
      <procEmi>0</procEmi>
      <verProc>NF-eletronica.com</verProc>
    </ide>
    <emit>
      <CNPJ>99999090910270</CNPJ>
      <xNome>NF-e Associacao NF-e</xNome>
      <xFant>NF-e</xFant>
      <enderEmit>
        <xLgr>Rua Central</xLgr>
        <nro>100</nro>
        <xCpl>Fundos</xCpl>
        <xBairro>Distrito Industrial</xBairro>
        <cMun>3502200</cMun>
        <xMun>Angatuba</xMun>
        <UF>SP</UF>
        <CEP>17100171</CEP>
        <cPais>1058</cPais>
        <xPais>Brasil</xPais>
        <fone>1733021717</fone>
      </enderEmit>
      <IE>123456789012</IE>
    </emit>
    <dest>
      <CNPJ>00000000000191</CNPJ>
      <xNome>DISTRIBUIDORA DE AGUAS MINERAIS</xNome>
      <enderDest>
        <xLgr>AV DAS FONTES</xLgr>
        <nro>1777</nro>
        <xCpl>10 ANDAR</xCpl>
        <xBairro>PARQUE FONTES</xBairro>
        <cMun>5030801</cMun>
        <xMun>Sao Paulo</xMun>
        <UF>SP</UF>
        <CEP>13950000</CEP>
        <cPais>1058</cPais>
        <xPais>BRASIL</xPais>
        <fone>1932011234</fone>
      </enderDest>
      <IE></IE>
    </dest>
    <retirada>
      <CNPJ>99171171000194</CNPJ>
      <xLgr>AV PAULISTA</xLgr>
      <nro>12345</nro>
      <xCpl>TERREO</xCpl>
      <xBairro>CERQUEIRA CESAR</xBairro>
      <cMun>3550308</cMun>
      <xMun>SAO PAULO</xMun>
      <UF>SP</UF>
    </retirada>
    <entrega>
      <CNPJ>99299299000194</CNPJ>
      <xLgr>AV FARIA LIMA</xLgr>
      <nro>1500</nro>
      <xCpl>15 ANDAR</xCpl>
      <xBairro>PINHEIROS</xBairro>
      <cMun>3550308</cMun>
      <xMun>SAO PAULO</xMun>
      <UF>SP</UF>
    </entrega>
    <det nItem="1">
      <prod>
        <cProd>00001</cProd>
        <cEAN />
        <xProd>Agua Mineral</xProd>
        <CFOP>5101</CFOP>
        <uCom>dz</uCom>
        <qCom>1000000.0000</qCom>
        <vUnCom>1</vUnCom>
        <vProd>10000000.00</vProd>
        <cEANTrib />
        <uTrib>und</uTrib>
        <qTrib>12000000.0000</qTrib>
        <vUnTrib>1</vUnTrib>
      </prod>
      <imposto>
        <ICMS>
          <ICMS00>
            <orig>0</orig>
            <CST>00</CST>
            <modBC>0</modBC>
            <vBC>10000000.00</vBC>
            <pICMS>18.00</pICMS>
            <vICMS>1800000.00</vICMS>
          </ICMS00>
        </ICMS>
        <PIS>
          <PISAliq>
            <CST>01</CST>
            <vBC>10000000.00</vBC>
            <pPIS>0.65</pPIS>
            <vPIS>65000</vPIS>
          </PISAliq>
        </PIS>
        <COFINS>
          <COFINSAliq>
            <CST>01</CST>
            <vBC>10000000.00</vBC>
            <pCOFINS>2.00</pCOFINS>
            <vCOFINS>200000.00</vCOFINS>
          </COFINSAliq>
        </COFINS>
      </imposto>
    </det>
    <det nItem="2">
      <prod>
        <cProd>00002</cProd>
        <cEAN />
        <xProd>Agua Mineral</xProd>
        <CFOP>5101</CFOP>
        <uCom>pack</uCom>
        <qCom>5000000.0000</qCom>
        <vUnCom>2</vUnCom>
        <vProd>10000000.00</vProd>
        <cEANTrib />
        <uTrib>und</uTrib>
        <qTrib>3000000.0000</qTrib>
        <vUnTrib>0.3333</vUnTrib>
      </prod>
      <imposto>
        <ICMS>
          <ICMS00>
            <orig>0</orig>
            <CST>00</CST>
            <modBC>0</modBC>
            <vBC>10000000.00</vBC>
            <pICMS>18.00</pICMS>
            <vICMS>1800000.00</vICMS>
          </ICMS00>
        </ICMS>
        <PIS>
          <PISAliq>
            <CST>01</CST>
            <vBC>10000000.00</vBC>
            <pPIS>0.65</pPIS>
            <vPIS>65000</vPIS>
          </PISAliq>
        </PIS>
        <COFINS>
          <COFINSAliq>
            <CST>01</CST>
            <vBC>10000000.00</vBC>
            <pCOFINS>2.00</pCOFINS>
            <vCOFINS>200000.00</vCOFINS>
          </COFINSAliq>
        </COFINS>
      </imposto>
    </det>
    <total>
      <ICMSTot>
        <vBC>20000000.00</vBC>
        <vICMS>18.00</vICMS>
        <vBCST>0</vBCST>
        <vST>0</vST>
        <vProd>20000000.00</vProd>
        <vFrete>0</vFrete>
        <vSeg>0</vSeg>
        <vDesc>0</vDesc>
        <vII>0</vII>
        <vIPI>0</vIPI>
        <vPIS>130000.00</vPIS>
        <vCOFINS>400000.00</vCOFINS>
        <vOutro>0</vOutro>
        <vNF>20000000.00</vNF>
      </ICMSTot>
    </total>
    <transp>
      <modFrete>0</modFrete>
      <transporta>
        <CNPJ>99171171000191</CNPJ>
        <xNome>Distribuidora de Bebidas Fazenda de SP Ltda.</xNome>
        <IE>171999999119</IE>
        <xEnder>Rua Central 100 - Fundos - Distrito Industrial</xEnder>
        <xMun>SAO PAULO</xMun>
        <UF>SP</UF>
      </transporta>
      <veicTransp>
        <placa>BXI1717</placa>
        <UF>SP</UF>
        <RNTC>123456789</RNTC>
      </veicTransp>
      <reboque>
        <placa>BXI1818</placa>
        <UF>SP</UF>
        <RNTC>123456789</RNTC>
      </reboque>
      <vol>
        <qVol>10000</qVol>
        <esp>CAIXA</esp>
        <marca>LINDOYA</marca>
        <nVol>500</nVol>
        <pesoL>1000000000.000</pesoL>
        <pesoB>1200000000.000</pesoB>
        <lacres>
          <nLacre>XYZ10231486</nLacre>
        </lacres>
      </vol>
    </transp>
    <infAdic>
      <infAdFisco>Nota Fiscal de exemplo NF-eletronica.com</infAdFisco>
    </infAdic>
  </infNFe>

Como estou iniciando agora sobre o desenvolvimento de Assinatura de XML em Java para NFe, os erros ainda estão escuros pra mim.

Segue o erro que ocorreu na execução do Main.Java

[Fatal Error] NFe.xml:5:6: O destino da instrução de processamento correspondente "[xX][mM][lL]" não é permitido.
org.xml.sax.SAXParseException; systemId: file:/D:/thiago/NFe.xml; lineNumber: 5; columnNumber: 6; O destino da instrução de processamento correspondente "[xX][mM][lL]" não é permitido.
	at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:254)
	at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:300)
	at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:205)
	at Assinador.assinar(Assinador.java:49)
	at Main.main(Main.java:33)
CONSTRUÍDO COM SUCESSO (tempo total: 3 segundos)

Pelo código apresentado (desculpem a inocencia se estiver errado) parece ser no arquivo Nfe.xml.

Este arquivo é um arquivo Válido para NFe?

QUALQUER AJUDA PRA CLAREAR MINHA CUCA TO AGRADECENDOO…heehee XD

Pessoal agora to conseguindo fazer gerar outro erro…heehee

Tirei algumas linhas em branco do topo do arquivo NFe.xml. Mas agora o erro é outro (bom eu acho)

Segue o erro:

[Fatal Error] NFe.xml:222:12: As estruturas do documento XML devem começar e terminar com a mesma entidade.
org.xml.sax.SAXParseException; systemId: file:/D:/thiago/NFe.xml; lineNumber: 222; columnNumber: 12; As estruturas do documento XML devem começar e terminar com a mesma entidade.
	at com.sun.org.apache.xerces.internal.parsers.DOMParser.parse(DOMParser.java:254)
	at com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderImpl.parse(DocumentBuilderImpl.java:300)
	at javax.xml.parsers.DocumentBuilder.parse(DocumentBuilder.java:205)
	at Assinador.assinar(Assinador.java:49)
	at Main.main(Main.java:33)
CONSTRUÍDO COM SUCESSO (tempo total: 28 segundos)

Qualquer dica ja tamu agradeçendo…XD