<?xml version="1.0" encoding="ISO-8859-1"?>
<rss version="2.0">
	<channel>
		<title><![CDATA[Últimas mensagens do tópico "assinaturas de arquivos xml da NFe"]]></title>
		<link>http://www.guj.com.br/posts/list/23.java</link>
		<description><![CDATA[Últimas mensagens enviadas no tópico "assinaturas de arquivos xml da NFe"]]></description>
		<generator>JForum - http://www.jforum.net</generator>
			<item>
				<title>assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Boa tarde a todos<br /> Aqui na empresa estamos tendo problemas para assinar o xml para o envio dos dados da NFe. O web service da receita sempre retorna o erro:<br /> 297 Rejeição: Assinatura difere do calculado<br /> Acho que o erro está no campo SignatureValue da assinatura. Alguém conseguiu fazer a assinatura funcionar?<br /> <br /> Abaixo está o código que usei: (encontrei o código aqui no forum e adaptei)<br /> <br /> 	[code]public static String sign(String xml) {<br /> 		OutputStream os = null;<br /> 		String CANONICALIZE_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";<br /> 		String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";<br /> 		String PROVIDER_CLASS_NAME = "org.jcp.xml.dsig.internal.dom.XMLDSigRI";<br /> 		String PROVIDER_NAME = "jsr105Provider";<br /> 		ByteArrayInputStream inXML = new ByteArrayInputStream(xml.getBytes());<br /> 		try {<br /> 			DocumentBuilderFactory factory = DocumentBuilderFactory<br /> 					.newInstance();<br /> 			factory.setNamespaceAware(false);<br /> 			// Obtem DOM do documento<br /> 			DocumentBuilder builder = factory.newDocumentBuilder();<br /> 			Document doc = builder.parse(inXML);<br /> <br /> 			// Obtem elemento do documento a ser assinado, será criado uma<br /> 			// REFERENCE para o mesmo<br /> 			NodeList elements = doc.getElementsByTagName("infNFe");<br /> 			org.w3c.dom.Element el = (org.w3c.dom.Element) elements.item(0);<br /> 			String id = el.getAttribute("Id");<br /> <br /> 			// Cria uma factory representando o elemento XML Signature, a partir<br /> 			// dela serão criados as parte desse elemento<br /> 			String providerName = System.getProperty(PROVIDER_NAME,<br /> 					PROVIDER_CLASS_NAME);<br /> 			XMLSignatureFactory signatureFactory = XMLSignatureFactory<br /> 					.getInstance("DOM", (Provider) Class.forName(providerName)<br /> 							.newInstance());<br /> <br /> 			// Cria método de Digest e canonicalização<br /> 			DigestMethod digestMethod = signatureFactory.newDigestMethod(<br /> 					DigestMethod.SHA1, null);<br /> 			C14NMethodParameterSpec c14NMethodParameterSpec = null;<br /> 			CanonicalizationMethod canonicalMethod = signatureFactory<br /> 					.newCanonicalizationMethod(CANONICALIZE_METHOD,<br /> 							c14NMethodParameterSpec);<br /> <br /> 			// Cria classe representando o Hash e algoritmo de criptografia a<br /> 			// ser aplicado<br /> 			SignatureMethod sm = signatureFactory.newSignatureMethod(<br /> 					SignatureMethod.RSA_SHA1, null);<br /> <br /> 			// Cria a lista de tranformações a serem aplicadas as referencias a<br /> 			// serem assinadas<br /> 			ArrayList transformList = new ArrayList();<br /> 			TransformParameterSpec tps = null;<br /> 			Transform envelopedTransform = signatureFactory.newTransform(<br /> 					Transform.ENVELOPED, tps);<br /> 			Transform c14NTransform = signatureFactory.newTransform(<br /> 					C14N_TRANSFORM_METHOD, tps);<br /> 			transformList.add(envelopedTransform);<br /> 			transformList.add(c14NTransform);<br /> <br /> 			// Cria referencia, parte do XML a ser assinado<br /> 			Reference ref = signatureFactory.newReference("#" + id,<br /> 					digestMethod, transformList, null, null);<br /> 			ArrayList refList = new ArrayList();<br /> 			refList.add(ref);<br /> <br /> 			SignedInfo signedInfo = signatureFactory.newSignedInfo(<br /> 					canonicalMethod, sm, refList);<br /> <br /> <br /> 			String configName = "/token.cfg";<br /> 			Provider p = new sun.security.pkcs11.SunPKCS11(configName);<br /> 			Security.addProvider(p);<br /> <br /> 			char[] pin = { 's', 'a', 'f', 'e', 'w', 'e', 'b' };<br /> 			KeyStore ks = KeyStore.getInstance("pkcs11");<br /> 			ks.load(null, pin);<br /> 			KeyStore.PrivateKeyEntry pkEntry = null;<br /> 			Enumeration aliasesEnum = ks.aliases();<br /> 			PrivateKey privateKey = null;<br /> 			String alias = "";<br /> 			while (aliasesEnum.hasMoreElements()) {<br /> 				alias = (String) aliasesEnum.nextElement();<br /> 				System.out.println(alias);<br /> 				if (ks.isKeyEntry(alias)) {<br /> 					privateKey = (PrivateKey) ks.getKey(alias, new String(<br /> 							"safeweb").toCharArray());<br /> 					break;<br /> 				}<br /> 			}<br /> 			Certificate certificate = ks.getCertificate(alias);<br /> <br /> 			DOMSignContext dsc = new DOMSignContext(privateKey, doc<br /> 					.getDocumentElement());<br /> <br /> 			KeyInfoFactory kif = signatureFactory.getKeyInfoFactory();<br /> 			X509Data x509Data = kif.newX509Data(Collections<br /> 					.singletonList(certificate));<br /> <br /> 			KeyInfo keyInfo = kif.newKeyInfo(Collections<br /> 					.singletonList(x509Data));<br /> <br /> 			XMLSignature signature = signatureFactory.newXMLSignature(<br /> 					signedInfo, keyInfo);<br /> 			signature.sign(dsc);<br /> <br /> 			os = new ByteArrayOutputStream();<br /> <br /> 			TransformerFactory tf = TransformerFactory.newInstance();<br /> 			Transformer trans = tf.newTransformer();<br /> 			trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 		} catch (Exception ex) {<br /> 			ex.printStackTrace();<br /> 		}<br /> 		return os.toString();<br /> 	}[/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/446763/assinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/446763/assinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 3 Mar 2008 16:40:21]]> GMT</pubDate>
				<author><![CDATA[ julianosott]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ conseguimos fazer funcionar aqui. Quem tiver duvidas é só pedir. Estamos pensando em fazer um tutorial pra nfe :-p (se ninguem for contra :-p)]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/447524/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/447524/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 4 Mar 2008 16:58:27]]> GMT</pubDate>
				<author><![CDATA[ julianosott]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=julianosott]conseguimos fazer funcionar aqui. Quem tiver duvidas é só pedir. Estamos pensando em fazer um tutorial pra nfe :-p (se ninguem for contra :-p)[/quote]<br /> <br /> Bah, um tutorial seria muito bacana! Aqui na empresa temos planos para implementar a NFe nos próximos e ter um artigo sobre isso feito por alguém que já teve problemas e conseguiu resolver seria de muita valia! Pois você já tem noção dos problemas encontrados nesse processo.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/447695/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/447695/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 5 Mar 2008 07:18:50]]> GMT</pubDate>
				<author><![CDATA[ Yky Mattshawn]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Um tutorial de NFe seria legal. Eu apoio esta idéia.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/448037/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/448037/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 5 Mar 2008 14:02:15]]> GMT</pubDate>
				<author><![CDATA[ victorwss]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Opa,<br /> <br /> Conta ai o segredo de tostines... <br /> Como vc conseguiu fazer funcionar?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/448358/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/448358/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 6 Mar 2008 02:47:51]]> GMT</pubDate>
				<author><![CDATA[ crdornelles]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Consegui terminar os métodos que eu queria. Fiz dois métodos que recebem uma string com o xml e retornam uma String como o xml assinado. O primeiro pega um enviNFe e assina todas as NFe dentro dele. O outro assina o elemento raíz do xml, servindo para o cancelamento e para a inutilização da nota.<br /> <br /> aqui vai o método para assinar o enviNFe:<br /> [code]<br /> 	public static String assinarEnviNFe(String xml) throws Exception {<br /> 		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();<br /> 		factory.setNamespaceAware(true);<br /> 		DocumentBuilder builder = factory.newDocumentBuilder();<br /> 		// Document docs = builder.parse(new File(<br /> 		// "c:/xml/430802017886010001735500000000010000030371-nfe.xml"));<br /> 		Document doc = factory.newDocumentBuilder().parse(<br /> 				new ByteArrayInputStream(xml.getBytes()));<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> 		XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");<br /> <br /> 		// Create a Reference to the enveloped document (in this case,<br /> 		// you are signing the whole document, so a URI of "" signifies<br /> 		// that, and also specify the SHA1 digest algorithm and<br /> 		// the ENVELOPED Transform.<br /> 		ArrayList transformList = new ArrayList();<br /> 		TransformParameterSpec tps = null;<br /> 		Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,<br /> 				tps);<br /> 		Transform c14NTransform = fac.newTransform(<br /> 				"http://www.w3.org/TR/2001/REC-xml-c14n-20010315", tps);<br /> <br /> 		transformList.add(envelopedTransform);<br /> 		transformList.add(c14NTransform);<br /> <br /> 		// Load the KeyStore and get the signing key and certificate.<br /> <br /> 		String configName = "/token.cfg";<br /> <br /> 		Provider p = new sun.security.pkcs11.SunPKCS11(configName);<br /> 		Security.addProvider(p);<br /> <br /> 		char[] pin = { 's', 'a', 'f', 'e', 'w', 'e', 'b' };<br /> 		KeyStore ks = KeyStore.getInstance("pkcs11", p);<br /> 		ks.load(null, pin);<br /> 		KeyStore.PrivateKeyEntry pkEntry = null;<br /> 		Enumeration aliasesEnum = ks.aliases();<br /> 		PrivateKey privateKey = null;<br /> 		while (aliasesEnum.hasMoreElements()) {<br /> 			String alias = (String) aliasesEnum.nextElement();<br /> 			System.out.println(alias);<br /> 			if (ks.isKeyEntry(alias)) {<br /> 				pkEntry = (KeyStore.PrivateKeyEntry) ks<br /> 						.getEntry(alias, new KeyStore.PasswordProtection(<br /> 								"safeweb".toCharArray()));<br /> 				privateKey = pkEntry.getPrivateKey();<br /> 				break;<br /> 			}<br /> 		}<br /> <br /> 		X509Certificate cert = (X509Certificate) pkEntry.getCertificate();<br /> <br /> 		// Create the KeyInfo containing the X509Data.<br /> 		KeyInfoFactory kif = fac.getKeyInfoFactory();<br /> 		List x509Content = new ArrayList();<br /> 		// x509Content.add(cert.getSubjectX500Principal().getName());<br /> 		x509Content.add(cert);<br /> 		X509Data xd = kif.newX509Data(x509Content);<br /> 		KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> <br /> 		for (int i = 0; i &lt; doc.getDocumentElement()<br /> 				.getElementsByTagName("NFe").getLength(); i++) {<br /> 			assinarNFE(fac, transformList, privateKey, ki, doc, i);<br /> 		}<br /> 		// Output the resulting document.<br /> 		ByteArrayOutputStream os = new ByteArrayOutputStream();<br /> 		TransformerFactory tf = TransformerFactory.newInstance();<br /> 		Transformer trans = tf.newTransformer();<br /> 		trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 		return os.toString();<br /> 	}<br /> <br /> 	private static void assinarNFE(XMLSignatureFactory fac,<br /> 			ArrayList transformList, PrivateKey privateKey, KeyInfo ki,<br /> 			Document doc, int i) throws Exception {<br /> <br /> 		// Obtem elemento do documento a ser assinado, será criado uma<br /> 		// REFERENCE para o mesmo<br /> 		NodeList elements = doc.getElementsByTagName("infNFe");<br /> 		Element el = (Element) elements.item(i);<br /> 		String id = el.getAttribute("Id");<br /> <br /> 		// doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> 		// ((Element)<br /> 		// doc.getDocumentElement().getElementsByTagName("NFe").item(0))<br /> 		// .setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> <br /> 		Reference ref = fac.newReference("#" + id, fac.newDigestMethod(<br /> 				DigestMethod.SHA1, null), transformList, null, null);<br /> <br /> 		// Create the SignedInfo.<br /> 		SignedInfo si = fac<br /> 				.newSignedInfo(fac.newCanonicalizationMethod(<br /> 						CanonicalizationMethod.INCLUSIVE,<br /> 						(C14NMethodParameterSpec) null), fac<br /> 						.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br /> 						Collections.singletonList(ref));<br /> <br /> 		// Create the XMLSignature, but don't sign it yet.<br /> 		XMLSignature signature = fac.newXMLSignature(si, ki);<br /> <br /> 		// Marshal, generate, and sign the enveloped signature.<br /> 		// Create a DOMSignContext and specify the RSA PrivateKey and<br /> 		// location of the resulting XMLSignature's parent element.<br /> 		DOMSignContext dsc = new DOMSignContext(privateKey, doc<br /> 				.getDocumentElement().getElementsByTagName("NFe").item(i));<br /> 		signature.sign(dsc);<br /> <br /> 	}<br /> [/code]<br /> <br /> este aqui assina o elemento raiz do xml:<br /> [code]<br /> 	public static String assinarRaiz(String xml) throws Exception {<br /> 		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();<br /> 		factory.setNamespaceAware(true);<br /> 		DocumentBuilder builder = factory.newDocumentBuilder();<br /> 		// Document docs = builder.parse(new File(<br /> 		// "c:/xml/430802017886010001735500000000010000030371-nfe.xml"));<br /> 		Document doc = factory.newDocumentBuilder().parse(<br /> 				new ByteArrayInputStream(xml.getBytes()));<br /> <br /> 		doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> <br /> 		// NodeList elements = doc.getElementsByTagName("infNFe");<br /> 		Node element = doc.getDocumentElement().getFirstChild()<br /> 				.getNextSibling();<br /> 		// elements.getLength();<br /> 		Element el = (Element) element;<br /> 		// Element el =<br /> 		// doc.getDocumentElement().getFirstChild().getChildNodes();<br /> 		String id = el.getAttribute("Id");<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> 		XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");<br /> <br /> 		// Create a Reference to the enveloped document (in this case,<br /> 		// you are signing the whole document, so a URI of "" signifies<br /> 		// that, and also specify the SHA1 digest algorithm and<br /> 		// the ENVELOPED Transform.<br /> 		ArrayList transformList = new ArrayList();<br /> 		TransformParameterSpec tps = null;<br /> 		Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,<br /> 				tps);<br /> 		Transform c14NTransform = fac.newTransform(<br /> 				"http://www.w3.org/TR/2001/REC-xml-c14n-20010315", tps);<br /> <br /> 		transformList.add(envelopedTransform);<br /> 		transformList.add(c14NTransform);<br /> <br /> 		// Load the KeyStore and get the signing key and certificate.<br /> <br /> 		String configName = "/token.cfg";<br /> <br /> 		Provider p = new sun.security.pkcs11.SunPKCS11(configName);<br /> 		Security.addProvider(p);<br /> <br /> 		char[] pin = { 's', 'a', 'f', 'e', 'w', 'e', 'b' };<br /> 		KeyStore ks = KeyStore.getInstance("pkcs11", p);<br /> 		ks.load(null, pin);<br /> 		KeyStore.PrivateKeyEntry pkEntry = null;<br /> 		Enumeration aliasesEnum = ks.aliases();<br /> 		PrivateKey privateKey = null;<br /> 		while (aliasesEnum.hasMoreElements()) {<br /> 			String alias = (String) aliasesEnum.nextElement();<br /> 			System.out.println(alias);<br /> 			if (ks.isKeyEntry(alias)) {<br /> 				pkEntry = (KeyStore.PrivateKeyEntry) ks<br /> 						.getEntry(alias, new KeyStore.PasswordProtection(<br /> 								"safeweb".toCharArray()));<br /> 				privateKey = pkEntry.getPrivateKey();<br /> 				break;<br /> 			}<br /> 		}<br /> <br /> 		X509Certificate cert = (X509Certificate) pkEntry.getCertificate();<br /> <br /> 		// Create the KeyInfo containing the X509Data.<br /> 		KeyInfoFactory kif = fac.getKeyInfoFactory();<br /> 		List x509Content = new ArrayList();<br /> 		// x509Content.add(cert.getSubjectX500Principal().getName());<br /> 		x509Content.add(cert);<br /> 		X509Data xd = kif.newX509Data(x509Content);<br /> 		KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> <br /> 		// doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> 		// ((Element)<br /> 		// doc.getDocumentElement().getElementsByTagName("NFe").item(0))<br /> 		// .setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> <br /> 		Reference ref = fac.newReference("#" + id, fac.newDigestMethod(<br /> 				DigestMethod.SHA1, null), transformList, null, null);<br /> <br /> 		// Create the SignedInfo.<br /> 		SignedInfo si = fac<br /> 				.newSignedInfo(fac.newCanonicalizationMethod(<br /> 						CanonicalizationMethod.INCLUSIVE,<br /> 						(C14NMethodParameterSpec) null), fac<br /> 						.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br /> 						Collections.singletonList(ref));<br /> <br /> 		// Create the XMLSignature, but don't sign it yet.<br /> 		XMLSignature signature = fac.newXMLSignature(si, ki);<br /> <br /> 		// Marshal, generate, and sign the enveloped signature.<br /> 		// Create a DOMSignContext and specify the RSA PrivateKey and<br /> 		// location of the resulting XMLSignature's parent element.<br /> 		DOMSignContext dsc = new DOMSignContext(privateKey, doc<br /> 				.getDocumentElement());<br /> 		signature.sign(dsc);<br /> <br /> 		// Output the resulting document.<br /> 		ByteArrayOutputStream os = new ByteArrayOutputStream();<br /> 		TransformerFactory tf = TransformerFactory.newInstance();<br /> 		Transformer trans = tf.newTransformer();<br /> 		trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 		return os.toString();<br /> 	}<br /> [/code]<br /> <br /> uma coisa que temque cuidar muito é o cabeçalho do xml que temque tá desse jeito<br /> [code]<br /> &lt;?xml version="1.0" encoding="UTF-8"?&gt;<br /> &lt;cancNFe versao="1.07" xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br /> [/code]<br /> <br /> ou seja, não pode ter o xmlns:ns2="http://www.w3.org/2000/09/xmldsig#"<br /> <br /> o mesmo vale para o enviNFe:<br /> [code]<br /> &lt;enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.10"&gt;<br />   &lt;idLote&gt;1&lt;/idLote&gt; <br />   &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br /> [/code]<br /> <br /> nesse caso tanto o envi como cada nfe devem ter xmlns="http://www.portalfiscal.inf.br/nfe" e o envi não pode ter o xmlns:ns2="http://www.w3.org/2000/09/xmldsig#". Se por acaso o xml estiver do jeito errado, pode usar esses códigos no assinador, ou criar outro método:<br /> <br /> esse aqui remove o xmlns:ns2 do elemento raíz:<br /> [code]<br /> 	doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> [/code]<br /> <br /> esse aqui adiciona o xmlns necessário a tag NFe:<br /> [code]<br /> 	((Element) doc.getDocumentElement().getElementsByTagName("NFe").item(i)).setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> [/code]<br /> <br /> Quem quiser verificar o xml pode usar esse site: http://www.sefaz.rs.gov.br/AAE_ROOT/NFE/SAT-WEB-NFE-VAL_1.asp Acho que ele só valida os certificados do Rio Grande do Sul, mas o bom é que ele verifica a estrutura do xml tb.<br /> <br /> É isso por enquanto, qualquer coisa é só perguntar.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/448662/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/448662/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 6 Mar 2008 12:51:33]]> GMT</pubDate>
				<author><![CDATA[ julianosott]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ esqueci de colocar, esse são os imports da classe: <br /> <br /> [code]<br /> import java.io.ByteArrayInputStream;<br /> import java.io.ByteArrayOutputStream;<br /> import java.io.FileInputStream;<br /> import java.io.FileOutputStream;<br /> import java.io.InputStream;<br /> import java.io.InputStreamReader;<br /> import java.io.OutputStream;<br /> import java.io.StringWriter;<br /> import java.security.KeyPair;<br /> import java.security.KeyPairGenerator;<br /> import java.security.KeyStore;<br /> import java.security.PrivateKey;<br /> import java.security.Provider;<br /> import java.security.Security;<br /> import java.security.cert.CertificateFactory;<br /> import java.security.cert.X509Certificate;<br /> import java.util.ArrayList;<br /> import java.util.Collections;<br /> import java.util.Enumeration;<br /> import java.util.List;<br /> <br /> import javax.xml.bind.JAXBContext;<br /> import javax.xml.bind.Marshaller;<br /> import javax.xml.bind.Unmarshaller;<br /> import javax.xml.crypto.dsig.CanonicalizationMethod;<br /> import javax.xml.crypto.dsig.DigestMethod;<br /> import javax.xml.crypto.dsig.Reference;<br /> import javax.xml.crypto.dsig.SignatureMethod;<br /> import javax.xml.crypto.dsig.SignedInfo;<br /> import javax.xml.crypto.dsig.Transform;<br /> import javax.xml.crypto.dsig.XMLSignature;<br /> import javax.xml.crypto.dsig.XMLSignatureFactory;<br /> import javax.xml.crypto.dsig.dom.DOMSignContext;<br /> import javax.xml.crypto.dsig.keyinfo.KeyInfo;<br /> import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;<br /> import javax.xml.crypto.dsig.keyinfo.X509Data;<br /> import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;<br /> import javax.xml.crypto.dsig.spec.TransformParameterSpec;<br /> import javax.xml.parsers.DocumentBuilder;<br /> import javax.xml.parsers.DocumentBuilderFactory;<br /> import javax.xml.transform.Transformer;<br /> import javax.xml.transform.TransformerFactory;<br /> import javax.xml.transform.dom.DOMSource;<br /> import javax.xml.transform.stream.StreamResult;<br /> <br /> import org.w3c.dom.Document;<br /> import org.w3c.dom.Element;<br /> import org.w3c.dom.Node;<br /> import org.w3c.dom.NodeList;<br /> import org.xml.sax.InputSource;<br /> [/code]<br /> <br /> Estou usando Java 5. então para usar os crypto eu tive que baixar o jwsdp-2.0 (java web server) e importar alguns jars dele. acho que foram esses:<br /> <br /> /xmldsig/lib/xmldsig.jar" /&gt; <br /> /jaxp/lib/jaxp-api.jar" /&gt; <br /> /jaxp/lib/endorsed/dom.jar" /&gt; <br /> /jaxp/lib/endorsed/xercesImpl.jar" /&gt; <br /> /jwsdp-shared/lib/xmlsec.jar" /&gt; <br /> /jaxp/lib/endorsed/xalan.jar" /&gt; ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/448686/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/448686/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 6 Mar 2008 13:13:17]]> GMT</pubDate>
				<author><![CDATA[ julianosott]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[      String configName = "/token.cfg";  <br />      Provider p = new sun.security.pkcs11.SunPKCS11(configName);  <br />      Security.addProvider(p);  <br />      char[] pin = { 's', 'a', 'f', 'e', 'w', 'e', 'b' }; <br /> <br /> Com relação ao codigo acima, gostaria de saber sobre esse arq. token.cfg que informação contem nesse arquivo, como faço para gerar esse arquivo ? <br /> e com relação ao char[] pin que informação eu devo setar ?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/453835/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/453835/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 14 Mar 2008 21:12:48]]> GMT</pubDate>
				<author><![CDATA[ ale_desenv]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ ale,<br /> <br /> Nesse arquivo temos informações sobre o driver do dispositivo pkcs11 instalado.<br /> <br /> Segue exemplo:<br /> <br /> name = Safenetikey2032<br /> <br /> library = c:\windows\system32\dkck201.dll<br /> <br /> beleza?<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/455143/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/455143/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 18 Mar 2008 09:13:24]]> GMT</pubDate>
				<author><![CDATA[ elissandromendes]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ ...]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/457978/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/457978/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 24 Mar 2008 16:46:04]]> GMT</pubDate>
				<author><![CDATA[ pbnf]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Olá,<br /> <br /> Estou iniciando com SOAP tbm para um projeto de NFE. Alguém poderiam postar o código que transmite o arquivo após a assinatura?<br /> <br /> Muito Obrigado!!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/461657/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/461657/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 31 Mar 2008 10:01:02]]> GMT</pubDate>
				<author><![CDATA[ alexandretalbert]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Bom dia pessoal,<br /> <br /> Como fica o código acima quando tenho como certificado, um arquivo pfx (serasa)? Como uso o keytool para importar para um keystore e como ficaria o código que busca o certificado?<br /> <br /> Orbigado!!!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/462183/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/462183/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 1 Apr 2008 06:36:01]]> GMT</pubDate>
				<author><![CDATA[ alexandretalbert]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Boa tarde pessoal,<br /> <br />     Estou tentando assinar um XML da NFe usando o código acima, já consegui efetuar a conexão com o web-server usando o código abaixo:<br /> [b]<br /> System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");<br /> Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());<br /> <br /> System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");<br /> System.setProperty("javax.net.ssl.keyStore", verConf.getPathKeyPFX());<br /> System.setProperty("javax.net.ssl.keyStorePassword", "xxxx");<br /> <br /> System.setProperty("javax.net.ssl.trustStoreType", "JKS");<br /> System.setProperty("javax.net.ssl.trustStore",verConf.getPathKeyJKS());<br /> [/b]<br /> <br /> Alguem já conseguiu assinar um XML NFe usando somente o arquivo .pfx   ??]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/477449/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/477449/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 28 Apr 2008 13:54:59]]> GMT</pubDate>
				<author><![CDATA[ reinaldoaraujo]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Eu consegui... veja a parte do certificado:<br /> <br /> [code]<br /> 		// Load the KeyStore and get the signing key and certificate.<br /> 		KeyStore ks = KeyStore.getInstance(Statics.getKeystoreType());<br /> 		FileInputStream fis = new FileInputStream(Statics.getKeystoreFile());<br /> 		//load the keystore<br /> 		ks.load(fis, Statics.getKeystorePassword().toCharArray());<br /> 		String alias = ks.aliases().nextElement();<br /> <br /> 		KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(Statics.getKeystorePassword().toCharArray()));<br /> <br /> 		X509Certificate cert = (X509Certificate) keyEntry.getCertificate();<br /> 		<br /> 		// Create the KeyInfo containing the X509Data.<br /> 		KeyInfoFactory kif = fac.getKeyInfoFactory();<br /> 		List&lt;Serializable&gt; x509Content = new ArrayList&lt;Serializable&gt;();<br /> 		x509Content.add(cert.getSubjectX500Principal().getName());<br /> 		x509Content.add(cert);<br /> 		X509Data xd = kif.newX509Data(x509Content);<br /> 		KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> 		<br /> 		for (int i = 0; i &lt; doc.getDocumentElement().getElementsByTagName("NFe").getLength(); i++) {<br /> 			assinarNFE(fac, transformList, keyEntry.getPrivateKey(), ki, doc, i);<br /> 		}<br /> [/code]<br /> <br /> So que o retorno da sefaz de MT e o seguinte:<br /> [code]<br /> &lt;?xml version="1.0" encoding="UTF-8"?&gt;<br /> &lt;retConsReciNFe xmlns="http://www.portalfiscal.inf.br/nfe" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.portalfiscal.inf.br/nfe retConsReciNFe_v1.10.xsd" versao="1.10"&gt;<br /> &lt;tpAmb&gt;2&lt;/tpAmb&gt;<br /> &lt;verAplic&gt;1.10&lt;/verAplic&gt;<br /> &lt;nRec&gt;510000000060267&lt;/nRec&gt;<br /> &lt;cStat&gt;104&lt;/cStat&gt;<br /> &lt;xMotivo&gt;Lote processado&lt;/xMotivo&gt;<br /> &lt;cUF&gt;51&lt;/cUF&gt;<br /> &lt;protNFe versao="1.10"&gt;<br /> &lt;infProt&gt;<br /> &lt;tpAmb&gt;2&lt;/tpAmb&gt;<br /> &lt;verAplic&gt;1.10&lt;/verAplic&gt;<br /> &lt;chNFe&gt;510804926656110128505500012345678918&lt;/chNFe&gt;<br /> &lt;dhRecbto&gt;2008-05-05T19:33:00&lt;/dhRecbto&gt;<br /> &lt;cStat&gt;297&lt;/cStat&gt;<br /> &lt;xMotivo&gt;Rejeicao: Assinatura difere do calculado&lt;/xMotivo&gt;<br /> &lt;/infProt&gt;<br /> &lt;/protNFe&gt;<br /> &lt;/retConsReciNFe&gt;<br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/481944/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/481944/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 7 May 2008 00:13:33]]> GMT</pubDate>
				<author><![CDATA[ developermaster]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Será que o erro de rejeição tem a ver com encoding, ou algo do sentido?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/482373/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/482373/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 7 May 2008 17:13:10]]> GMT</pubDate>
				<author><![CDATA[ developermaster]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Bom dia, vc validou seu XMl antes de conectar e enviar??<br /> Acesse esse site e coloque seu XML para testar, ai verificará se ele está correto e se a assinatura está correta antes de conectar no web service.<br /> <br /> <a class="snap_shots" href="http://www.sefaz.rs.gov.br/AAE_ROOT/NFE/SAT-WEB-NFE-VAL_1.asp" target="_blank" rel="nofollow">http://www.sefaz.rs.gov.br/AAE_ROOT/NFE/SAT-WEB-NFE-VAL_1.asp</a>]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/482444/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/482444/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 8 May 2008 07:19:29]]> GMT</pubDate>
				<author><![CDATA[ adrianokuse]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Bom dia...<br /> <br /> Sim, eu validei o schema com um programa chamado XmlNotepad, ele é um schema válido. Segundo informações da sefaz-MT, o esquema está correto, eles dizem que o erro é na assinatura em si.<br /> <br /> Quanto aquele validador da sefaz, nao rola pra mim pq a versao que a sefaz-mt usa e diferente...]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/482536/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/482536/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 8 May 2008 09:20:23]]> GMT</pubDate>
				<author><![CDATA[ developermaster]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ E o programa Assinador do portal da nfe, aquele vc pode colocar os Schemas da tua versão e ele válida a assinatura, utlizava ele na versão PL005a, PL007..etc..<br /> <br /> <a class="snap_shots" href="http://www.nfe.fazenda.gov.br/portal/assinador.aspx" target="_blank" rel="nofollow">http://www.nfe.fazenda.gov.br/portal/assinador.aspx</a><br /> <br /> abraços]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/482727/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/482727/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 8 May 2008 12:11:32]]> GMT</pubDate>
				<author><![CDATA[ adrianokuse]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=developermaster]Bom dia...<br /> <br /> Sim, eu validei o schema com um programa chamado XmlNotepad, ele é um schema válido. Segundo informações da sefaz-MT, o esquema está correto, eles dizem que o erro é na assinatura em si.<br /> <br /> Quanto aquele validador da sefaz, nao rola pra mim pq a versao que a sefaz-mt usa e diferente...[/quote]<br /> <br /> Eu trabalho com a sefaz-mt e eles estão com a versão 1.10.<br /> Parece que já estão aceitando 1.12 também.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/482744/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/482744/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 8 May 2008 12:32:57]]> GMT</pubDate>
				<author><![CDATA[ victorwss]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal, usei o assinador do RS, que usa .net pra assinar, e depois so transmiti com o meu programa em java, dai ele aceita o mardito!!!<br /> <br /> Segui o codigo de Assinatura do pessoal aqui no forum, apenas adaptei pra usar um certificado em arquivo, alguem esta passando pelo mesmo ou tem alguma solucao?<br /> <br /> Segue abaixo o codigo:<br /> <br /> [code]<br /> package com.developermaster.nfe.utils;<br /> <br /> import java.io.BufferedReader;<br /> import java.io.ByteArrayInputStream;<br /> import java.io.ByteArrayOutputStream;<br /> import java.io.File;<br /> import java.io.FileInputStream;<br /> import java.io.FileNotFoundException;<br /> import java.io.FileOutputStream;<br /> import java.io.FileReader;<br /> import java.io.IOException;<br /> import java.io.Serializable;<br /> import java.security.KeyStore;<br /> import java.security.PrivateKey;<br /> import java.security.Provider;<br /> import java.security.cert.X509Certificate;<br /> import java.util.ArrayList;<br /> import java.util.Collections;<br /> import java.util.List;<br /> <br /> import javax.xml.XMLConstants;<br /> import javax.xml.crypto.dsig.CanonicalizationMethod;<br /> import javax.xml.crypto.dsig.DigestMethod;<br /> import javax.xml.crypto.dsig.Reference;<br /> import javax.xml.crypto.dsig.SignatureMethod;<br /> import javax.xml.crypto.dsig.SignedInfo;<br /> import javax.xml.crypto.dsig.Transform;<br /> import javax.xml.crypto.dsig.XMLSignature;<br /> import javax.xml.crypto.dsig.XMLSignatureFactory;<br /> import javax.xml.crypto.dsig.dom.DOMSignContext;<br /> import javax.xml.crypto.dsig.keyinfo.KeyInfo;<br /> import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;<br /> import javax.xml.crypto.dsig.keyinfo.X509Data;<br /> import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;<br /> import javax.xml.crypto.dsig.spec.TransformParameterSpec;<br /> import javax.xml.parsers.DocumentBuilder;<br /> import javax.xml.parsers.DocumentBuilderFactory;<br /> import javax.xml.parsers.ParserConfigurationException;<br /> import javax.xml.transform.Source;<br /> import javax.xml.transform.Transformer;<br /> import javax.xml.transform.TransformerFactory;<br /> import javax.xml.transform.dom.DOMSource;<br /> import javax.xml.transform.stream.StreamResult;<br /> import javax.xml.transform.stream.StreamSource;<br /> import javax.xml.validation.Schema;<br /> import javax.xml.validation.SchemaFactory;<br /> import javax.xml.validation.Validator;<br /> <br /> import org.w3c.dom.Document;<br /> import org.w3c.dom.Element;<br /> import org.w3c.dom.Node;<br /> import org.w3c.dom.NodeList;<br /> import org.xml.sax.SAXException;<br /> <br /> public class Util {	<br /> 		<br /> 	public static String getXmlContent(String xmlFile) {<br /> 		String retorno = "";<br /> 		try {<br /> 			BufferedReader reader = new BufferedReader(new FileReader(xmlFile));<br /> 			String aux = null;<br /> 			while ((aux = reader.readLine()) != null) {<br /> 				retorno += aux;<br /> 			}<br /> 			reader.close();<br /> 		} catch (FileNotFoundException e) {<br /> 			e.printStackTrace();<br /> 		} catch (IOException e) {<br /> 			e.printStackTrace();<br /> 		}<br /> 		return retorno;<br /> 	}<br /> <br /> 	public static void GravaRetorno(String xmlFile, String conteudo) {<br /> 		try {<br /> 			FileOutputStream file = new FileOutputStream(xmlFile, false);<br /> 			file.write(conteudo.getBytes());<br /> 			file.close();<br /> 		} catch (FileNotFoundException e) {<br /> 			e.printStackTrace();<br /> 		} catch (IOException e) {<br /> 			e.printStackTrace();<br /> 		}<br /> 	}<br /> <br /> 	public static void ValidateXml(String xml, String xsd) {<br /> 		try {<br />             // Parse an XML document into a DOM tree.<br />             DocumentBuilder parser = DocumentBuilderFactory.newInstance().newDocumentBuilder();<br />             Document document = parser.parse(new File(xml));<br /> <br />             // Create a SchemaFactory capable of understanding WXS schemas.<br />             SchemaFactory factory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI);<br /> <br />             // Load a WXS schema, represented by a Schema instance.<br />             Source schemaFile = new StreamSource(new File(xsd));<br />             Schema schema = factory.newSchema(schemaFile);<br /> <br />             // Create a Validator object, which can be used to validate<br />             // an instance document.<br />             Validator validator = schema.newValidator();<br /> <br />             // Validate the DOM tree.<br />             validator.validate(new DOMSource(document));<br /> <br />         } catch (ParserConfigurationException e) {<br />             e.printStackTrace();<br />         } catch (SAXException e) {<br />         	e.printStackTrace();<br />         } catch (IOException e) {<br />         	e.printStackTrace();<br />         }<br /> 	}<br /> 	<br /> 	public static String assinarEnviNFe(String xml) throws Exception {<br /> 		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();<br /> 		factory.setNamespaceAware(true);<br /> 		factory.setIgnoringElementContentWhitespace(true);<br /> 		DocumentBuilder builder = factory.newDocumentBuilder();<br /> 		// Document docs = builder.parse(new File(<br /> 		// "c:/xml/430802017886010001735500000000010000030371-nfe.xml"));<br /> 		Document doc = factory.newDocumentBuilder().parse(new File(xml));<br /> 		<br /> 		String providerName = System.getProperty("jsr105Provider", "org.jcp.xml.dsig.internal.dom.XMLDSigRI");<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> 		XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM",(Provider) Class.forName(providerName).newInstance());<br /> <br /> 		// Create a Reference to the enveloped document (in this case,<br /> 		// you are signing the whole document, so a URI of "" signifies<br /> 		// that, and also specify the SHA1 digest algorithm and<br /> 		// the ENVELOPED Transform.<br /> 		ArrayList transformList = new ArrayList();<br /> 		TransformParameterSpec tps = null;<br /> 		Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED, tps);<br /> 		Transform c14NTransform = fac.newTransform("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", tps);<br /> 		<br /> 		transformList.add(c14NTransform);<br /> 		transformList.add(envelopedTransform);<br /> <br /> 		// Load the KeyStore and get the signing key and certificate.<br /> 		KeyStore ks = KeyStore.getInstance(Statics.getKeystoreType());<br /> 		FileInputStream fis = new FileInputStream(Statics.getKeystoreFile());<br /> 		<br /> 		// load the keystore<br /> 		ks.load(fis, Statics.getKeystorePassword().toCharArray());<br /> 		<br /> 		KeyStore.PrivateKeyEntry keyEntry = null;<br /> 		<br /> 		while (ks.aliases().hasMoreElements()) {<br /> 			String alias = ks.aliases().nextElement();<br /> 			if (ks.isKeyEntry(alias)) {<br /> 				keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(Statics.getKeystorePassword().toCharArray()));<br /> 				break;<br /> 			}<br /> 		}<br /> 		<br /> 		X509Certificate cert = (X509Certificate) keyEntry.getCertificate();<br /> <br /> 		// Create the KeyInfo containing the X509Data.<br /> 		KeyInfoFactory kif = fac.getKeyInfoFactory();<br /> 		List x509Content = new ArrayList();<br /> 		x509Content.add(cert);<br /> 		X509Data xd = kif.newX509Data(x509Content);<br /> 		KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> <br /> 		for (int i = 0; i &lt; doc.getDocumentElement()<br /> 				.getElementsByTagName("NFe").getLength(); i++) {<br /> 			assinarNFE(fac, transformList, keyEntry.getPrivateKey(), ki, doc, i);<br /> 		}<br /> 		// Output the resulting document.<br /> 		ByteArrayOutputStream os = new ByteArrayOutputStream();<br /> 		TransformerFactory tf = TransformerFactory.newInstance();<br /> 		Transformer trans = tf.newTransformer();<br /> 		trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 		return os.toString();<br /> 	}<br /> <br /> 	private static void assinarNFE(XMLSignatureFactory fac,<br /> 			ArrayList transformList, PrivateKey privateKey, KeyInfo ki,<br /> 			Document doc, int i) throws Exception {<br /> <br /> 		// Obtem elemento do documento a ser assinado, será criado uma<br /> 		// REFERENCE para o mesmo<br /> 		NodeList elements = doc.getElementsByTagName("infNFe");<br /> 		Element el = (Element) elements.item(i);<br /> 		String id = el.getAttribute("Id");<br /> <br /> 		// doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> 		// ((Element)<br /> 		// doc.getDocumentElement().getElementsByTagName("NFe").item(0))<br /> 		// .setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> <br /> 		Reference ref = fac.newReference("#" + id, fac.newDigestMethod(<br /> 				DigestMethod.SHA1, null), transformList, null, null);<br /> <br /> 		// Create the SignedInfo.<br /> 		SignedInfo si = fac<br /> 				.newSignedInfo(fac.newCanonicalizationMethod(<br /> 						CanonicalizationMethod.INCLUSIVE,<br /> 						(C14NMethodParameterSpec) null), fac<br /> 						.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br /> 						Collections.singletonList(ref));<br /> <br /> 		// Create the XMLSignature, but don't sign it yet.<br /> 		XMLSignature signature = fac.newXMLSignature(si, ki);<br /> <br /> 		// Marshal, generate, and sign the enveloped signature.<br /> 		// Create a DOMSignContext and specify the RSA PrivateKey and<br /> 		// location of the resulting XMLSignature's parent element.<br /> 		DOMSignContext dsc = new DOMSignContext(privateKey, doc<br /> 				.getDocumentElement().getElementsByTagName("NFe").item(i));<br /> 		signature.sign(dsc);<br /> <br /> 	}<br /> 	<br /> 	public static String assinarRaiz(String xml) throws Exception {<br /> 		DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();<br /> 		factory.setNamespaceAware(true);<br /> 		//DocumentBuilder builder = factory.newDocumentBuilder();<br /> 		// Document docs = builder.parse(new File(<br /> 		// "c:/xml/430802017886010001735500000000010000030371-nfe.xml"));<br /> 		Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(xml.getBytes()));<br /> <br /> 		doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> <br /> 		// NodeList elements = doc.getElementsByTagName("infNFe");<br /> 		Node element = doc.getDocumentElement().getFirstChild().getNextSibling();<br /> 		// elements.getLength();<br /> 		Element el = (Element) element;<br /> 		<br /> 		String id = el.getAttribute("Id");<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> 		XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");<br /> <br /> 		// Create a Reference to the enveloped document (in this case,<br /> 		// you are signing the whole document, so a URI of "" signifies<br /> 		// that, and also specify the SHA1 digest algorithm and<br /> 		// the ENVELOPED Transform.<br /> 		ArrayList&lt;Transform&gt; transformList = new ArrayList&lt;Transform&gt;();<br /> 		TransformParameterSpec tps = null;<br /> 		Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED, tps);<br /> 		Transform c14NTransform = fac.newTransform("http://www.w3.org/TR/2001/REC-xml-c14n-20010315", tps);<br /> <br /> 		transformList.add(envelopedTransform);<br /> 		transformList.add(c14NTransform);<br /> <br /> 		// Load the KeyStore and get the signing key and certificate.<br /> 		KeyStore ks = KeyStore.getInstance(Statics.getKeystoreType());<br /> 		FileInputStream fis = new FileInputStream(Statics.getKeystoreFile());<br /> 		//load the keystore<br /> 		ks.load(fis, Statics.getKeystorePassword().toCharArray());<br /> 		String alias = ks.aliases().nextElement();<br /> 		KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(Statics.getKeystorePassword().toCharArray()));<br /> <br /> 		//get the private key for signing.<br /> 		//PrivateKey privateKey = (PrivateKey) ks.getKey(privateKeyAlias, privateKeyPass.toCharArray());<br /> 		<br /> 		X509Certificate cert = (X509Certificate) keyEntry.getCertificate();<br /> 		<br /> 		// Create the KeyInfo containing the X509Data.<br /> 		KeyInfoFactory kif = fac.getKeyInfoFactory();<br /> 		List&lt;Serializable&gt; x509Content = new ArrayList&lt;Serializable&gt;();<br /> 		x509Content.add(cert.getSubjectX500Principal().getName());<br /> 		x509Content.add(cert);<br /> 		X509Data xd = kif.newX509Data(x509Content);<br /> 		KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> 		<br /> 		doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> 		// ((Element)<br /> 		// doc.getDocumentElement().getElementsByTagName("NFe").item(0))<br /> 		// .setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> <br /> 		// Create a DOM XMLSignatureFactory that will be used to<br /> 		// generate the enveloped signature.<br /> <br /> 		Reference ref = fac.newReference("#" + id, fac.newDigestMethod(<br /> 				DigestMethod.SHA1, null), transformList, null, null);<br /> <br /> 		// Create the SignedInfo.<br /> 		SignedInfo si = fac<br /> 				.newSignedInfo(fac.newCanonicalizationMethod(<br /> 						CanonicalizationMethod.INCLUSIVE,<br /> 						(C14NMethodParameterSpec) null), fac<br /> 						.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br /> 						Collections.singletonList(ref));<br /> <br /> 		// Create the XMLSignature, but don't sign it yet.<br /> 		XMLSignature signature = fac.newXMLSignature(si, ki);<br /> <br /> 		// Marshal, generate, and sign the enveloped signature.<br /> 		// Create a DOMSignContext and specify the RSA PrivateKey and<br /> 		// location of the resulting XMLSignature's parent element.<br /> 		DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc<br /> 				.getDocumentElement());<br /> 		signature.sign(dsc);<br /> <br /> 		// Output the resulting document.<br /> 		ByteArrayOutputStream os = new ByteArrayOutputStream();<br /> 		TransformerFactory tf = TransformerFactory.newInstance();<br /> 		Transformer trans = tf.newTransformer();<br /> 		trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 		return os.toString();<br /> 	}<br /> }<br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/490299/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/490299/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 21 May 2008 19:15:16]]> GMT</pubDate>
				<author><![CDATA[ developermaster]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Entao, ninguem conseguiu assinar usando um arquivo pfx ou p12???]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/491783/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/491783/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 26 May 2008 10:48:45]]> GMT</pubDate>
				<author><![CDATA[ developermaster]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ boa tarde!!!<br /> <br /> Eu consegui assinar cada arquivo de nfe individualemente usando um arquivo PFX de certificado.<br /> SEgue em anexo o código.<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/497421/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/497421/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 3 Jun 2008 14:10:58]]> GMT</pubDate>
				<author><![CDATA[ adrianokuse]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Bom dia pessoal, <br />   Alguém já conseguiu fazer conexão, envio e retorno de xml de algum dos Web Services da NF-e. Se alguem tiver um exemplo ficaria grato se pudesse me enviar ou colocar no forum.<br />  Adrianolkp@gmail.com<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/500272/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/500272/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 9 Jun 2008 06:53:53]]> GMT</pubDate>
				<author><![CDATA[ adrianokuse]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Alem das rotinas de assinatura da NFe, vocês também tem a implementação do cliente WebService?<br /> <br /> Teria como postar aqui no tópico ou enviar para <a class="snap_shots" href="mailto:bhermont@gmail.com">bhermont@gmail.com</a> ?<br /> <br /> Obrigado<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/508879/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/508879/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 24 Jun 2008 11:53:48]]> GMT</pubDate>
				<author><![CDATA[ Berkamps]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ <br /> Como consigo gerar o arquivo pfx a partir do token?<br /> <br /> Alguma dica?<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/509683/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/509683/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 25 Jun 2008 14:23:24]]> GMT</pubDate>
				<author><![CDATA[ Berkamps]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ O Arquivo pfx vc nao gera, ele é o certificado q vc tem de adquiri junto a uma autoridade certificadora.<br /> <br /> Quanto ao consumo dos webservices, procure pelo AXIS, da apache.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/509716/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/509716/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 25 Jun 2008 14:48:26]]> GMT</pubDate>
				<author><![CDATA[ developermaster]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Ola pessoal,<br /> Alguém por acaso poderia me enviar o arquivo dkck201.dll, pois eu não consegui encontrar no windows vista <img src="http://www.guj.com.br/images/smilies/9d71f0541cff0a302a0309c5079e8dee.gif" border="0"><br /> Melhor, realmente é necessário o uso dessa dll, junto do exemplo postado?<br /> <br /> Abraços,<br /> Alexandre.<br /> <br /> email: <a class="snap_shots" href="mailto:alexrosa@gmail.com">alexrosa@gmail.com</a>]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/511547/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/511547/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Sat, 28 Jun 2008 00:16:35]]> GMT</pubDate>
				<author><![CDATA[ alexrosa]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal, ao executar o código da assinatura da NFe que foi fornecido nos posts anteriores,  me deparei com o seguinte erro:<br /> <br /> [b]Private keys must be instance of RSAPrivate(Crt)Key or have PKCS#8 encoding[/b]<br /> <br /> Na parte de assinatura:<br /> <br /> [code]<br />       // Marshal, generate, and sign the enveloped signature.  <br />       // Create a DOMSignContext and specify the RSA PrivateKey and  <br />       // location of the resulting XMLSignature's parent element.  <br />       DOMSignContext dsc = new DOMSignContext(privateKey, doc.getElementsByTagName("NFe").item(i));  <br />       signature.sign(dsc);  <br /> [/code]<br /> <br /> <br /> [code]Exception in thread "main" javax.xml.crypto.dsig.XMLSignatureException: java.security.InvalidKeyException: Private keys must be instance of RSAPrivate(Crt)Key or have PKCS#8 encoding<br /> 	at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(DOMXMLSignature.java:376)<br /> 	at com.chart.julianosott.NFEUtils.assinarNFE(NFEUtils.java:155)<br /> 	at com.chart.julianosott.NFEUtils.assinarEnviNFe(NFEUtils.java:115)<br /> 	at com.chart.testcases.TrustExample.main(TrustExample.java:75)<br /> Caused by: java.security.InvalidKeyException: Private keys must be instance of RSAPrivate(Crt)Key or have PKCS#8 encoding<br /> 	at sun.security.rsa.RSAKeyFactory.translatePrivateKey(RSAKeyFactory.java:246)<br /> 	at sun.security.rsa.RSAKeyFactory.engineTranslateKey(RSAKeyFactory.java:149)<br /> 	at sun.security.rsa.RSAKeyFactory.toRSAKey(RSAKeyFactory.java:79)<br /> 	at sun.security.rsa.RSASignature.engineInitSign(RSASignature.java:90)<br /> 	at sun.security.rsa.RSASignature.engineInitSign(RSASignature.java:84)<br /> 	at java.security.Signature$Delegate.init(Signature.java:1073)<br /> 	at java.security.Signature$Delegate.chooseProvider(Signature.java:1033)<br /> 	at java.security.Signature$Delegate.engineInitSign(Signature.java:1097)<br /> 	at java.security.Signature.initSign(Signature.java:480)<br /> 	at org.jcp.xml.dsig.internal.dom.DOMRSASignatureMethod.sign(DOMRSASignatureMethod.java:134)<br /> 	at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(DOMXMLSignature.java:373)<br /> 	... 3 more<br /> java.security.InvalidKeyException: Private keys must be instance of RSAPrivate(Crt)Key or have PKCS#8 encoding<br /> 	at sun.security.rsa.RSAKeyFactory.translatePrivateKey(RSAKeyFactory.java:246)<br /> 	at sun.security.rsa.RSAKeyFactory.engineTranslateKey(RSAKeyFactory.java:149)<br /> 	at sun.security.rsa.RSAKeyFactory.toRSAKey(RSAKeyFactory.java:79)<br /> 	at sun.security.rsa.RSASignature.engineInitSign(RSASignature.java:90)<br /> 	at sun.security.rsa.RSASignature.engineInitSign(RSASignature.java:84)<br /> 	at java.security.Signature$Delegate.init(Signature.java:1073)<br /> 	at java.security.Signature$Delegate.chooseProvider(Signature.java:1033)<br /> 	at java.security.Signature$Delegate.engineInitSign(Signature.java:1097)<br /> 	at java.security.Signature.initSign(Signature.java:480)<br /> 	at org.jcp.xml.dsig.internal.dom.DOMRSASignatureMethod.sign(DOMRSASignatureMethod.java:134)<br /> 	at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(DOMXMLSignature.java:373)<br /> 	at com.chart.julianosott.NFEUtils.assinarNFE(NFEUtils.java:155)<br /> 	at com.chart.julianosott.NFEUtils.assinarEnviNFe(NFEUtils.java:115)<br /> 	at com.chart.testcases.TrustExample.main(TrustExample.java:75)<br /> [/code]<br /> <br /> Estou utilizando o JDK6, update 10.  Alguém obteve o mesmo erro ou sabe como resolvê-lo?<br /> <br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/520181/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/520181/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 14 Jul 2008 12:46:03]]> GMT</pubDate>
				<author><![CDATA[ Berkamps]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[  .]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/534868/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/534868/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 7 Aug 2008 10:20:26]]> GMT</pubDate>
				<author><![CDATA[ jcainelli]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Boa tarde pessoal, <br /> <br /> Queria a ajuda de vocês para fazer a chamada do web service e o envio do meu xml pra eles.<br /> Como vcs fizeram isso???<br /> <br /> Tou começando nisso agora e tou quebrando a cabeça aki, se alguém puder me ajudar...<br /> <br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/553268/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/553268/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 9 Sep 2008 13:03:27]]> GMT</pubDate>
				<author><![CDATA[ tspaulino]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Bem pessoal, <br /> <br /> Depois de alguns dias rachando o crânio, consegui adaptar um método para assinatura de XML's para envio de NF-e.<br /> Fiz o uso dele no arquivo disponibilizado para teste no site:<br /> E coloquei no link: <br /> para validar a assinatura e foi tudo ok!!<br /> <br /> RELEMBRANDO: ele assina o XML, mas com base nos dados que este já tem. Para assiná-lo você já deve estar com a chave de acesso OK e todos os campos validados. ELE REALMENTE SÓ ASSINA O XML.<br /> <br /> Enfim, tá ae o código:<br /> [code]<br /> import java.security.*;<br /> import java.security.Certificate;<br /> import java.security.cert.*;<br /> import java.io.*;<br /> import java.util.*;<br /> import javax.xml.parsers.*;<br /> import javax.xml.transform.*;<br /> import javax.xml.transform.dom.DOMSource;<br /> import javax.xml.transform.stream.StreamResult;<br /> import javax.xml.crypto.dsig.*;<br /> import javax.xml.crypto.dsig.dom.DOMSignContext;<br /> import javax.xml.crypto.dsig.keyinfo.*;<br /> import javax.xml.crypto.dsig.spec.*;<br /> <br /> import org.w3c.dom.Document;<br /> import org.w3c.dom.NodeList;<br /> <br /> <br /> <br /> public class TratadorCertificado{<br /> 	/*<br /> 	 * 	Classe para tratamento de certificados. Deve fazer a manipulacao<br /> 	 * dos certificados exportando chaves, assinando XML's e demais funcoes.<br /> 	 *<br /> 	 */	<br /> 	public static final String algoritmo= "RSA"; <br /> 	public static final String algoritmoAssinatura= "MD5withRSA"; <br /> 	private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";<br /> 	public static File file= new File("Caminho da Keystore .jks");<br /> 	private static String alias="seu alias";<br /> 	private static char[] senha="sua senha".toCharArray(); <br /> 	static XMLSignatureFactory sig;<br /> 	static X509Certificate cert;<br /> 	static KeyInfo ki; <br /> 	static SignedInfo si;<br /> 	static KeyStore rep;<br /> 	<br /> 	public static PrivateKey getChavePrivada() throws Exception{<br /> 				<br /> 		InputStream entrada= new FileInputStream(file);<br /> 		rep.load(entrada, senha);<br /> 		entrada.close();<br /> 		Key chavePrivada= (Key) rep.getKey(alias, senha);<br /> 		if(chavePrivada instanceof PrivateKey){<br /> 			System.out.println("Chave Privada encontrada!");<br /> 			return (PrivateKey) chavePrivada;<br /> 		}<br /> 		return null;		<br /> 	}<br /> 	<br /> 	public static PublicKey getChavePublica() throws Exception{<br /> 			<br /> 		InputStream entrada= new FileInputStream(file);<br /> 		rep.load(entrada, senha);<br /> 		entrada.close();<br /> 		Key chave= (Key) rep.getKey(alias, senha);		<br /> 		java.security.Certificate cert= (java.security.Certificate) rep.getCertificate(alias);//O tipo de dado é declarado desse modo por haver ambigüidade (Classes assinadas com o mesmo nome "Certificate")<br /> 		PublicKey chavePublica= cert.getPublicKey();<br /> 		System.out.println("Chave Pública encontrada!");<br /> 		return chavePublica;		<br /> 	}<br /> 	<br /> 	public static boolean verificarAssinatura(PublicKey chave, byte[] buffer, byte[] assinado) throws Exception{<br /> 		<br /> 		Signature assinatura= Signature.getInstance(algoritmoAssinatura);<br /> 		assinatura.initVerify(chave);<br /> 		assinatura.update(buffer, 0, buffer.length);<br /> 		return assinatura.verify(assinado);<br /> 	}<br /> 	<br /> 	public static byte[] criarAssinatura(PrivateKey chavePrivada, byte[] buffer) throws Exception{<br /> 		<br /> 		Signature assinatura= Signature.getInstance(algoritmoAssinatura);		<br /> 		assinatura.initSign(chavePrivada);<br /> 		assinatura.update(buffer, 0, buffer.length);<br /> 		return assinatura.sign();<br /> 	}<br /> 	<br /> 	public static String getValidade(X509Certificate cert){<br /> 		try{<br /> 			cert.checkValidity();<br /> 			return "Certificado válido!";<br /> 		}<br /> 		catch(CertificateExpiredException e){<br /> 			return "Certificado expirado!";<br /> 		}<br /> 		catch(CertificateNotYetValidException e){<br /> 			return "Certificado inválido!";<br /> 		}		<br /> 	}	<br /> 	<br /> 	public static void getCertificado() throws Exception{					<br /> 		InputStream dado= new FileInputStream(file);		<br /> 		rep= KeyStore.getInstance("JKS");		<br /> 		rep.load(dado, senha);<br /> 		cert= (X509Certificate) rep.getCertificate(alias);<br /> 		String retorno= TratadorCertificado.getValidade(cert);<br /> 		System.out.println(retorno);		<br /> 	}	<br /> 	<br /> 	public static void assinarDocumento(String localDocumento) throws Exception{		<br /> 		DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();<br /> 		dbf.setNamespaceAware(true);<br /> 		Document doc = dbf.newDocumentBuilder().parse<br /> 		    (new FileInputStream(localDocumento));<br /> 		System.out.println("Documento ok!");<br /> 		<br /> 		sig= XMLSignatureFactory.getInstance("DOM");<br /> 		<br /> 		ArrayList&lt;Transform&gt; transformList= new ArrayList&lt;Transform&gt;();<br /> 		Transform enveloped= sig.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);<br /> 		Transform c14n= sig.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null);<br /> 		transformList.add(enveloped);<br /> 		transformList.add(c14n);<br /> 		<br /> 		NodeList elements = doc.getElementsByTagName("infNFe");<br /> 		org.w3c.dom.Element el = (org.w3c.dom.Element) elements.item(0);<br /> 		String id = el.getAttribute("Id");<br /> 		Reference r= sig.newReference		<br /> 		 ("#".concat(id), sig.newDigestMethod(DigestMethod.SHA1, null),<br /> 				  transformList,<br /> 				     null, null);<br /> 		si = sig.newSignedInfo(<br /> 			sig.newCanonicalizationMethod<br /> 				(CanonicalizationMethod.INCLUSIVE,<br /> 					(C14NMethodParameterSpec) null),<br /> 						sig.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br /> 						Collections.singletonList(r)						<br /> 		);<br /> 		<br /> 		KeyInfoFactory kif = sig.getKeyInfoFactory();<br /> 		List x509Content = new ArrayList();		<br /> 		x509Content.add(cert);<br /> 		X509Data xd = kif.newX509Data(x509Content);<br /> 		ki = kif.newKeyInfo(Collections.singletonList(xd));		<br /> 		<br /> 		DOMSignContext dsc = new DOMSignContext<br /> 	    (getChavePrivada(), doc.getDocumentElement());<br /> 		XMLSignature signature = sig.newXMLSignature(si, ki);<br /> 		signature.sign(dsc);<br /> 		OutputStream os = new FileOutputStream("Nome do arquivo de saída");<br /> 		TransformerFactory tf = TransformerFactory.newInstance();<br /> 		Transformer trans = tf.newTransformer();<br /> 		trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 		<br /> 	}<br /> 	<br /> 	public static void main(String[] args) {<br /> 		try{<br /> 			TratadorCertificado.getCertificado();			<br /> 			TratadorCertificado.assinarDocumento("Caminho da XML para ser assinada");<br /> 		}<br /> 		catch(Exception e){<br /> 			e.printStackTrace();<br /> 		}<br /> 	<br /> 	}<br /> 	<br /> }<br /> [/code]<br /> <br /> Qualquer dúvidam, entrem em contato via MP.<br /> <br /> Obrigado a todos os colegas que têm postado as suas soluções aqui. Profissionais inexperientes como eu (3 semanas :P ) aprendem muito a partir das dicas dos colegas.<br /> <br /> Abraço,<br /> <br /> Tiago Paulino.<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/557132/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/557132/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 16 Sep 2008 14:23:14]]> GMT</pubDate>
				<author><![CDATA[ tspaulino]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=alexandretalbert]Olá,<br /> <br /> Estou iniciando com SOAP tbm para um projeto de NFE. Alguém poderiam postar o código que transmite o arquivo após a assinatura?<br /> <br /> Muito Obrigado!![/quote]<br /> <br /> <br /> voce tera q implementar o webservice, <br /> <a class="snap_shots" href="http://www.guj.com.br/posts/list/30/72325.java#553800" target="_blank" rel="nofollow">http://www.guj.com.br/posts/list/30/72325.java#553800</a><br /> aqui tem o codigo com expemplo pra gerar as classes que acessam<br /> <br /> abraço]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/557248/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/557248/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 16 Sep 2008 15:48:56]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Galera,<br /> <br /> Estou seguindo o código do julianosott postado na primeira página desse tópico. Quando assino a minha nota fiscal ela esta vindo com a seguinte tag:<br /> [code]<br /> &lt;?xml version="1.0" encoding="UTF-8" standalone="no"?&gt;<br /> [/code]<br /> <br /> Alguem sabe como que eu tiro essa propriedade [b]standalone[/b] dessa tag?<br /> <br /> Acho que é isso que esta quebrando as minhas pernas na hora do envio da nota fiscal.<br /> Estou usando java 1.5_10.<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/597720/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/597720/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 25 Nov 2008 15:10:13]]> GMT</pubDate>
				<author><![CDATA[ vcsmetallica]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Galera,<br /> <br /> Achei aqui, se alguem passar por isso é so colocar assim:<br /> [code]<br /> doc.setXmlStandalone(true);<br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/597732/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/597732/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 25 Nov 2008 15:34:38]]> GMT</pubDate>
				<author><![CDATA[ vcsmetallica]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ boa tarde pessoal<br /> alguem sabe algo sobre isso???<br /> <br /> <a class="snap_shots" href="http://nfe.sef.sc.gov.br/index.php?option=com_content&task=view&id=75&Itemid=54" target="_blank" rel="nofollow">http://nfe.sef.sc.gov.br/index.php?option=com_content&task=view&id=75&Itemid=54</a><br /> <br /> abraço]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/598225/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/598225/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 26 Nov 2008 12:39:24]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=julianosott]Consegui terminar os métodos que eu queria. Fiz dois métodos que recebem uma string com o xml e retornam uma String como o xml assinado. O primeiro pega um enviNFe e assina todas as NFe dentro dele. O outro assina o elemento raíz do xml, servindo para o cancelamento e para a inutilização da nota.<br /> <br /> aqui vai o método para assinar o enviNFe:<br /> ...<br /> <br /> Quem quiser verificar o xml pode usar esse site: <a class="snap_shots" href="http://www.sefaz.rs.gov.br/AAE_ROOT/NFE/SAT-WEB-NFE-VAL_1.asp" target="_blank" rel="nofollow">http://www.sefaz.rs.gov.br/AAE_ROOT/NFE/SAT-WEB-NFE-VAL_1.asp</a> Acho que ele só valida os certificados do Rio Grande do Sul, mas o bom é que ele verifica a estrutura do xml tb.<br /> <br /> É isso por enquanto, qualquer coisa é só perguntar.[/quote]<br /> <br /> Tenho tido casos estranhos de Assinatura invalida de uma nota dentro de lote com varias outras.<br /> Explico os detalhes:<br /> <br /> Uma nota x, gerada seu xml e assinada passa pelo validador tanto do site acima como no programa fornecido pela SEFAZ, o "AssinadorRS v2.1.0".<br /> Dentro do mesmo programa, gerando um lote com esta nota (ja validada pelo dito), o lote gerado resulta em "Assinatura INVALIDA".<br /> <br /> Prestem atencao ao detalhe que, sem sair do programa AssinadorRS v2.1.0, a nota avulsa valida e a mesma dentro de um lote nao valida.<br /> <br /> O suporte da NFe me relatou na sua ultima resposta:<br /> [i]<br /> Pode estar acontecendo 2 erros:<br /> <br /> - o primeiro é o uso de algum caractere especial não permitido (&lt;  &gt;  &  "  ') - ver pg. 69 manual de integração - contribuinte.<br /> <br /> A outra possibilidade é de a nota estar sendo alterada entre a assinatura e a transmissão da NF-e<br /> [/i]<br /> <br /> Duvida: se o xml da nota avulsa tivesse algum caracter nao permitido, teria validado no schema e na assinatura?<br /> A segunda hipotese cai por agua, pelos testes que fiz.<br /> <br /> Se alguem ja passou por isso ou se tiver alguma dica, por favor, retornem o quanto antes possivel.<br /> <br /> Grato<br /> <br /> Alencar<br /> P.S.: Em anexo os result do AssinadorRS v2.1.0. Por motivos de sigilo, nao posso anexar os xml.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/600126/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/600126/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Sat, 29 Nov 2008 10:41:40]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=philler]<br /> Tenho tido casos estranhos de Assinatura invalida de uma nota dentro de lote com varias outras.<br /> Explico os detalhes:<br /> <br /> Uma nota x, gerada seu xml e assinada passa pelo validador tanto do site acima como no programa fornecido pela SEFAZ, o "AssinadorRS v2.1.0".<br /> Dentro do mesmo programa, gerando um lote com esta nota (ja validada pelo dito), o lote gerado resulta em "Assinatura INVALIDA".<br /> <br /> Prestem atencao ao detalhe que, sem sair do programa AssinadorRS v2.1.0, a nota avulsa valida e a mesma dentro de um lote nao valida.<br /> <br /> O suporte da NFe me relatou na sua ultima resposta:<br /> [i]<br /> Pode estar acontecendo 2 erros:<br /> <br /> - o primeiro é o uso de algum caractere especial não permitido (&lt;  &gt;  &  "  ') - ver pg. 69 manual de integração - contribuinte.<br /> <br /> A outra possibilidade é de a nota estar sendo alterada entre a assinatura e a transmissão da NF-e<br /> [/i]<br /> <br /> Duvida: se o xml da nota avulsa tivesse algum caracter nao permitido, teria validado no schema e na assinatura?<br /> A segunda hipotese cai por agua, pelos testes que fiz.<br /> <br /> Se alguem ja passou por isso ou se tiver alguma dica, por favor, retornem o quanto antes possivel.<br /> <br /> Grato<br /> <br /> Alencar<br /> P.S.: Em anexo os result do AssinadorRS v2.1.0. Por motivos de sigilo, nao posso anexar os xml.[/quote]<br /> <br /> Respondendo ao meu proprio email, descobri apos 2 dias intensos de testes.<br /> Dentro do campo observacao da nota, constava algo do tipo "Entrega: Rua Etc, 123456", onde entre o : e a primeira letra<br /> tinha DOIS ESPACOS.<br /> Tirando um deles tudo volta a funcionar.<br /> <br /> Pergunto aos amigos: que b...ta de regra e' esta que o usuario nao pode preencher um campo texto de 60 caracteres do jeito<br /> que ele bem entende ou precisa?<br /> Sao BURROCRACIAS assim que trancam um processo simples como a NFe.<br /> <br /> Alencar ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/600473/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/600473/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Sun, 30 Nov 2008 18:24:17]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ é realmente, a nf-e tem umas regras bem chatinhas.... mas por outro lado é bom pra manter a integridade dos dados....<br /> <br /> estou usando xstream pra gerar o xml, ele ja substitui os &lt; &gt; & e tals, pra nao dar problema no xml, isso é uma coisa útil, acredito que o jaxb tbm faça isso... <br /> <br /> o que andou me encomodando, é o campo obs que no nosso sistema aceita \r\n (enter do windows) e no xml isso estava dando problema, tive de tratar usando o replaceALL do String....<br /> <br /> abraço]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/600812/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/600812/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 1 Dec 2008 11:34:14]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ boa tarde pessoal estou usado o iKey2032 que (pelo que entendi) usa a dll dkck201.dll<br /> <br /> to com uns problemas....<br /> ta dando (403)Forbiden quando vou acessar os webservice...<br /> <br /> estou setando as propriedades assim:<br /> <br /> [code]<br /> System.setProperty("javax.net.ssl.keyStoreType", "pkcs11");<br /> 	        System.setProperty("javax.net.ssl.keyStorePassword", certPass);<br /> 	        Provider pr = new sun.security.pkcs11.SunPKCS11("token.cfg");	        <br /> 	        java.security.Security.addProvider(pr);<br /> [/code]<br /> <br /> meu arquivo token.cfg ta assim<br /> [code]<br /> library=C:\WINDOWS\system32\dkck201.dll<br /> name=Safenetikey2032<br /> [/code]<br /> <br /> alguem sabe o que pode estar errado???<br /> alguem ja usou esse token?<br /> <br /> abraço!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/601555/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/601555/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 2 Dec 2008 13:33:59]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=f-schmitt]boa tarde pessoal estou usado o iKey2032 que (pelo que entendi) usa a dll dkck201.dll<br /> <br /> to com uns problemas....<br /> ta dando (403)Forbiden quando vou acessar os webservice...<br /> <br /> estou setando as propriedades assim:<br /> <br /> [code]<br /> System.setProperty("javax.net.ssl.keyStoreType", "pkcs11");<br /> 	        System.setProperty("javax.net.ssl.keyStorePassword", certPass);<br /> 	        Provider pr = new sun.security.pkcs11.SunPKCS11("token.cfg");	        <br /> 	        java.security.Security.addProvider(pr);<br /> [/code]<br /> <br /> meu arquivo token.cfg ta assim<br /> [code]<br /> library=C:\WINDOWS\system32\dkck201.dll<br /> name=Safenetikey2032<br /> [/code]<br /> <br /> alguem sabe o que pode estar errado???<br /> alguem ja usou esse token?<br /> <br /> abraço![/quote]<br /> <br /> Tente alterar para isso:<br /> [code]<br /> 			// configura o acesso dos certificados de validacao<br /> 			System.setProperty("javax.net.ssl.trustStoreType", "PKCS11");<br /> 			System.setProperty("javax.net.ssl.trustStore", "NONE");<br /> 			System.setProperty("javax.net.ssl.trustStoreProvider", "SunPKCS11-Safenetikey2032");<br /> 			System.setProperty("javax.net.ssl.trustStoreAlias", alias);<br /> 			System.setProperty("javax.net.ssl.trustStorePassword", passwd);<br /> <br /> 			// configura o acesso ao certificado do cliente<br /> 			System.setProperty("javax.net.ssl.keyStoreType", "PKCS11");<br /> 			System.setProperty("javax.net.ssl.keyStore", "NONE");<br /> 			System.setProperty("javax.net.ssl.keyStoreProvider", "SunPKCS11-Safenetikey2032");<br /> 			System.setProperty("javax.net.ssl.keyStoreAlias", alias);<br /> 			System.setProperty("javax.net.ssl.keyStorePassword", passwd);<br /> [/code]<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/601598/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/601598/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 2 Dec 2008 14:27:43]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ OPA, vou testar aqui...<br /> <br /> o trust nao vou trocar pq ja uso assim, ok?<br /> <br /> [code]<br /> System.setProperty("javax.net.ssl.trustStoreType", "JKS");<br /> System.setProperty("javax.net.ssl.trustStore", "jssecacerts");<br /> System.setProperty("javax.net.ssl.trustStorePassword", "changeit");<br /> [/code]<br /> <br /> o que voce coloca no ALIAS?<br /> <br /> VALEU!!!!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/601639/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/601639/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 2 Dec 2008 15:21:01]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ troquei la<br /> <br /> <br /> fiz assim:<br /> <br /> [code]<br /> System.setProperty("javax.net.ssl.keyStoreType", "PKCS11");<br /> System.setProperty("javax.net.ssl.keyStore", "NONE");<br /> System.setProperty("javax.net.ssl.keyStoreProvider", "SunPKCS11-Safenetikey2032");<br /> System.setProperty("javax.net.ssl.keyStoreAlias", "Safenetikey2032");<br /> System.setProperty("javax.net.ssl.keyStorePassword", certPass);<br /> [/code]<br /> <br /> deu erro denovo<br /> no debug <br /> deu isso<br /> <br /> [list]<br /> keyStore is : NONE<br /> keyStore type is : PKCS11<br /> keyStore provider is : SunPKCS11-Safenetikey2032<br /> init keystore<br /> default context init failed: java.security.NoSuchProviderException: no such prov<br /> ider: SunPKCS11-Safenetikey2032<br /> [/list]<br /> <br /> o card funcionou tao bem,,, agora o token ta me deixando preocupado....<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/601657/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/601657/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 2 Dec 2008 15:37:33]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=f-schmitt]<br /> deu erro denovo<br /> no debug <br /> deu isso<br /> <br /> [list]<br /> keyStore is : NONE<br /> keyStore type is : PKCS11<br /> keyStore provider is : SunPKCS11-Safenetikey2032<br /> init keystore<br /> default context init failed: java.security.NoSuchProviderException: no such prov<br /> ider: SunPKCS11-Safenetikey2032<br /> [/list]<br /> [/quote]<br /> <br /> Este erro é tipico quando o nome dentro do .cfg esta errado.<br /> Tente algumas alteracoes neste nome, tipo name = Card, e no provider toque por SunPKCS11Card.<br /> Sei que passei por isso e era no nome o problema. <br /> O que acontece no caso java.security.NoSuchProviderException é porque nao encontrou a dll.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/601748/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/601748/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 2 Dec 2008 16:57:03]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ pessoal alguem poderia me ajudar estou usando o codigo deixado acima mais estou com um pequeno problema em resolver este erro aqui <br /> <br /> java.lang.NullPointerException<br /> 	at TratadorCertificado.getValidade(TratadorCertificado.java:82)<br /> 	at TratadorCertificado.getCertificado(TratadorCertificado.java:100)<br /> 	at TratadorCertificado.main(TratadorCertificado.java:159)<br /> <br /> ja aconteceu com alguem ?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/636623/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/636623/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 9 Feb 2009 14:52:41]]> GMT</pubDate>
				<author><![CDATA[ evandromib]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=evandromib]pessoal alguem poderia me ajudar estou usando o codigo deixado acima mais estou com um pequeno problema em resolver este erro aqui <br /> <br /> java.lang.NullPointerException<br /> 	at TratadorCertificado.getValidade(TratadorCertificado.java:82)<br /> 	at TratadorCertificado.getCertificado(TratadorCertificado.java:100)<br /> 	at TratadorCertificado.main(TratadorCertificado.java:159)<br /> <br /> ja aconteceu com alguem ?[/quote]<br /> <br /> Poderia especificar qual dos codigos acima voce esta usando?<br /> Ja debugou para ver onde da o erro exatamente?<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/636668/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/636668/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 9 Feb 2009 15:32:31]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ o codigo postado pelo tspaulino <br /> <br /> consegui ajustar alguns erros e wargings <br /> <br /> mais estão aparecendo estes erros aqui qdo executo ele <br /> <br /> java.io.IOException: Keystore was tampered with, or password was incorrect<br /> 	at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:771)<br /> 	at sun.security.provider.JavaKeyStore$JKS.engineLoad(JavaKeyStore.java:3<img src="http://www.guj.com.br/images/smilies/b2eb59423fbf5fa39342041237025880.gif" border="0"><br /> 	at java.security.KeyStore.load(KeyStore.java:1185)<br /> 	at TratadorCertificado.getCertificado(TratadorCertificado.java:121)<br /> 	at TratadorCertificado.getCertificado(TratadorCertificado.java:121)<br /> Caused by: java.security.UnrecoverableKeyException: Password verification failed<br /> 	at sun.security.provider.JavaKeyStore.engineLoad(JavaKeyStore.java:769)<br /> <br /> fiz todas as instalações e  importações referentes a os certificados será que esta faltando mais coisas ?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/636695/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/636695/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 9 Feb 2009 15:48:05]]> GMT</pubDate>
				<author><![CDATA[ evandromib]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=reinaldoaraujo]Boa tarde pessoal,<br /> <br />     Estou tentando assinar um XML da NFe usando o código acima, já consegui efetuar a conexão com o web-server usando o código abaixo:<br /> [b]<br /> System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");<br /> Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());<br /> <br /> System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");<br /> System.setProperty("javax.net.ssl.keyStore", verConf.getPathKeyPFX());<br /> System.setProperty("javax.net.ssl.keyStorePassword", "xxxx");<br /> <br /> System.setProperty("javax.net.ssl.trustStoreType", "JKS");<br /> System.setProperty("javax.net.ssl.trustStore",verConf.getPathKeyJKS());<br /> [/b]<br /> <br /> Alguem já conseguiu assinar um XML NFe usando somente o arquivo .pfx   ??[/quote]<br /> <br /> O path que você usa é o completo do arquivo (/Users/ze/certificado.pfx) ou relativo ao classpath (/certs/certificado.pfx)?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/658410/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/658410/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 23 Mar 2009 17:42:21]]> GMT</pubDate>
				<author><![CDATA[ andrefariagomes]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ ola<br /> estou tendo problemas com a assinatura da nfe. (estou usando o codigo daqui <a class="snap_shots" href="http://www.guj.com.br/posts/list/30/83758.java" target="_blank" rel="nofollow">http://www.guj.com.br/posts/list/30/83758.java</a>)<br />  eu envio o xml de lote vai tranquilo,ai qdo vou consultar <br /> me retorma a seguinte msg: "Rejeição: Certificado Assinatura inválido". estou consumindo o ws do PR<br /> Agora eu queria saber... eu estou usando o certificado .pfx para fazer essa assinatura. <br /> Tenho que fazer alguma coisa a mais com o certificado? apenas com o pfx da para fazer a assinatura normalmente??<br /> <br /> abraço]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/672959/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/672959/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 09:10:50]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=alves.Felipe]ola<br /> estou tendo problemas com a assinatura da nfe. (estou usando o codigo daqui <a class="snap_shots" href="http://www.guj.com.br/posts/list/30/83758.java" target="_blank" rel="nofollow">http://www.guj.com.br/posts/list/30/83758.java</a>)<br />  eu envio o xml de lote vai tranquilo,ai qdo vou consultar <br /> me retorma a seguinte msg: "Rejeição: Certificado Assinatura inválido". estou consumindo o ws do PR<br /> Agora eu queria saber... eu estou usando o certificado .pfx para fazer essa assinatura. <br /> Tenho que fazer alguma coisa a mais com o certificado? apenas com o pfx da para fazer a assinatura normalmente??<br /> <br /> abraço[/quote]<br /> <br /> Tive este problema e era espacos entre palavras, tipo assim: "palavra  palavra".<br /> O problema é os dois espacos (ou mais) entre palavras. Só pode ter um.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/672974/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/672974/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 09:28:37]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Bom dia, somente com o pfx é o suficiente para assinar a nfe, para transmitir precisa de mais alguns certificados,,,,<br /> antes de enviar valide a NFe/Lote no site<br /> <a class="snap_shots" href="http://www.sefaz.rs.gov.br/NFE/NFE-VAL.aspx" target="_blank" rel="nofollow">http://www.sefaz.rs.gov.br/NFE/NFE-VAL.aspx</a><br /> ai voce vai ter certeza se há algo de errado na &lt;Signature&gt;<br /> <br /> <br /> abraço]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673040/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673040/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 10:12:37]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ f-schmitt, esse foi o retorno...<br /> <br /> [code]<br /> Resultado da Validação do Schema e Conferência da Assinatura: <br /> <br /> PARSER XML: OK <br /> TIPO DE MENSAGEM: Lote NF-e <br /> SCHEMA: OK <br /> ASSINATURA XML: <br />    Validando NOTA #1 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #2 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #3 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #4 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #5 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #6 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #7 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #8 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #9 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #10 do Lote NF-e: Assinatura ***INVÁLIDA*** <br />    Validando NOTA #11 do Lote NF-e: Assinatura ***INVÁLIDA*** <br /> [/code]<br /> <br /> para transmitir vai tranquilo...<br /> o problema é a assinatura mesmo... pior que agora não tenho nem ideia do que pode ser..<br /> o seu assinador vc fez com base nos códigos ja postados aqui no forum?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673053/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673053/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 10:26:24]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=philler][quote=alves.Felipe]ola<br /> estou tendo problemas com a assinatura da nfe. (estou usando o codigo daqui <a class="snap_shots" href="http://www.guj.com.br/posts/list/30/83758.java" target="_blank" rel="nofollow">http://www.guj.com.br/posts/list/30/83758.java</a>)<br />  eu envio o xml de lote vai tranquilo,ai qdo vou consultar <br /> me retorma a seguinte msg: "Rejeição: Certificado Assinatura inválido". estou consumindo o ws do PR<br /> Agora eu queria saber... eu estou usando o certificado .pfx para fazer essa assinatura. <br /> Tenho que fazer alguma coisa a mais com o certificado? apenas com o pfx da para fazer a assinatura normalmente??<br /> <br /> abraço[/quote]<br /> <br /> Tive este problema e era espacos entre palavras, tipo assim: "palavra  palavra".<br /> O problema é os dois espacos (ou mais) entre palavras. Só pode ter um.<br /> <br /> Alencar[/quote]<br /> <br /> vou verificar isso tb... <br /> mas como o f-schmitt disse para eu testar no sefaz / rs... e me retorno aquela msg.. sera que ainda assim pode ser os espaços em branco?!<br /> <br /> valeo]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673056/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673056/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 10:28:33]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ é, seu assinador está com problemas<br /> <br /> poste seu xml ou me manda no email<br /> <br /> nao, desenvolvi o assinardor aqui...]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673058/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673058/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 10:30:08]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ eu estou trabalhando com 1 nfe por lote, mto mais simples de controlar e não há vantagem nenhuma em fazer varias notas por lote....]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673059/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673059/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 10:32:36]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=f-schmitt]eu estou trabalhando com 1 nfe por lote, mto mais simples de controlar e não há vantagem nenhuma em fazer varias notas por lote....[/quote]<br /> <br /> Discordo do amigo. O lote é uma ferramenta muito valiosa quando se trata de faturamento <br /> antecipado ao embarque (programado).<br /> Vejamos: o faturista tem 20 pedidos para embarque as 15h.<br /> Emite todas as notas no ERP e gera apenas um lote com todas elas.<br /> Recebe apenas um retorno do lote e emite apenas uma vez todas as DANFES.<br /> <br /> Vejam que, quando menciono "apenas uma vez" quero dizer em um só comando e nao<br /> um comando por nota do lote. Isso é ganho de tempo com certeza.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673105/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673105/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 11:49:05]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ nesse cado voce coloca seu erp aos moldes da nfe, mas no nosso caso temos a carga que faz exatamente o que voce explicou....<br /> <br /> e se uma dessas 20 notas for denegada ou algo errado,,, acho (claro que é minha opiniao) controlar o envio e o retorno de cada lote....]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673108/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673108/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 11:53:33]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ no meu caso não fica muito viavel criar um lote por nf...<br /> philler, eu até achei uma String que tinha 2 espaços em branco.. mas não é isso o problema não...<br /> <br /> f-schmitt, tem mandei o xml e meu assinador por email.. blz...]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673191/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673191/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 22 Apr 2009 13:01:32]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ o problema que eu estava tendo é que depois de assinar o xml eu o gravava , e nessa hora eu alterava o xml... por isso <br /> ficava errado a assinatura...<br /> agora eu gravo eu não altero nada. mas antes de gravar eu transformo o Document para string e consumo o WS...<br /> e agora foi.. <img src="http://www.guj.com.br/images/smilies/3b63d1616c5dfcf29f8a7a031aaa7cad.gif" border="0"> <br /> <br /> mas valeo pela força f-schmitt e philler ...<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/673725/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/673725/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 23 Apr 2009 08:54:29]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Aproveitando o topico aqui, bom aqui estou eu tentando assinar uma NFe, peguei uns codigo aqui do forum, mexi pouca coisa só pra fazer um teste e to recebendo um erro:<br /> <br /> [code]<br /> javax.xml.crypto.dsig.XMLSignatureException: javax.xml.crypto.URIReferenceException: java.lang.NullPointerException<br />         at org.jcp.xml.dsig.internal.dom.DOMReference.dereference(DOMReference.java:352)<br />         at org.jcp.xml.dsig.internal.dom.DOMReference.digest(DOMReference.java:278)<br />         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.digestReference(DOMXMLSignature.java:447)<br />         at org.jcp.xml.dsig.internal.dom.DOMXMLSignature.sign(DOMXMLSignature.java:343)<br /> [/code]<br /> <br /> O erro acontece nesta linha:<br /> [code]<br />         DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement().getElementsByTagName("NFe").item(i));<br />         signature.sign(dsc);  //&lt;=== Erro acontece nesta linha<br /> [/code]<br /> <br />  e Eis todo o codigo que peguei aqui mesmo no GUJ.<br /> <br /> [code]<br /> public static String assinarEnviNFe(String xml, String certificado, String keyStorePass) throws Exception {<br />         DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();<br />         factory.setNamespaceAware(true);<br />         DocumentBuilder builder = factory.newDocumentBuilder();<br />         // Document docs = builder.parse(new File(<br />         // "c:/xml/430802017886010001735500000000010000030371-nfe.xml"));<br />         Document doc = factory.newDocumentBuilder().parse(<br />                 new ByteArrayInputStream(xml.getBytes()));<br /> <br />         // Create a DOM XMLSignatureFactory that will be used to<br />         // generate the enveloped signature.<br />         XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");<br /> <br />         // Create a Reference to the enveloped document (in this case,<br />         // you are signing the whole document, so a URI of "" signifies<br />         // that, and also specify the SHA1 digest algorithm and<br />         // the ENVELOPED Transform.<br />         ArrayList transformList = new ArrayList();<br />         TransformParameterSpec tps = null;<br />         Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,<br />                 tps);<br />         Transform c14NTransform = fac.newTransform(<br />                 "http://www.w3.org/TR/2001/REC-xml-c14n-20010315", tps);<br /> <br />         transformList.add(envelopedTransform);<br />         transformList.add(c14NTransform);<br /> <br />         // Load the KeyStore and get the signing key and certificate.<br />         KeyStore ks = KeyStore.getInstance("PKCS12");     //MUDEI AQUI PRA PEGAR DIRETO O PFX<br />         FileInputStream fis = new FileInputStream(certificado);<br />         //load the keystore<br />         ks.load(fis, keyStorePass.toCharArray());<br />         String alias = ks.aliases().nextElement();<br /> <br />         KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(keyStorePass.toCharArray()));<br /> <br />         X509Certificate cert = (X509Certificate) keyEntry.getCertificate();<br /> <br />         // Create the KeyInfo containing the X509Data.<br />         KeyInfoFactory kif = fac.getKeyInfoFactory();<br />         List&lt;Serializable&gt; x509Content = new ArrayList&lt;Serializable&gt;();<br />         x509Content.add(cert.getSubjectX500Principal().getName());<br />         x509Content.add(cert);<br />         X509Data xd = kif.newX509Data(x509Content);<br />         KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> <br />         for (int i = 0; i &lt; doc.getDocumentElement().getElementsByTagName("NFe").getLength(); i++) {<br />             assinarNFE(fac, transformList, keyEntry.getPrivateKey(), ki, doc, i);<br />         }<br />         // Output the resulting document.<br />         ByteArrayOutputStream os = new ByteArrayOutputStream();<br />         TransformerFactory tf = TransformerFactory.newInstance();<br />         Transformer trans = tf.newTransformer();<br />         trans.transform(new DOMSource(doc), new StreamResult(os));<br />         return os.toString();<br />     }<br /> <br />     private static void assinarNFE(XMLSignatureFactory fac,<br />             ArrayList transformList, PrivateKey privateKey, KeyInfo ki,<br />             Document doc, int i) throws Exception {<br /> <br />         // Obtem elemento do documento a ser assinado, será criado uma<br />         // REFERENCE para o mesmo<br />         NodeList elements = doc.getElementsByTagName("infNFe");<br />         Element el = (Element) elements.item(i);<br />         String id = el.getAttribute("Id");<br /> <br />         // doc.getDocumentElement().removeAttribute("xmlns:ns2");<br />         // ((Element)<br />         // doc.getDocumentElement().getElementsByTagName("NFe").item(0))<br />         // .setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> <br />         // Create a DOM XMLSignatureFactory that will be used to<br />         // generate the enveloped signature.<br /> <br />         Reference ref = fac.newReference("" + id, fac.newDigestMethod(<br />                 DigestMethod.SHA1, null), transformList, null, null);<br /> <br />         // Create the SignedInfo.<br />         SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(<br />                 CanonicalizationMethod.INCLUSIVE,<br />                 (C14NMethodParameterSpec) null), fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br />                 Collections.singletonList(ref));<br /> <br />         // Create the XMLSignature, but don't sign it yet.<br />         XMLSignature signature = fac.newXMLSignature(si, ki);<br /> <br />         // Marshal, generate, and sign the enveloped signature.<br />         // Create a DOMSignContext and specify the RSA PrivateKey and<br />         // location of the resulting XMLSignature's parent element.<br />         DOMSignContext dsc = new DOMSignContext(privateKey, doc.getDocumentElement().getElementsByTagName("NFe").item(i));<br />         signature.sign(dsc);<br /> <br />     }<br /> [/code]<br /> <br /> Uma coisa que mudei foi pegar direto o PFX, ao inves do JKS, to tentando fazer assim, sem criar JKS, seguindo o que o thingol disse aqui: http://www.guj.com.br/posts/list/15/87934.java<br /> <br /> <br /> To meio perdido aqui com essa assinatura, alguem passou por isso?<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/676817/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/676817/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 28 Apr 2009 22:26:22]]> GMT</pubDate>
				<author><![CDATA[ fredferrao]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ olá, no seu XML tem um node chamado &lt;NFe&gt; ?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/676888/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/676888/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 29 Apr 2009 07:09:02]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Fred, pareceu-me que o seu problema esta na montagem do ID da tag:<br /> <br /> &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br />  &lt;infNFe Id="NFe43090491428466000148550000000398064132785580" versao="1.10"&gt;<br /> <br /> Note que em &lt;infNFe Id=... tem a String "NFe" seguida da chave de acesso da NFe.<br /> É esta tag que o processo de assinatura busca para assinar o xml da nota.<br /> javax.xml.crypto.URIReferenceException deu a entender que nao encontrou a tag com <br /> o Id especificado neste trecho de codigo:<br /> <br /> String id = el.getAttribute("Id");  <br /> Ou entao esta faltando o caracter "#" aqui (erro mais provavel):<br />    Reference ref = fac.newReference("#" + id, fac.newDigestMethod(  <br />                                         DigestMethod.SHA1, null), transformList, null, null);  <br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/676892/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/676892/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 29 Apr 2009 07:26:25]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=f-schmitt]olá, no seu XML tem um node chamado &lt;NFe&gt; ?[/quote]<br /> <br /> Pior é que tem.<br /> <br /> [code]<br /> &lt;?xml version="1.0" encoding="utf-8" ?&gt; <br /> - &lt;enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.10"&gt;<br />   &lt;idLote&gt;1&lt;/idLote&gt; <br /> - &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br /> - &lt;infNFe xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" Id="NFexxxxxxxxxx..." versao="1.10"&gt;<br /> - &lt;ide&gt;<br /> [/code]<br /> <br /> Só falta assinar pra mim concluir aqui.<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/676897/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/676897/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 29 Apr 2009 07:36:25]]> GMT</pubDate>
				<author><![CDATA[ fredferrao]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=philler]Fred, pareceu-me que o seu problema esta na montagem do ID da tag:<br /> <br /> &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br />  &lt;infNFe Id="NFe43090491428466000148550000000398064132785580" versao="1.10"&gt;<br /> <br /> Note que em &lt;infNFe Id=... tem a String "NFe" seguida da chave de acesso da NFe.<br /> É esta tag que o processo de assinatura busca para assinar o xml da nota.<br /> javax.xml.crypto.URIReferenceException deu a entender que nao encontrou a tag com <br /> o Id especificado neste trecho de codigo:<br /> <br /> String id = el.getAttribute("Id");  <br /> Ou entao esta faltando o caracter "#" aqui (erro mais provavel):<br />    Reference ref = fac.newReference("#" + id, fac.newDigestMethod(  <br />                                         DigestMethod.SHA1, null), transformList, null, null);  <br /> <br /> Alencar[/quote]<br /> <br /> BINGOOO!! Era o # faltando mesmo, coloquei e assinou na hora!!  Valeu mesmo, estes errinhos podem nos tomar dias de trabalho.<br /> <br /> Mas o que seria o # afinal? É que realmente nao tive tempo pra estudar a coisa a fundo e entender o que cada coisa faz, é um projeto pessoal e só tenho tempo de fazer a noite, e o prazo é pra ontem como dizem.<br /> <br /> Bom agora vou validar la no site do rs pra ver se assinou legal hehe, Valeu ae galera pela força.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/676901/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/676901/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 29 Apr 2009 07:43:21]]> GMT</pubDate>
				<author><![CDATA[ fredferrao]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal,<br /> <br /> alguém está trabalhando com o token ePass2000? Como eu configuro o arquivo .cfg pra esse token? Qual a dll que eu uso?<br /> <br /> Obrigado a todos!<br /> <br /> Daniel]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/682704/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/682704/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 12 May 2009 12:05:03]]> GMT</pubDate>
				<author><![CDATA[ drcosta]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ dae galera...<br /> minha situação é a seguinte: no ws do PR eu consigo conectar normalmente..apenas seto o meu certificado e o certificado que baixei da sefaz-pr e pronto....<br /> <br /> agora estou tentando consultar o status do serviço do ws de contingência da receita.. mas não consigo conectar.. recebo a seguinte msg:<br /> [code]<br /> Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target[/code]<br /> <br /> ja tentei entrar em contato com o pessoal da receita ja faz 2 semanas e até agora não tive nenhuma resposta..<br /> <br /> gostaria de saber se, assim como no ws do pr eu precisei baixar os certificados deles , eu preciso baixar algum certificado da receita para conseguir conectar..?? oq preciso fazer para conectar??<br /> <br /> valeo<br /> abraco]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/688775/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/688775/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 07:51:45]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Deve estar faltando a cadeia de certificados para validar o certificado do<br /> servidor da Receita.<br /> No ws do Parana deu certo pois o teu certificado foi expedido pela mesma<br /> entidade certificadora.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/688868/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/688868/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 09:27:54]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Era bem isso philler.. eu que estava marcando...<br /> <br /> agora eu consigo conectar no sefaz-pr e no SCAN , masss...<br /> se rodando o programa eu tentar conectar nos 2...por ex. consultar 1º o status no SCAN  e depois de pegar o retorno, setar os certificados do Sefaz-pr e fazer a consulta de status tb...na 2º consulta me retorna a mesma msg:<br /> [code]<br /> Caused by: sun.security.provider.certpath.SunCertPathBuilderException: unable to find valid certification path to requested target[/code]<br /> acontece isso só qdo é para servidores diferentes...<br /> eu só consigo consultar um de cada vez... rodar o programa, consultar um, ai finaliza o programa, ai rodo de volta e só ai consulta o outro...<br /> entendem??<br /> tem algum problema de setar <br /> [code]System.setProperty("javax.net.ssl.trustStoreType", "JKS"); ...[/code]<br /> depois limpar <br /> [code]<br /> System.clearProperty("javax.net.ssl.trustStoreType");...[/code]<br /> e setar novamente o certificado??]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689091/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689091/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 13:40:18]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Nao sei te afirmar. Mas como é variavel de ambiente, creio que se voce setar<br /> atraves de arquivos de configuracao, hora um hora outro, nao vai ter galho.<br /> Com isso voce nao precisa fechar e reabrir o prg todo. <br /> Reseta a variavel e instancia a classe novamente.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689112/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689112/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 14:08:39]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ cara.. não querendo abusar.. hehe..mas da uma olhada como é minha classe q seta os certificados..<br /> [code]<br /> public void setPropertySefaz(int codFilial,int tipoEmissao,String caminhoCertificado)<br /> 	{<br /> 		System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");   <br /> 		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());   <br /> <br /> 		if(System.getProperty("javax.net.ssl.keyStoreType")==null)<br /> 		{<br /> 			System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");   <br /> 			System.setProperty("javax.net.ssl.keyStore",caminhoCertificado+"certificado-mili-nfe.pfx");//Aqui vem o arquivo do certificado do seu cliente<br /> 			System.setProperty("javax.net.ssl.keyStorePassword", "x");//Aqui a senha deste certificado   <br /> 		}<br /> 		<br />                System.setProperty("javax.net.ssl.trustStoreType", "JKS");   <br /> 		System.setProperty("javax.net.ssl.trustStore", caminhoCertificado+"nfehomologado.keystore");//<br /> 		System.setProperty("javax.net.ssl.keyStorePassword", "x");//Aqui a senha deste certificado<br /> }<br /> <br /> [/code]<br /> <br /> [quote]<br /> Mas como é variavel de ambiente, creio que se voce setar <br /> atraves de arquivos de configuracao, hora um hora outro, nao vai ter galho. <br /> [/quote]<br /> isso que vc falou não é a mesma coisa que eu estou fazendo né? tem como passar um exemplo?<br /> <br /> valewss]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689142/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689142/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 14:35:58]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ É a mesma coisa.<br /> Do teu jeito nao funcionou?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689143/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689143/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 14:41:21]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ ixe cara.. ja vi que estou com problemas....<br /> desse jeito funciona, mas só se eu não setar 2x...se não for para estados diferentes.. entende?!<br /> e pensando aqui..sera que não vai ter como 2 usuários, que emitem nfe para diferentes estados (por ex. pr e al), usarem a aplicação?<br /> estou fazendo a aplicação web.. mas vai ter gente do PR,AL e SC usando... to f...hehe<br /> ninguém tem ai algumas sugestões?!?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689162/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689162/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 15:01:34]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ O teu problema esta só no trustStore?<br /> Se sim, porque voce nao coloca todos os certificados em um só JKS?<br /> <br /> Se nao, eu é que nao entendi....]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689186/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689186/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 15:21:12]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ é isso mesmo.. só no trustStore..<br /> <br /> [quote]Se sim, porque voce nao coloca todos os certificados em um só JKS? <br /> [/quote]<br /> <br /> sabia que eu não tinha pensado nisso!!?! hehe.. <br /> vou tentar jogar tudo num só keystore... <br /> valeo de novo]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689196/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689196/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 15:33:43]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ po.. batata .. funcionou de primeira.. haha..<br /> <br /> nem preciso fazer todos aqueles ifs que tinha mostrado antes... <br /> vou até tirar o codigo para ninguem querer copiar.. heh<br /> <br /> valeo...<br /> abraco]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689215/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689215/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 25 May 2009 15:59:35]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Olá pessoal...<br /> <br /> Sou desenvolvedora Java e C# e gostaria de divulgar a solução [b]Open Source[/b] da minha empresa pra Nota Fiscal eletrônica.<br /> Essa solução foi desenvolvida em C#, mas acredito que, como o C# é muito parecido com o Java (uma cópia, pra falar a verdade, hehe) irá ajudar quem estiver interessado em estudar ou até desenvolver uma solução Java pra nota fiscal eletrônica.<br /> <br /> Segue o link para maiores informações: [url]www.uninfe.com.br[/url]<br /> <br /> Bom estudo para todos.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/689477/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/689477/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 26 May 2009 08:41:56]]> GMT</pubDate>
				<author><![CDATA[ eliangela]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal, estou com dificuldades em extrair o CNPJ do certificado que assinou o xml.<br /> Sei que a receita faz isso, pois eles testam se o CNPJ base do certificado é o mesmo<br /> do CNPJ base do emitente.<br /> <br /> Alguns certificados vem com o CNPJ logo apos o nome da empresa, por exemplo:<br /> CN=ALGUMA EMPRESA LTDA:01001001000101<br /> <br /> Nestes casos é só pegar o getNomeCertificado() e sacar o cnpj.<br /> Mas tenho visto casos em que o CN nao vem com este valor.<br /> <br /> Alguma luz por ai? De onde a SEFAZ tira a informacao?<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/698709/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/698709/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 15 Jun 2009 15:03:45]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ cara.. ve se a resposta do thingol te ajuda nesse tópico ai<br /> <br /> <a class="snap_shots" href="http://www.guj.com.br/posts/list/126975.java" target="_blank" rel="nofollow">http://www.guj.com.br/posts/list/126975.java</a>]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/698814/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/698814/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 15 Jun 2009 16:43:02]]> GMT</pubDate>
				<author><![CDATA[ alves.Felipe]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Galera muito boa tarde!<br /> <br /> HELP-ME  <img src="http://www.guj.com.br/images/smilies/136dd33cba83140c7ce38db096d05aed.gif" border="0"> <br /> <br /> Não estou conseguindo validar a assinatura do xml em alguma notas e as mesmas são geradas no mesmo sistema.<br /> Não consigo achar o erro alguém pode me ajudar?[color=darkblue] [/color]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713085/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713085/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 15 Jul 2009 12:54:59]]> GMT</pubDate>
				<author><![CDATA[ Marilice]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=Marilice]Galera muito boa tarde!<br /> <br /> HELP-ME  <img src="http://www.guj.com.br/images/smilies/136dd33cba83140c7ce38db096d05aed.gif" border="0"> <br /> <br /> Não estou conseguindo validar a assinatura do xml em alguma notas e as mesmas são geradas no mesmo sistema.<br /> Não consigo achar o erro alguém pode me ajudar?[color=darkblue] [/color][/quote]<br /> <br /> Pode nos informar quais as msgs de erro?<br /> Uma dica que ja posso lhe adiantar: Se tiver dois espacos entre palavras nao valida.<br /> Ex.: "Rua  Treze...". Entre Rua e Treze tem dois espacos. Isso ocorre com muita frequencia en descricao de produtos<br /> e observacoes.<br /> <br /> Se nao for isso, manda as msgs de erro.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713098/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713098/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 15 Jul 2009 13:11:11]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Segue a mensagem<br /> <br /> PARSER XML:	OK<br /> TIPO DE MENSAGEM:	Distribuição da NF-e processada<br /> SCHEMA:	OK<br /> ASSINATURA XML:	Assinatura ***INVÁLIDA***]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713145/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713145/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 15 Jul 2009 13:55:26]]> GMT</pubDate>
				<author><![CDATA[ Marilice]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=Marilice]Segue a mensagem<br /> <br /> PARSER XML:	OK<br /> TIPO DE MENSAGEM:	Distribuição da NF-e processada<br /> SCHEMA:	OK<br /> ASSINATURA XML:	Assinatura ***INVÁLIDA***[/quote]<br /> <br /> Humm, assim fica dificil <img src="http://www.guj.com.br/images/smilies/3b63d1616c5dfcf29f8a7a031aaa7cad.gif" border="0"><br /> <br /> Por favor, envie um xml por aqui mesmo, assinado com erro.<br /> Analiso ele para voce.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713176/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713176/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 15 Jul 2009 14:29:22]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Alencar<br /> <br /> Obrigada por sua ajuda.<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713251/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713251/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 15 Jul 2009 15:50:31]]> GMT</pubDate>
				<author><![CDATA[ Marilice]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Alencar bom dia!<br /> <br /> Aqui estou eu novamente, fiz as alterações conformE vc havia me orientado mas mesmo assim continua com o erro"ASSINATURA INVÁLIDA"<br /> <br /> HELP-ME PLEASE]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713422/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713422/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 16 Jul 2009 07:05:28]]> GMT</pubDate>
				<author><![CDATA[ Marilice]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Cola o xml gerado pra gente ver e poder ajudar....]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713436/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713436/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 16 Jul 2009 07:18:59]]> GMT</pubDate>
				<author><![CDATA[ drcosta]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Vide mp]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713460/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713460/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 16 Jul 2009 07:47:48]]> GMT</pubDate>
				<author><![CDATA[ Marilice]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=Marilice]Alencar bom dia!<br /> <br /> Aqui estou eu novamente, fiz as alterações conformE vc havia me orientado mas mesmo assim continua com o erro"ASSINATURA INVÁLIDA"<br /> <br /> HELP-ME PLEASE[/quote]<br /> <br /> Manda novamente por email. <br /> Desculpe a demora em responder. Por vezes nao estou online.<br /> <br /> ALencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713918/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713918/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 16 Jul 2009 20:11:17]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Alencar muito bom dia!<br /> <br /> Imagina ja agradeço pela atenção que todos me deram neste forum, mas cosegui resolver e gostaria de deixar a solução.<br /> <br /> O problema estava na hora que gerava o xml a codificação estava como ANSI e o padrão é UTF-8, fiz o seguinte<br /> <br /> Abri o arquivo xml no bloco de notas<br /> Pedir para salvar como<br /> Modifique a codificação de ANSI para UTF 8<br /> Substitui o arquivo e pronto <br /> Entrei no site sefaz rs <br /> Assinatura válida<br /> <br /> Um abraço a todos]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/713981/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/713981/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 17 Jul 2009 07:09:53]]> GMT</pubDate>
				<author><![CDATA[ Marilice]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ eae camaradas, eu denovo, agora descobri que minha assinatura ta faltando uma tag, se alguem puder me ajudar agradeço, na validação acusa que falta a seguinte tag essa que coloco em negrito, essa realmente não consta na minha assinatura, mas sim nos xml nf-e de exemplo dareceita &lt;Transforms&gt;&lt;Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /&gt;[b]&lt;Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /&gt;[/b]&lt;/Transforms&gt;<br /> <br /> abaixo lanço o cod. que uso pra assianr, saiu daqui mesmo do guj, são 2 classes obrigado.<br /> <br /> [code]<br /> package nfe.signature;<br /> <br /> 	import java.io.FileInputStream;<br /> 	import java.io.FileNotFoundException;<br /> 	import java.io.FileOutputStream;<br /> 	import java.io.IOException;<br /> 	import java.io.InputStream;<br /> 	import java.io.OutputStream;<br /> 	import java.security.KeyStore;<br /> 	import java.security.KeyStoreException;<br /> 	import java.security.NoSuchAlgorithmException;<br /> 	import java.security.PrivateKey;<br /> 	import java.security.UnrecoverableEntryException;<br /> 	import java.security.cert.CertificateException;<br /> 	import java.security.cert.X509Certificate;<br /> 	import java.util.ArrayList;<br /> 	import java.util.Collections;<br /> 	import java.util.Enumeration;<br /> 	import java.util.Iterator;<br /> <br /> 	import javax.xml.crypto.dsig.CanonicalizationMethod;<br /> 	import javax.xml.crypto.dsig.DigestMethod;<br /> 	import javax.xml.crypto.dsig.Reference;<br /> 	import javax.xml.crypto.dsig.SignatureMethod;<br /> 	import javax.xml.crypto.dsig.SignedInfo;<br /> 	import javax.xml.crypto.dsig.Transform;<br /> 	import javax.xml.crypto.dsig.XMLSignature;<br /> 	import javax.xml.crypto.dsig.XMLSignatureFactory;<br /> 	import javax.xml.crypto.dsig.dom.DOMSignContext;<br /> 	import javax.xml.crypto.dsig.dom.DOMValidateContext;<br /> 	import javax.xml.crypto.dsig.keyinfo.KeyInfo;<br /> 	import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;<br /> 	import javax.xml.crypto.dsig.keyinfo.X509Data;<br /> 	import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;<br /> 	import javax.xml.crypto.dsig.spec.TransformParameterSpec;<br /> 	import javax.xml.parsers.DocumentBuilderFactory;<br /> 	import javax.xml.parsers.ParserConfigurationException;<br /> 	import javax.xml.transform.Transformer;<br /> 	import javax.xml.transform.TransformerFactory;<br /> 	import javax.xml.transform.dom.DOMSource;<br /> 	import javax.xml.transform.stream.StreamResult;<br /> <br /> 	import org.w3c.dom.Document;<br /> 	import org.w3c.dom.Element;<br /> 	import org.w3c.dom.NodeList;<br /> 	import org.xml.sax.SAXException;<br /> <br /> <br /> 	public class AssinaXML {<br /> 		<br /> 		public static String keyStoreP12 = "PKCS12";<br /> 		public static String keyStoreJKS = "JKS";<br /> 		<br /> 		public static Reference ref = null;<br /> 		public static SignedInfo si = null;<br /> 		public static XMLSignature signature = null;<br /> 		public static DOMSignContext dsc = null;<br /> 		<br /> 		private String certificadoArquivo = "";<br /> 		private String certificadoSenha = "";<br /> 		private String arquivoEntrada = "";<br /> 		private String arquivoSaida = "";<br /> 		private String keyStore = "";<br /> 		<br /> 		public AssinaXML(String arquivoCertificado, String senhaCertificado,<br /> 				String arquivoEntradaXML, String arquivoSaidaXML, String keyStore){<br /> 			this.certificadoArquivo = arquivoCertificado;<br /> 			this.certificadoSenha = senhaCertificado;<br /> 			this.arquivoEntrada = arquivoEntradaXML;<br /> 			this.arquivoSaida = arquivoSaidaXML;<br /> 			this.keyStore = keyStore;<br /> 		}<br /> 			<br /> 		public static XMLSignature getSignature() {<br /> 			return signature;<br /> 		}<br /> <br /> 		public static void setSignature(XMLSignature signature) {<br /> 			AssinaXML.signature = signature;<br /> 		}<br /> <br /> 		public String getCertificadoArquivo() {<br /> 			return certificadoArquivo;<br /> 		}<br /> <br /> 		public void setCertificadoArquivo(String certificadoArquivo) {<br /> 			this.certificadoArquivo = certificadoArquivo;<br /> 		}<br /> <br /> 		public String getCertificadoSenha() {<br /> 			return certificadoSenha;<br /> 		}<br /> <br /> 		public void setCertificadoSenha(String certificadoSenha) {<br /> 			this.certificadoSenha = certificadoSenha;<br /> 		}<br /> <br /> 		public String getArquivoEntrada() {<br /> 			return arquivoEntrada;<br /> 		}<br /> <br /> 		public void setArquivoEntrada(String arquivoEntrada) {<br /> 			this.arquivoEntrada = arquivoEntrada;<br /> 		}<br /> <br /> 		public String getArquivoSaida() {<br /> 			return arquivoSaida;<br /> 		}<br /> <br /> 		public void setArquivoSaida(String arquivoSaida) {<br /> 			this.arquivoSaida = arquivoSaida;<br /> 		}<br /> 		<br /> 		public String getKeyStore() {<br /> 			return keyStore;<br /> 		}<br /> <br /> 		public void setKeyStore(String keyStore) {<br /> 			this.keyStore = keyStore;<br /> 		}<br /> <br /> 		@SuppressWarnings("unchecked")<br /> 		public void colocaCertificado(){<br /> 			XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM");<br /> 			try {<br /> 				<br /> 				KeyStore ks = KeyStore.getInstance(getKeyStore());<br /> 				ks.load(new FileInputStream(getCertificadoArquivo()), getCertificadoSenha().toCharArray());			<br /> 				KeyStore.PrivateKeyEntry keyEntry = null;<br /> 				<br /> 				for(Enumeration e = ks.aliases(); e.hasMoreElements();){ <br /> 					keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry((String) e.nextElement(),<br /> 								new KeyStore.PasswordProtection(getCertificadoSenha().toCharArray()));<br /> 				}<br /> 				<br /> 				X509Certificate cert = (X509Certificate) keyEntry.getCertificate();<br /> 				KeyInfoFactory kif = fac.getKeyInfoFactory();<br /> 				ArrayList x509Content = new ArrayList();<br /> 				x509Content.add(cert);<br /> 				X509Data xd = kif.newX509Data(x509Content);<br /> 				KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> 	  <br /> 				DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();<br /> 				dbf.setNamespaceAware(true);<br /> 		        Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(getArquivoEntrada()));<br /> 				  <br /> 				dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());<br /> 				  	  <br /> 		        assinatura(fac, x509Content, keyEntry.getPrivateKey(), ki, doc);<br /> 				 <br /> 		        OutputStream os = new FileOutputStream(getArquivoSaida());<br /> 		          TransformerFactory tf = TransformerFactory.newInstance();<br /> 		          Transformer trans = tf.newTransformer();<br /> 		          trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 				    <br /> 		          NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");<br /> 				            		  <br /> 				  if (nl.getLength() == 0){<br /> 				     throw new Exception("Nao encontrou elemento (TAG) Signature!!!");<br /> 		          }<br /> <br /> 		          DOMValidateContext valContext = new DOMValidateContext(new X509KeySelector(), nl.item(0));<br /> 		          <br /> 		          XMLSignature signature1 = fac.unmarshalXMLSignature(valContext);<br /> <br /> 		          boolean coreValidity = signature1.validate(valContext);<br /> 				  <br /> 		          if (coreValidity == false) {<br /> 		             System.err.println("Signature failed core validation");<br /> 		             boolean sv = signature.getSignatureValue().validate(valContext);<br /> 		             System.out.println("signature validation status: " + sv);<br /> 		             if (sv == false) {<br /> 		                Iterator i = signature.getSignedInfo().getReferences().iterator();<br /> 		                for (int j=0; i.hasNext(); j++) {<br /> 		                    boolean refValid = ((Reference) i.next()).validate(valContext);<br /> 		                    System.out.println("ref["+j+"] validity status: " + refValid);<br /> 		                }<br /> 		             }<br /> 		          }<br /> 				  else {<br /> 		             System.out.println("Signature passed core validation");<br /> 		          }<br /> 				  <br /> 				  valContext.setProperty("javax.xml.crypto.dsig.cacheReference", Boolean.TRUE);<br /> 				  XMLSignature signaturex = fac.unmarshalXMLSignature(valContext);<br /> 				  @SuppressWarnings("unused")<br /> 				boolean coreValidityx = signaturex.validate(valContext);<br /> 					<br /> 		          Iterator i = signature.getSignedInfo().getReferences().iterator();<br /> 				  for (int j=0; i.hasNext(); j++) {<br /> 					  @SuppressWarnings("unused")<br /> 					InputStream is = ((Reference) i.next()).getDigestInputStream();<br /> 				  }<br /> 				  <br /> 			} catch (KeyStoreException e) {				<br /> 				e.printStackTrace();<br /> 			} catch (NoSuchAlgorithmException e) {<br /> 				e.printStackTrace();<br /> 			} catch (CertificateException e) {<br /> 				e.printStackTrace();<br /> 			} catch (FileNotFoundException e) {<br /> 				e.printStackTrace();<br /> 			} catch (IOException e) {<br /> 				e.printStackTrace();<br /> 			} catch (UnrecoverableEntryException e) {<br /> 				e.printStackTrace();<br /> 			} catch (SAXException e) {<br /> 				e.printStackTrace();<br /> 			} catch (ParserConfigurationException e) {<br /> 				e.printStackTrace();<br /> 			} catch (Exception e) {<br /> 				e.printStackTrace();<br /> 			}<br /> 			<br /> 		}<br /> 		<br /> 		@SuppressWarnings("unchecked")<br /> 		private static void assinatura(XMLSignatureFactory fac,<br /> 	            ArrayList transformList,<br /> 	            PrivateKey privateKey,<br /> 	            KeyInfo ki,<br /> 	            Document doc<br /> 			    ) throws Exception {<br /> <br /> 			NodeList elements = doc.getElementsByTagName("infNFe");<br /> 			Element el = (org.w3c.dom.Element) elements.item(0);<br /> 			String id = el.getAttribute("Id");<br /> <br /> 			ref = fac.newReference("#" + id, fac.newDigestMethod(<br /> 	                  DigestMethod.SHA1, null),<br /> 				       Collections.singletonList (<br /> 				       fac.newTransform(Transform.ENVELOPED,<br /> 				      (TransformParameterSpec) null)), null, null);<br /> <br /> 			si = fac.newSignedInfo(fac.newCanonicalizationMethod(<br /> 	        CanonicalizationMethod.INCLUSIVE,<br /> 	       (C14NMethodParameterSpec) null),<br /> 		     fac.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br /> 			     Collections.singletonList(ref));<br /> 			 <br /> 			DOMSignContext dsc = new DOMSignContext(privateKey,doc.getElementsByTagName("NFe").item(0));<br /> 			signature = fac.newXMLSignature(si, ki);<br /> 			signature.sign(dsc);<br /> 	}<br /> 		<br /> 		<br /> 		public static void main(String[] args) {<br /> 			AssinaXML ax3 = new AssinaXML("src/nfe/resources/Associacao.pfx", "associacao", <br /> 					"src/nfe/resources/NF-e.xml",<br /> 					"src/nfe/resources/assinadas/NF-e.xml", AssinaXML.keyStoreP12);<br /> 			ax3.colocaCertificado();<br /> 		}<br /> <br /> 	}<br /> [/code]<br /> <br /> <br /> [code]<br /> package nfe.signature;<br /> <br /> import java.security.Key;<br /> import java.security.PublicKey;<br /> import java.security.cert.X509Certificate;<br /> import java.util.Iterator;<br /> <br /> import javax.xml.crypto.AlgorithmMethod;<br /> import javax.xml.crypto.KeySelector;<br /> import javax.xml.crypto.KeySelectorException;<br /> import javax.xml.crypto.KeySelectorResult;<br /> import javax.xml.crypto.XMLCryptoContext;<br /> import javax.xml.crypto.XMLStructure;<br /> import javax.xml.crypto.dsig.SignatureMethod;<br /> import javax.xml.crypto.dsig.keyinfo.KeyInfo;<br /> import javax.xml.crypto.dsig.keyinfo.X509Data;<br /> <br /> public class X509KeySelector extends KeySelector {<br />     <br /> 	@SuppressWarnings("unchecked")<br /> 	public KeySelectorResult select(KeyInfo keyInfo,<br />                                     KeySelector.Purpose purpose,<br />                                     AlgorithmMethod method,<br />                                     XMLCryptoContext context)<br />         throws KeySelectorException {<br />         Iterator ki = keyInfo.getContent().iterator();<br />         while (ki.hasNext()) {<br />             XMLStructure info = (XMLStructure) ki.next();<br />             if (!(info instanceof X509Data))<br />                 continue;<br />             X509Data x509Data = (X509Data) info;<br />             Iterator xi = x509Data.getContent().iterator();<br />             while (xi.hasNext()) {<br />                 Object o = xi.next();<br />                 if (!(o instanceof X509Certificate))<br />                     continue;<br />                 final PublicKey key = ((X509Certificate)o).getPublicKey();<br />                 // Make sure the algorithm is compatible<br />                 // with the method.<br />                 if (algEquals(method.getAlgorithm(), key.getAlgorithm())) {<br />                     return new KeySelectorResult() {<br />                         public Key getKey() { return key; }<br />                     };<br />                 }<br />             }<br />         }<br />         throw new KeySelectorException("No key found!");<br />     }<br /> <br />     static boolean algEquals(String algURI, String algName) {<br />         if ((algName.equalsIgnoreCase("DSA") &&<br />             algURI.equalsIgnoreCase(SignatureMethod.DSA_SHA1)) ||<br />             (algName.equalsIgnoreCase("RSA") &&<br />             algURI.equalsIgnoreCase(SignatureMethod.RSA_SHA1))) {<br />             return true;<br />         } else {<br />             return false;<br />         }<br />     }<br /> }<br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/715209/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/715209/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 20 Jul 2009 22:52:52]]> GMT</pubDate>
				<author><![CDATA[ aix]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Olha ai a parte do meu codigo que inclui as transformacoes exigidas:<br /> <br /> [code]<br /> 			// C14N_TRANSFORM_METHOD<br /> 			String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";<br /> 			// Cria a lista de tranformações a serem aplicadas as referencias a<br /> 			// serem assinadas<br /> 			ArrayList transforms = new ArrayList();<br /> 			TransformParameterSpec tps = null;<br /> 			Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED, tps);<br /> 			Transform c14NTransform = fac.newTransform(C14N_TRANSFORM_METHOD, tps);<br /> 			transforms.add(envelopedTransform);<br /> 			transforms.add(c14NTransform);<br /> <br /> 			// cria uma referencia ao envelope e define o algoritmo SHA1<br /> 			Reference ref = fac.newReference(URI, fac.newDigestMethod(<br /> 			    DigestMethod.SHA1, null), transforms, null, null);<br /> [/code]<br /> <br /> Alencar<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/715235/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/715235/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 21 Jul 2009 06:48:28]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=alves.Felipe]o problema que eu estava tendo é que depois de assinar o xml eu o gravava , e nessa hora eu alterava o xml... por isso <br /> ficava errado a assinatura...<br /> agora eu gravo eu não altero nada.[b] mas antes de gravar eu transformo o Document para string e consumo o WS...[/b]<br /> e agora foi.. <img src="http://www.guj.com.br/images/smilies/3b63d1616c5dfcf29f8a7a031aaa7cad.gif" border="0"> <br /> <br /> mas valeo pela força f-schmitt e philler ...<br /> <br /> [/quote]<br /> <br /> pode me explicar isso melhor manu, porque eu to com o mesmo rolo, se puder ajudar agradeço, abraços.<br /> <br /> Validando NOTA #1 do Lote NF-e: Assinatura ***INVÁLIDA***]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/718398/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/718398/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 27 Jul 2009 23:42:17]]> GMT</pubDate>
				<author><![CDATA[ aix]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Apos o processo de assinatura, uso as linhas de cmd abaixo para transformar o Document em String:<br /> [code]<br /> 			ByteArrayOutputStream os = new ByteArrayOutputStream();<br /> 			TransformerFactory tf = TransformerFactory.newInstance();<br /> 			Transformer trans = tf.newTransformer();<br /> 			trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 			return os.toString();<br /> [/code]<br /> <br /> onde "doc" é o Document tratado.<br /> <br /> E depois assim para salvar em disco:<br /> [code]<br /> 	public static boolean saveFile(String arqSaida, String conteudo) throws IOException {<br /> 		File file = new File(arqSaida);<br /> 		if (file.exists())<br /> 			file.delete();<br /> 		<br /> 		FileWriter fw = new FileWriter(file);<br /> 		fw.write(conteudo);<br /> 		fw.flush();<br /> 		fw.close();<br /> 		<br /> 		return true;<br /> 	}<br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/718462/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/718462/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 28 Jul 2009 07:37:29]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Estou com o seguinte erro ao tentar assinar o xml: <br /> <br /> [code]<br /> <br /> java.lang.NullPointerException: signingKey cannot be null<br />         at javax.xml.crypto.dsig.dom.DOMSignContext.&lt;init&gt;(DOMSignContext.java:53)<br />         at br.com.peoplesolutions.nfeservice.assinador.TratadorCertificado.assinarDocumento(TratadorCertificado.java:151)<br />         at br.com.peoplesolutions.nfeservice.assinador.TratadorCertificado.main(TratadorCertificado.java:165)<br /> <br /> [/code]<br /> <br /> Minha classe está assim:<br /> <br /> [code]<br /> /*<br />  * To change this template, choose Tools | Templates<br />  * and open the template in the editor.<br />  */<br /> package br.com.peoplesolutions.nfeservice.assinador;<br /> <br /> /**<br />  *<br />  * @author Gilmar<br />  */<br /> import java.security.*;<br /> import java.security.Certificate;<br /> import java.security.cert.*;<br /> import java.io.*;<br /> import java.util.*;<br /> import javax.xml.parsers.*;<br /> import javax.xml.transform.*;<br /> import javax.xml.transform.dom.DOMSource;<br /> import javax.xml.transform.stream.StreamResult;<br /> import javax.xml.crypto.dsig.*;<br /> import javax.xml.crypto.dsig.dom.DOMSignContext;<br /> import javax.xml.crypto.dsig.keyinfo.*;<br /> import javax.xml.crypto.dsig.spec.*;<br /> <br /> import org.w3c.dom.Document;<br /> import org.w3c.dom.NodeList;<br /> <br /> public class TratadorCertificado {<br />     /*<br />      * 	Classe para tratamento de certificados. Deve fazer a manipulacao<br />      * dos certificados exportando chaves, assinando XML's e demais funcoes.<br />      *<br />      */<br /> <br />     public static final String algoritmo = "RSA";<br />     public static final String algoritmoAssinatura = "MD5withRSA";<br />     private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";<br />     public static File file = new File("c:\\meuKeystore.jks");<br />     private static String alias = "meuAlias";<br />     private static char[] senha = "senhaKeystore".toCharArray();<br />     static XMLSignatureFactory sig;<br />     static X509Certificate cert;<br />     static KeyInfo ki;<br />     static SignedInfo si;<br />     static KeyStore rep;<br /> <br />     public static PrivateKey getChavePrivada() throws Exception {<br />         <br />         InputStream entrada = new FileInputStream(file);<br />         rep.load(entrada, senha);<br />         entrada.close();<br />         Key chavePrivada = (Key) rep.getKey(alias, senha);<br /> <br /> <br />         if (chavePrivada instanceof PrivateKey) {<br />         System.out.println("Chave Privada encontrada!");<br />         return (PrivateKey) chavePrivada;<br />         } else {<br />         System.out.println("NULL");<br />         return null;  // Está retornando null<br />         }<br />         <br />         <br />     }<br /> <br />     public static PublicKey getChavePublica() throws Exception {<br /> <br />         InputStream entrada = new FileInputStream(file);<br />         rep.load(entrada, senha);<br />         entrada.close();<br />         Key chave = (Key) rep.getKey(alias, senha);<br />         java.security.Certificate cert = (java.security.Certificate) rep.getCertificate(alias);//O tipo de dado é declarado desse modo por haver ambigüidade (Classes assinadas com o mesmo nome "Certificate")<br />         PublicKey chavePublica = cert.getPublicKey();<br />         System.out.println("Chave Pública encontrada!");<br />         return chavePublica;<br /> <br /> <br /> <br /> <br /> <br />     }<br /> <br />     public static boolean verificarAssinatura(PublicKey chave, byte[] buffer, byte[] assinado) throws Exception {<br /> <br />         Signature assinatura = Signature.getInstance(algoritmoAssinatura);<br />         assinatura.initVerify(chave);<br />         assinatura.update(buffer, 0, buffer.length);<br />         return assinatura.verify(assinado);<br />     }<br /> <br />     public static byte[] criarAssinatura(PrivateKey chavePrivada, byte[] buffer) throws Exception {<br /> <br />         Signature assinatura = Signature.getInstance(algoritmoAssinatura);<br />         assinatura.initSign(chavePrivada);<br />         assinatura.update(buffer, 0, buffer.length);<br />         return assinatura.sign();<br />     }<br /> <br />     public static String getValidade(X509Certificate cert) {<br />         try {<br />             cert.checkValidity();<br />             return "Certificado válido!";<br />         } catch (CertificateExpiredException e) {<br />             return "Certificado expirado!";<br />         } catch (CertificateNotYetValidException e) {<br />             return "Certificado inválido!";<br />         }<br />     }<br /> <br />     public static void getCertificado() throws Exception {<br />         InputStream dado = new FileInputStream(file);<br />         rep = KeyStore.getInstance("JKS");<br />         rep.load(dado, senha);<br />         cert = (X509Certificate) rep.getCertificate(alias);<br />         String retorno = TratadorCertificado.getValidade(cert);<br />         System.out.println(retorno);<br />     }<br /> <br />     public static void assinarDocumento(String localDocumento) throws Exception {<br />         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();<br />         dbf.setNamespaceAware(true);<br />         Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(localDocumento));<br />         System.out.println("Documento ok!");<br /> <br />         sig = XMLSignatureFactory.getInstance("DOM");<br /> <br />         ArrayList&lt;Transform&gt; transformList = new ArrayList&lt;Transform&gt;();<br />         Transform enveloped = sig.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);<br />         Transform c14n = sig.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null);<br />         transformList.add(enveloped);<br />         transformList.add(c14n);<br /> <br />         NodeList elements = doc.getElementsByTagName("infNFe");<br />         org.w3c.dom.Element el = (org.w3c.dom.Element) elements.item(0);<br />         String id = el.getAttribute("Id");<br />         Reference r = sig.newReference("#".concat(id), sig.newDigestMethod(DigestMethod.SHA1, null),<br />                 transformList,<br />                 null, null);<br />         si = sig.newSignedInfo(<br />                 sig.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,<br />                 (C14NMethodParameterSpec) null),<br />                 sig.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br />                 Collections.singletonList(r));<br /> <br />         KeyInfoFactory kif = sig.getKeyInfoFactory();<br />         List x509Content = new ArrayList();<br />         x509Content.add(cert);<br />         X509Data xd = kif.newX509Data(x509Content);<br />         ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> <br />         DOMSignContext dsc = new DOMSignContext(getChavePrivada(), doc.getDocumentElement());<br />         XMLSignature signature = sig.newXMLSignature(si, ki);<br />         signature.sign(dsc);<br />         OutputStream os = new FileOutputStream("assinado.xml");<br />         TransformerFactory tf = TransformerFactory.newInstance();<br />         Transformer trans = tf.newTransformer();<br />         trans.transform(new DOMSource(doc), new StreamResult(os));<br /> <br />     }<br /> <br />     public static void main(String[] args) {<br /> <br />         try {<br />             TratadorCertificado.getCertificado();<br />             TratadorCertificado.assinarDocumento("C:\\Documents and Settings\\Gilmar\\Desktop\\35090850559251000189550010000000010004001100-nfe.xml");<br />         } catch (Exception e) {<br />             e.printStackTrace();<br />         }<br /> <br />     }<br /> }<br /> <br /> <br /> [/code]<br /> <br /> Meu certificado é do tipo .pfx<br /> <br /> Estou usando essa ferramenta para criar o keystore [url]http://yellowcat1.free.fr/index_ktl.html[/url]<br /> <br /> Não sei se estou fazendo certo.<br /> Tentei pela linha de comando e também não deu certo]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/721520/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/721520/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 3 Aug 2009 23:01:30]]> GMT</pubDate>
				<author><![CDATA[ gilmaslima]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Verifique se esta linha esta sendo executada:<br /> <br /> System.out.println("Chave Privada encontrada!");  <br /> <br /> Pelo que entendi, vc esta tendo problemas em ler o jks.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/721523/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/721523/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 3 Aug 2009 23:16:27]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Consegui resolver de uma forma mais fácil graças a esses post do thingol [url]http://www.guj.com.br/posts/list/15/87934.java[/url]<br /> <br /> Usei o comando: [b] keytool -list -storetype pkcs12 -keystore "Nfe emissor.pfx"[/b] e peguei o alias do meu .pfx<br /> <br /> E mudei o método que pega a chave privada.<br /> <br /> Ficou assim:<br /> <br /> [code]<br /> /*<br />  * To change this template, choose Tools | Templates<br />  * and open the template in the editor.<br />  */<br /> package br.com.peoplesolutions.nfeservice.assinador;<br /> <br /> /**<br />  *<br />  * @author Gilmar<br />  */<br /> import java.security.*;<br /> import java.security.Certificate;<br /> import java.security.cert.*;<br /> import java.io.*;<br /> import java.util.*;<br /> import javax.xml.parsers.*;<br /> import javax.xml.transform.*;<br /> import javax.xml.transform.dom.DOMSource;<br /> import javax.xml.transform.stream.StreamResult;<br /> import javax.xml.crypto.dsig.*;<br /> import javax.xml.crypto.dsig.dom.DOMSignContext;<br /> import javax.xml.crypto.dsig.keyinfo.*;<br /> import javax.xml.crypto.dsig.spec.*;<br /> <br /> import org.w3c.dom.Document;<br /> import org.w3c.dom.NodeList;<br /> <br /> public class TratadorCertificado {<br />     /*<br />      * 	Classe para tratamento de certificados. Deve fazer a manipulacao<br />      * dos certificados exportando chaves, assinando XML's e demais funcoes.<br />      *<br />      */<br /> <br />     public static final String algoritmo = "RSA";<br />     public static final String algoritmoAssinatura = "MD5withRSA";<br />     private static final String C14N_TRANSFORM_METHOD = "http://www.w3.org/TR/2001/REC-xml-c14n-20010315";<br />     public static File file = new File("c:\\NFe emissao.pfx");<br />     private static String alias = "7329c51b033a11c43842c2768e4974ea_9781a9e3-5b38-48a9-a28d-6443bfbf0f03"; // Esse foi o alias retornado pelo comando<br />     private static char[] senha = "senha_do_meu_arquivo.pfx".toCharArray();<br />     static XMLSignatureFactory sig;<br />     static X509Certificate cert;<br />     static KeyInfo ki;<br />     static SignedInfo si;<br />     static KeyStore rep;<br /> <br />     public static PrivateKey getChavePrivada() throws Exception {<br />         /*<br />         InputStream entrada = new FileInputStream(file);<br />         rep.load(entrada, senha);<br />         entrada.close();<br />         Key chavePrivada = (Key) rep.getKey(alias, senha);<br /> <br /> <br />         if (chavePrivada instanceof PrivateKey) {<br />         System.out.println("Chave Privada encontrada!");<br />         return (PrivateKey) chavePrivada;<br />         } else {<br />         System.out.println("NULLLLLLLL");<br />         return null;<br />         }<br />          */<br />         KeyStore ks = KeyStore.getInstance("PKCS12");<br />         FileInputStream fis = new FileInputStream(file);<br /> <br /> //load the keystore<br />         ks.load(fis, senha);<br /> <br /> //get the private key for signing.<br />         PrivateKey privateKey = (PrivateKey) ks.getKey(alias, senha);<br /> <br />         return privateKey;<br />     }<br /> <br />     public static PublicKey getChavePublica() throws Exception {<br />         KeyStore ks = KeyStore.getInstance("PKCS12");<br />         FileInputStream fis = new FileInputStream(file);<br /> <br />         //InputStream entrada = new FileInputStream(file);<br />         rep.load(fis, senha);<br />         fis.close();<br />         Key chave = (Key) rep.getKey(alias, senha);<br />         java.security.Certificate cert = (java.security.Certificate) rep.getCertificate(alias);//O tipo de dado é declarado desse modo por haver ambigüidade (Classes assinadas com o mesmo nome "Certificate")<br />         PublicKey chavePublica = cert.getPublicKey();<br />         System.out.println("Chave Pública encontrada!");<br />         return chavePublica;<br /> <br /> <br /> <br /> <br /> <br />     }<br /> <br />     public static boolean verificarAssinatura(PublicKey chave, byte[] buffer, byte[] assinado) throws Exception {<br /> <br />         Signature assinatura = Signature.getInstance(algoritmoAssinatura);<br />         assinatura.initVerify(chave);<br />         assinatura.update(buffer, 0, buffer.length);<br />         return assinatura.verify(assinado);<br />     }<br /> <br />     public static byte[] criarAssinatura(PrivateKey chavePrivada, byte[] buffer) throws Exception {<br /> <br />         Signature assinatura = Signature.getInstance(algoritmoAssinatura);<br />         assinatura.initSign(chavePrivada);<br />         assinatura.update(buffer, 0, buffer.length);<br />         return assinatura.sign();<br />     }<br /> <br />     public static String getValidade(X509Certificate cert) {<br />         try {<br />             cert.checkValidity();<br />             return "Certificado válido!";<br />         } catch (CertificateExpiredException e) {<br />             return "Certificado expirado!";<br />         } catch (CertificateNotYetValidException e) {<br />             return "Certificado inválido!";<br />         }<br />     }<br /> <br />     public static void getCertificado() throws Exception {<br />         InputStream dado = new FileInputStream(file);<br />         rep = KeyStore.getInstance("PKCS12");<br />         rep.load(dado, senha);<br />         cert = (X509Certificate) rep.getCertificate(alias);<br />         String retorno = TratadorCertificado.getValidade(cert);<br />         System.out.println(retorno);<br />     }<br /> <br />     public static void assinarDocumento(String localDocumento) throws Exception {<br />         DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();<br />         dbf.setNamespaceAware(true);<br />         Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(localDocumento));<br />         System.out.println("Documento ok!");<br /> <br />         sig = XMLSignatureFactory.getInstance("DOM");<br /> <br />         ArrayList&lt;Transform&gt; transformList = new ArrayList&lt;Transform&gt;();<br />         Transform enveloped = sig.newTransform(Transform.ENVELOPED, (TransformParameterSpec) null);<br />         Transform c14n = sig.newTransform(C14N_TRANSFORM_METHOD, (TransformParameterSpec) null);<br />         transformList.add(enveloped);<br />         transformList.add(c14n);<br /> <br />         NodeList elements = doc.getElementsByTagName("infNFe");<br />         org.w3c.dom.Element el = (org.w3c.dom.Element) elements.item(0);<br />         String id = el.getAttribute("Id");<br />         Reference r = sig.newReference("#".concat(id), sig.newDigestMethod(DigestMethod.SHA1, null),<br />                 transformList,<br />                 null, null);<br />         si = sig.newSignedInfo(<br />                 sig.newCanonicalizationMethod(CanonicalizationMethod.INCLUSIVE,<br />                 (C14NMethodParameterSpec) null),<br />                 sig.newSignatureMethod(SignatureMethod.RSA_SHA1, null),<br />                 Collections.singletonList(r));<br /> <br />         KeyInfoFactory kif = sig.getKeyInfoFactory();<br />         List x509Content = new ArrayList();<br />         x509Content.add(cert);<br />         X509Data xd = kif.newX509Data(x509Content);<br />         ki = kif.newKeyInfo(Collections.singletonList(xd));<br /> <br />         DOMSignContext dsc = new DOMSignContext(getChavePrivada(), doc.getDocumentElement());<br />         XMLSignature signature = sig.newXMLSignature(si, ki);<br />         signature.sign(dsc);<br />         OutputStream os = new FileOutputStream("assinado.xml");<br />         TransformerFactory tf = TransformerFactory.newInstance();<br />         Transformer trans = tf.newTransformer();<br />         trans.transform(new DOMSource(doc), new StreamResult(os));<br /> <br />     }<br /> <br />     public static void main(String[] args) {<br /> <br />         try {<br />             TratadorCertificado.getCertificado();<br />             TratadorCertificado.assinarDocumento("C:\\Documents and Settings\\Gilmar\\Desktop\\35090850559251000189550010000000010004001100-nfe.xml");<br />         } catch (Exception e) {<br />             e.printStackTrace();<br />         }<br /> <br />     }<br /> }<br /> <br /> <br /> [/code]<br /> <br /> O melhor de tudo foi que eu não precisei criar nenhum keystore.<br /> <br /> Nada como vasculhar o fórum!!!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/721527/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/721527/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 3 Aug 2009 23:45:06]]> GMT</pubDate>
				<author><![CDATA[ gilmaslima]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Boa Tarde Pessoal!<br /> <br /> Achei que já havia finalizado a NFe, porém apareceu mais um erro que não consigo resolver.<br /> A SEFAZ do Paraná obriga que eu coloque o namespace na tag NFe, como abaixo:<br /> <br /> &lt;enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.10"&gt;<br /> &lt;idLote&gt;1&lt;/idLote&gt;<br /> &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br /> (...)<br /> <br /> mas quando eu assino meu documento e transformo ele de um objeto Document para um objeto String,<br /> eu estou perdendo este namespace, e o meu documento xml está ficando assim<br /> <br /> &lt;enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.10"&gt;<br /> &lt;idLote&gt;1&lt;/idLote&gt;<br /> &lt;NFe&gt;<br /> (...)<br /> <br /> Alguém sabe o que pod estar acontecendo?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/724451/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/724451/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 10 Aug 2009 16:29:28]]> GMT</pubDate>
				<author><![CDATA[ ernanics]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Tente assim a saida:<br /> <br /> [code]<br /> 	ByteArrayOutputStream os = new ByteArrayOutputStream();<br /> 	TransformerFactory tf = TransformerFactory.newInstance();<br /> 	Transformer trans = tf.newTransformer();<br /> 	trans.transform(new DOMSource(doc), new StreamResult(os));<br /> 	return os.toString();  			<br /> [/code]<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/724574/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/724574/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 10 Aug 2009 19:05:45]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ É exatamente assim que eu estou fazendo...<br /> <br /> será q não existe uma outra maneira, ou alguma propriedade que seja necessário setar, pois de acordo com a norma da w3c eu não posso ter tags com o mesmo namespace sem um prefixo, já que prefixos não são permitidos segundo o Layout da NFe, deve haver alguma coisa que eu tenho que fazer para poder ter namespaces repetidos, e aí, alguém arrisca?<br /> <br /> <br /> Att.<br /> <br /> <br /> Ernani C.S., <br /> Desenvolvimento - Joinville/SC]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/724666/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/724666/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 11 Aug 2009 08:12:40]]> GMT</pubDate>
				<author><![CDATA[ ernanics]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Opa... <br /> <br /> Pessoal estou com problemas em me comunicar com o ws... nao consigo tirar o erro:<br /> [b]unable to find valid certification path to requested target[/b]<br /> <br /> O procedimento que usei:<br /> 1. Baixei o Associacao.pfx da SEFAZ;<br /> 2. Importei usando o próprio JRE (javaws) e exportei o arquivo Associacao.cer;<br /> 3. pelo keytool adicionei o .cer no CAcerts na pasta security do JRE.<br /> 4. Setei as variaveis do sistema assim:<br /> [code]<br /> ...<br /> System.setProperty("javax.net.ssl.trustStoreType", "JKS");    <br /> System.setProperty("javax.net.ssl.trustStore", "associa");<br /> System.setProperty("javax.net.ssl.trustStorePassword", "changeit");<br /> <br /> System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");    <br /> System.setProperty("javax.net.ssl.keyStore", "C:\temp\Associacao.pfx");<br /> System.setProperty("javax.net.ssl.keyStorePassword", "associacao");<br /> <br /> strRetorno = soapServico.nfeStatusServicoNF(cabecMsg, consStatServ);<br /> ...<br /> [/code]<br /> 5. To com o maledito erro:<br /> [code]unable to find valid certification path to requested target[/code]<br /> <br /> Mesmo se tentar chamar os outros métodos do WS, recebo o mesmo erro. Estou usando o eclipse e ele ta configurado para usar o JDK1.5.<br /> <br /> Olhei dentro da classe que chama o metodo e o link eh "http://www.portalfiscal.inf.br/nfe/wsdl/NfeStatusServico"... o de vocês esta assim tb ?<br /> <br /> Preciso configurar algum certificado do WS na minha máquina ?<br /> <br /> <br /> Vlw!<br /> <br /> **************************************<br /> Progredi mais um pouco.. (eu acho rs)<br /> <br /> Acertei o keytool para o certificado (arquivo .cer), mas agora to com o seguinte erro:<br /> [code]Caused by: java.security.InvalidAlgorithmParameterException: the trustAnchors parameter must be non-empty<br /> 	at java.security.cert.PKIXParameters.setTrustAnchors(PKIXParameters.java:183)<br /> 	at java.security.cert.PKIXParameters.&lt;init&gt;(PKIXParameters.java:103)<br /> 	at java.security.cert.PKIXBuilderParameters.&lt;init&gt;(PKIXBuilderParameters.java:87)<br /> 	at sun.security.validator.PKIXValidator.&lt;init&gt;(PKIXValidator.java:54)<br /> 	... 30 more<br /> [/code]<br /> <br /> O que errei na hora de setar os parâmetros ?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/725070/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/725070/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 11 Aug 2009 17:07:29]]> GMT</pubDate>
				<author><![CDATA[ PadrE]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ O problema é o certificado.<br /> Você não vai conseguir conectar os servidores da receita federal com este certificado, é necessário um certificado válido. Peça ele aos seus clientes ou compre um e-CNPJ, como fizemos aqui na empresa.<br /> <br /> Olhe no site da certisign e dos correios (nos correios é mais barato)... o processo demora em torno de 96 horas, entre a compra do certificado e a autorização de uso.<br /> <br /> Informe-se...<br /> <br /> Outro problema é relacionado ao trustStore<br /> ele está incorreto<br /> <br /> [code]System.setProperty("javax.net.ssl.trustStoreType", "JKS");       <br /> System.setProperty("javax.net.ssl.trustStore", "associa");   <br /> System.setProperty("javax.net.ssl.trustStorePassword", "changeit");  [/code]<br /> <br /> Pesquise sobre SSL e o que é um trustStore você vai aprender... <br /> procure por isso: montar JKS em java... <br /> <br /> Para montar este trustStore JKS é necessário baixar as chaves públicas (.cer) das SEFAZ que você <br /> pretende enviar notas... depois é só colocar tudo neste trustStore. <br /> Este trustStore são os certificado que você vai aceitar, assim como tem no IE (lista de certificado aceitos, quer  dizer que aquelas pessoas são confiáveis).<br /> <br /> <br /> Att.<br /> <br /> Ernani C.S., <br /> Desenvolvimento - Joinville/SC<br /> PPINFO ERP - Sistema Web de Gestão Empresarial <br /> http://www.ppinfo.com.br]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/725545/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/725545/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 12 Aug 2009 14:31:25]]> GMT</pubDate>
				<author><![CDATA[ ernanics]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=ernanics]O problema é o certificado.<br /> Você não vai conseguir conectar os servidores da receita federal com este certificado, é necessário um certificado válido. Peça ele aos seus clientes ou compre um e-CNPJ, como fizemos aqui na empresa.<br /> <br /> Olhe no site da certisign e dos correios (nos correios é mais barato)... o processo demora em torno de 96 horas, entre a compra do certificado e a autorização de uso.<br /> <br /> Informe-se...<br /> <br /> Outro problema é relacionado ao trustStore<br /> ele está incorreto<br /> <br /> [code]System.setProperty("javax.net.ssl.trustStoreType", "JKS");       <br /> System.setProperty("javax.net.ssl.trustStore", "associa");   <br /> System.setProperty("javax.net.ssl.trustStorePassword", "changeit");  [/code]<br /> <br /> Pesquise sobre SSL e o que é um trustStore você vai aprender... <br /> procure por isso: montar JKS em java... <br /> <br /> Para montar este trustStore JKS é necessário baixar as chaves públicas (.cer) das SEFAZ que você <br /> pretende enviar notas... depois é só colocar tudo neste trustStore. <br /> Este trustStore são os certificado que você vai aceitar, assim como tem no IE (lista de certificado aceitos, quer  dizer que aquelas pessoas são confiáveis).<br /> <br /> <br /> Att.<br /> <br /> Ernani C.S., <br /> Desenvolvimento - Joinville/SC<br /> PPINFO ERP - Sistema Web de Gestão Empresarial <br /> http://www.ppinfo.com.br[/quote]<br /> <br /> Cara.. vlw as dicas... vou ver isso sim... principalmente a configuração dos .cer.. que preciso deixar de um jeito bem flexivel..<br /> Acho que consegui resolver essa parte... e me deparei com outro problema.. que ai ja acho que o certificado que estou usando nao funciona... <br /> <br /> postei minha duvida em outro post [url]http://www.guj.com.br/posts/list/195/72325.java#723150[/url] (são tantos de NFe que nem sei mais em qual postar.. hehe).<br /> <br /> Vlw<br /> ****************************<br /> Mudei o código e agora ta me dando:<br /> [code]Default SSL context init failed: DerInputStream.getLength(): lengthTag=109, too big.[/code]<br /> <br /> Modifiquei o codigo para:<br /> [code]System.setProperty("javax.net.ssl.trustStoreType", "JKS");    <br /> System.setProperty("javax.net.ssl.trustStore", keystore);<br /> System.setProperty("javax.net.ssl.trustStorePassword", "changeit");<br /> <br /> System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");    <br /> System.setProperty("javax.net.ssl.keyStore", keystore);<br /> System.setProperty("javax.net.ssl.keyStorePassword", "changeit");<br /> [/code]<br /> <br /> No keystore coloquei os .cer do arquivo SEFAZSP_homologacao.p7b<br /> <br /> =/]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/725736/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/725736/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 12 Aug 2009 17:34:38]]> GMT</pubDate>
				<author><![CDATA[ PadrE]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Alguém teria um exemplo do código para geração do XML?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/738220/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/738220/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 4 Sep 2009 08:24:06]]> GMT</pubDate>
				<author><![CDATA[ javer]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Algum colega de MG neste forum?<br /> Se sim, por favor, me mande uma mensagem privada.<br /> <br /> Grato<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/738232/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/738232/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 4 Sep 2009 08:37:19]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=javer]Alguém teria um exemplo do código para geração do XML?[/quote]<br /> <br /> cara, você pode usar um framework p/  gerar o xml há vários, como o xstream, normalmente voce modela seu xml em um beam, e o frame gera o xml, ajuda bastante<br /> <br /> abraço]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/738534/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/738534/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 4 Sep 2009 13:41:58]]> GMT</pubDate>
				<author><![CDATA[ f-schmitt]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ estou usando o código do [i]gilmaslima[/i], (muito obrigado por ter postado, ajudou d+)<br /> com algumas alteraçoes para a nota de BH/MG. O xml tem algumas diferenças mínimas como:<br /> <br />   ao invés de [b]infNFe[/b] é [b]InfNfse[/b]<br />   e o param [b]id[/b] é todo em minúsculo.<br /> <br /> bem, peguei o alias usando o keytool e rodei o codigo, ok gerou o [i]assinado.xml[/i] <br /> porém comparando com a nota de exemplo pela sec. faz. faltou um parâmetro em uma tag no xml<br /> <br /> na assinatura gerada ficou assim a tag: [code]&lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;[/code]<br /> e no arq exemplo assim:[code] &lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#" Id="NfseAssSMF_999999990001911733160024200900000000017"&gt;[/code] onde esse num é o id da nota<br /> <br /> ainda nao consegui testar se a assinatura vai ser validada, mas já adiantando<br /> alguem tem idéia de como adicionar esse Id na nota?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/740968/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/740968/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 10 Sep 2009 11:08:23]]> GMT</pubDate>
				<author><![CDATA[ andredurao]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ esta parte da assinatura (Id="NfseAssSMF_999999990001911733160024200900000000017")<br /> é a URI do xml que vai ser assinado.<br /> Caso vc nao informe a URI, o assinador assina todo o arquivo, o que nao é o caso da NFe.<br /> <br /> [code]<br /> 			nota = doc.getDocumentElement().getElementsByTagName("NFe").getLength() &gt; 0;<br /> 			if (nota) {<br /> 				NodeList elements = doc.getElementsByTagName("infNFe");<br /> 				Element el = (Element) elements.item(0);  <br /> 				URI = "#" + el.getAttribute("Id");<br /> 			}<br /> <br /> ....<br /> <br /> 			// cria uma referencia ao envelope e define o algoritmo SHA1<br /> 			Reference ref = fac.newReference(URI, fac.newDigestMethod(<br /> 			    DigestMethod.SHA1, null), transforms, null, null);<br /> <br /> [/code]<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/741181/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/741181/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 10 Sep 2009 14:43:15]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Quanto a essa parte estou usando a URI sim, <br /> da mesma forma que o código que citei tb usa.<br /> <br /> Minha dúvida era quanto a diferença entre o XML de exemplo do municipio e o que eu gerei na assinatura.<br /> <br /> Só eu que acho, ou tem mais gente que acha que a nfe é muito mal documentada?<br /> por ex: agora estou estudando como assinar os RPS de BH (que por sinal, novamente difere do padrão proposto)<br /> e não vejo claro onde identificar a URI para assinar o lote de RPS, nesse caso o SHA1 seria então do documento inteiro?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/743504/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/743504/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 15 Sep 2009 11:37:39]]> GMT</pubDate>
				<author><![CDATA[ andredurao]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=andredurao]Só eu que acho, ou tem mais gente que acha que a nfe é muito mal documentada?<br /> por ex: agora estou estudando como assinar os RPS de BH (que por sinal, novamente difere do padrão proposto) [/quote]<br /> <br /> Realmente tem diferenças, estou com alguns problemas em relação a isso também, mais especificamente no cancelamento<br /> Quando envio o web service retorna a seguinte mensagem de erro: "Arquivo enviado com erro na assinatura."<br /> <br /> Alguém sabe o que é ??]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/747948/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/747948/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 22 Sep 2009 15:17:22]]> GMT</pubDate>
				<author><![CDATA[ vitinho1712]]></author>
			</item>
			<item>
				<title>assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Senhores, estou tentando assinar a NFe e estou tendo problemas.<br /> Para efeito de testes, peguei o xml gerado e assinei pelo assinador disponivel no site da receita. <br /> A assinatura é feita corretamente.<br /> Só que quando tento validar a NFe o validador joga a seguinte mensagem:<br /> <br /> Erro na Cadeia de certificação. 'CN=Autoridade Certificadora Raiz Brasileira v1, OU=Instituto Nacional de Tecnologia da Informacao - ITI, O=ICP-Brasil, C=BR', emitido por 'CN=Autoridade Certificadora Raiz Brasileira v1, OU=Instituto Nacional de Tecnologia da Informacao - ITI, O=ICP-Brasil, C=BR', serial number '01' - ERRO: 32 - Descrição do Erro: Unknown error.<br /> <br /> alguém tem alguma sugestão?<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/756873/assinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/756873/assinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 6 Oct 2009 20:08:34]]> GMT</pubDate>
				<author><![CDATA[ gilson_gp]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Da a entender que o seu certificado não é valido <br /> ou nao é raiz ICP.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/756926/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/756926/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 6 Oct 2009 22:30:18]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal. <br /> Segui esse tutorial do proprio guj (<a class="snap_shots" href="http://www.guj.com.br/article.show.logic?id=141" target="_blank" rel="nofollow">http://www.guj.com.br/article.show.logic?id=141</a>)<br /> E consegui fazer a assinatura digital do XML.<br /> A grande questão é: o servidor não tem JAVA 6.<br /> Tem alguma solução para esse caso (usando o JAVA 5)??<br /> <br /> Abraços]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/757455/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/757455/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 7 Oct 2009 15:35:35]]> GMT</pubDate>
				<author><![CDATA[ bokerao]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Bom dia pessoal,<br /> Estou desenvolvendo um sistema para envio da NFe para Paraná. O sistema esta pronto, assinando e comunicando com o WebService. Mas não estou  conseguindo meu xml com o sistema Visualizador que foi fornecido pela receita, as estrutura do meu xml esta com as tags &lt;enviNFe&gt; e &lt;lote&gt;, tirando essas tags não estou conseguindo validar o xml no WebService do Paraná. Alguém pode me ajudar com isso ?<br /> Preciso saber com fica a estrutura inicial desse xml. Inclusive eu usei uma classe de assinatura daqui do fórum mesmo.<br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/765019/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/765019/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Wed, 21 Oct 2009 07:49:06]]> GMT</pubDate>
				<author><![CDATA[ acmedis]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=acmedis]Bom dia pessoal,<br /> Estou desenvolvendo um sistema para envio da NFe para Paraná. O sistema esta pronto, assinando e comunicando com o WebService. Mas não estou  conseguindo meu xml com o sistema Visualizador que foi fornecido pela receita, as estrutura do meu xml esta com as tags &lt;enviNFe&gt; e &lt;lote&gt;, tirando essas tags não estou conseguindo validar o xml no WebService do Paraná. Alguém pode me ajudar com isso ?<br /> Preciso saber com fica a estrutura inicial desse xml. Inclusive eu usei uma classe de assinatura daqui do fórum mesmo.<br /> [/quote]<br /> <br /> posta seu xml para melhor ajudar você]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/765938/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/765938/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 22 Oct 2009 09:36:30]]> GMT</pubDate>
				<author><![CDATA[ alexborges]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ conforme solicitado pelo alexborges, segue o xml assinado que esta sendo enviado para webservice do Paraná. <br /> <br /> &lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; <br /> - &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br /> - &lt;infNFe xmlns<img src="http://www.guj.com.br/images/smilies/1069449046bcd664c21db15b1dfedaee.gif" border="0">si="http://www.w3.org/2001/XMLSchema-instance" Id="NFe41091010257545000131550020000002903885489006" versao="1.10"&gt;<br /> - &lt;ide&gt;<br />   &lt;cUF&gt;41&lt;/cUF&gt; <br />   &lt;cNF&gt;388548900&lt;/cNF&gt; <br />   &lt;natOp&gt;VENDA DE MERCADORIAS&lt;/natOp&gt; <br />   &lt;indPag&gt;1&lt;/indPag&gt; <br />   &lt;mod&gt;55&lt;/mod&gt; <br />   &lt;serie&gt;2&lt;/serie&gt; <br />   &lt;nNF&gt;290&lt;/nNF&gt; <br />   &lt;dEmi&gt;2009-10-21&lt;/dEmi&gt; <br />   &lt;dSaiEnt&gt;2009-10-22&lt;/dSaiEnt&gt; <br />   &lt;tpNF&gt;1&lt;/tpNF&gt; <br />   &lt;cMunFG&gt;4113700&lt;/cMunFG&gt; <br />   &lt;tpImp&gt;1&lt;/tpImp&gt; <br />   &lt;tpEmis&gt;1&lt;/tpEmis&gt; <br />   &lt;cDV&gt;6&lt;/cDV&gt; <br />   &lt;tpAmb&gt;2&lt;/tpAmb&gt; <br />   &lt;finNFe&gt;1&lt;/finNFe&gt; <br />   &lt;procEmi&gt;0&lt;/procEmi&gt; <br />   &lt;verProc&gt;3&lt;/verProc&gt; <br />   &lt;/ide&gt;<br /> - &lt;emit&gt;<br />   &lt;CNPJ&gt;99999999999&lt;/CNPJ&gt; <br />   &lt;xNome&gt;S G teste LTDA&lt;/xNome&gt; <br />   &lt;xFant&gt;S G teste&lt;/xFant&gt; <br /> - &lt;enderEmit&gt;<br />   &lt;xLgr&gt;AV DEZ DE DEZEMBRO 1342 G 2&lt;/xLgr&gt; <br />   &lt;nro&gt;S/N&lt;/nro&gt; <br />   &lt;xCpl&gt;Complemento&lt;/xCpl&gt; <br />   &lt;xBairro&gt;CENTRO&lt;/xBairro&gt; <br />   &lt;cMun&gt;4113700&lt;/cMun&gt; <br />   &lt;xMun&gt;LONDRINA&lt;/xMun&gt; <br />   &lt;UF&gt;PR&lt;/UF&gt; <br />   &lt;CEP&gt;86026220&lt;/CEP&gt; <br />   &lt;cPais&gt;1058&lt;/cPais&gt; <br />   &lt;xPais&gt;BRASIL&lt;/xPais&gt; <br />   &lt;fone&gt;9999999999&lt;/fone&gt; <br />   &lt;/enderEmit&gt;<br />   &lt;IE&gt;999999999&lt;/IE&gt; <br />   &lt;/emit&gt;<br /> - &lt;dest&gt;<br />   &lt;CNPJ&gt;99999999999999&lt;/CNPJ&gt; <br />   &lt;xNome&gt;MOVEIS LTDA&lt;/xNome&gt; <br /> - &lt;enderDest&gt;<br />   &lt;xLgr&gt;RUA SANTO&lt;/xLgr&gt; <br />   &lt;nro&gt;S/N&lt;/nro&gt; <br />   &lt;xCpl&gt;Complemento&lt;/xCpl&gt; <br />   &lt;xBairro&gt;DISTRITO INDUSTRIAL&lt;/xBairro&gt; <br />   &lt;cMun&gt;3522901&lt;/cMun&gt; <br />   &lt;xMun&gt;ITAPUI&lt;/xMun&gt; <br />   &lt;UF&gt;SP&lt;/UF&gt; <br />   &lt;CEP&gt;17230000&lt;/CEP&gt; <br />   &lt;cPais&gt;1058&lt;/cPais&gt; <br />   &lt;xPais&gt;BRASIL&lt;/xPais&gt; <br />   &lt;fone&gt;9999999999&lt;/fone&gt; <br />   &lt;/enderDest&gt;<br />   &lt;IE&gt;999999999999&lt;/IE&gt; <br />   &lt;/dest&gt;<br /> - &lt;det nItem="1"&gt;<br /> - &lt;prod&gt;<br />   &lt;cProd&gt;123&lt;/cProd&gt; <br />   &lt;cEAN /&gt; <br />   &lt;xProd&gt;PERFIL CABIDEIRO SG5006 883MM&lt;/xProd&gt; <br />   &lt;CFOP&gt;6102&lt;/CFOP&gt; <br />   &lt;uCom&gt;UN&lt;/uCom&gt; <br />   &lt;qCom&gt;1.0000&lt;/qCom&gt; <br />   &lt;vUnCom&gt;10.0000&lt;/vUnCom&gt; <br />   &lt;vProd&gt;10.00&lt;/vProd&gt; <br />   &lt;cEANTrib /&gt; <br />   &lt;uTrib&gt;UN&lt;/uTrib&gt; <br />   &lt;qTrib&gt;1.0000&lt;/qTrib&gt; <br />   &lt;vUnTrib&gt;10.0000&lt;/vUnTrib&gt; <br />   &lt;/prod&gt;<br /> - &lt;imposto&gt;<br /> - &lt;ICMS&gt;<br /> - &lt;ICMS00&gt;<br />   &lt;orig&gt;0&lt;/orig&gt; <br />   &lt;CST&gt;00&lt;/CST&gt; <br />   &lt;modBC&gt;3&lt;/modBC&gt; <br />   &lt;vBC&gt;10.00&lt;/vBC&gt; <br />   &lt;pICMS&gt;12.00&lt;/pICMS&gt; <br />   &lt;vICMS&gt;1.20&lt;/vICMS&gt; <br />   &lt;/ICMS00&gt;<br />   &lt;/ICMS&gt;<br /> - &lt;PIS&gt;<br /> - &lt;PISNT&gt;<br />   &lt;CST&gt;04&lt;/CST&gt; <br />   &lt;/PISNT&gt;<br />   &lt;/PIS&gt;<br /> - &lt;COFINS&gt;<br /> - &lt;COFINSNT&gt;<br />   &lt;CST&gt;04&lt;/CST&gt; <br />   &lt;/COFINSNT&gt;<br />   &lt;/COFINS&gt;<br />   &lt;/imposto&gt;<br />   &lt;/det&gt;<br /> - &lt;total&gt;<br /> - &lt;ICMSTot&gt;<br />   &lt;vBC&gt;10.00&lt;/vBC&gt; <br />   &lt;vICMS&gt;1.20&lt;/vICMS&gt; <br />   &lt;vBCST&gt;0.00&lt;/vBCST&gt; <br />   &lt;vST&gt;0.00&lt;/vST&gt; <br />   &lt;vProd&gt;10.00&lt;/vProd&gt; <br />   &lt;vFrete&gt;0.00&lt;/vFrete&gt; <br />   &lt;vSeg&gt;0&lt;/vSeg&gt; <br />   &lt;vDesc&gt;0.00&lt;/vDesc&gt; <br />   &lt;vII&gt;0&lt;/vII&gt; <br />   &lt;vIPI&gt;0.00&lt;/vIPI&gt; <br />   &lt;vPIS&gt;0.00&lt;/vPIS&gt; <br />   &lt;vCOFINS&gt;0.00&lt;/vCOFINS&gt; <br />   &lt;vOutro&gt;0.00&lt;/vOutro&gt; <br />   &lt;vNF&gt;10.00&lt;/vNF&gt; <br />   &lt;/ICMSTot&gt;<br />   &lt;/total&gt;<br /> - &lt;transp&gt;<br />   &lt;modFrete&gt;1&lt;/modFrete&gt; <br /> - &lt;transporta&gt;<br />   &lt;CNPJ&gt;99999999999999&lt;/CNPJ&gt; <br />   &lt;xNome&gt;VIACAO GARCIA&lt;/xNome&gt; <br />   &lt;IE&gt;9999999999&lt;/IE&gt; <br />   &lt;xEnder&gt;AV CELSO 1100&lt;/xEnder&gt; <br />   &lt;xMun&gt;LONDRINA&lt;/xMun&gt; <br />   &lt;UF&gt;PR&lt;/UF&gt; <br />   &lt;/transporta&gt;<br /> - &lt;veicTransp&gt;<br />   &lt;placa&gt;AAA1111&lt;/placa&gt; <br />   &lt;UF&gt;PR&lt;/UF&gt; <br />   &lt;/veicTransp&gt;<br /> - &lt;vol&gt;<br />   &lt;qVol&gt;1&lt;/qVol&gt; <br />   &lt;/vol&gt;<br />   &lt;/transp&gt;<br />   &lt;/infNFe&gt;<br /> - &lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;<br /> - &lt;SignedInfo&gt;<br />   &lt;CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /&gt; <br />   &lt;SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /&gt; <br /> - &lt;Reference URI="#NFe41091010257545000131550020000002903885489006"&gt;<br /> - &lt;Transforms&gt;<br />   &lt;Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /&gt; <br />   &lt;Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /&gt; <br />   &lt;/Transforms&gt;<br />   &lt;DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /&gt; <br />   &lt;DigestValue&gt;z+w316xzZIoP4PatwNmBa14+wGg=&lt;/DigestValue&gt; <br />   &lt;/Reference&gt;<br />   &lt;/SignedInfo&gt;<br />   &lt;SignatureValue&gt;ZRH0Ezm2hvVe+wW3VdrUYmM8TB2CU9ALAW+AwuiR2SmnNhtzZjgqrz+JTXFG4I5f5nCQUxWO1JeN uG2kAyl/pc6aFj7C+X25q5hvlCCG9SQvDjuWmBi30SXh/PHcZ+LUenrJd884uu06Drwr/onFYzmE w5ySs2BR+A9k3Epr7ZE=&lt;/SignatureValue&gt; <br /> - &lt;KeyInfo&gt;<br /> - &lt;X509Data&gt;<br />   &lt;X509Certificate&gt;MIIGQDCCBSigAwIBAgIITkKXDYjr6CgwDQYJKoZIhvcNAQEFBQAwTDELMAkGA1UEBhMCQlIxEzAR BgNVBAoTCklDUC1CcmFzaWwxKDAmBgNVBAMTH1NFUkFTQSBDZXJ0aWZpY2Fkb3JhIERpZ2l0YWwg djEwHhcNMDkwODEzMjEwMDAwWhcNMTAwODEzMjEwMDAwWjCB/DELMAkGA1UEBhMCQlIxEzARBgNV BAoTCklDUC1CcmFzaWwxFDASBgNVBAsTCyhFTSBCUkFOQ08pMRgwFgYDVQQLEw8wMDAwMDEwMDA2 MzI2MjIxFDASBgNVBAsTCyhFTSBCUkFOQ08pMRQwEgYDVQQLEwsoRU0gQlJBTkNPKTEUMBIGA1UE CxMLKEVNIEJSQU5DTykxFDASBgNVBAsTCyhFTSBCUkFOQ08pMRQwEgYDVQQLEwsoRU0gQlJBTkNP KTE6MDgGA1UEAxMxSU5EVVNUUklBIENPTUVSQ0lPIEUgUkVQUkVTRU5UQUNPRVMgR0lCSU0gTFRE QSBNRTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEApnPkoSC3t/A7B9KkLB59yPRgO38e43CR 8KxcaDWwDMISclXCseO4uo1vWCI7C57vKbQhw9rsnFranP+u93C+8qIcMHWCAIhm67YDJRpMoFBP qNm4DDLIOH5JQbabDnQaYP6tzJqPAhc8p9YBtzObFfOIWl98E8IzwmpafhAItWMCAwEAAaOCAvcw ggLzMA4GA1UdDwEB/wQEAwIF4DAdBgNVHSUEFjAUBggrBgEFBQcDAgYIKwYBBQUHAwQwHwYDVR0j BBgwFoAUt2CoW/mypq4A7XTr1UrJlmhm9VwwgboGA1UdEQSBsjCBr4EZQ0FSTE9TQFNHQUxVTUlO SU9TLkNPTS5CUqA9BgVgTAEDBKA0EzIwNDExMTk3ODAyMzA3NTMyOTk0MDAwMDAwMDAwMDAwMDAw MDUuODUyLjUzODNTU1BQUqAfBgVgTAEDAqAWExRDQVJMT1MgRURVQVJETyBTT1VaQaAZBgVgTAED A6AQEw44MDkwNTY2NDAwMDEzOaAXBgVgTAEDB6AOEwwwMDAwMDAwMDAwMDAwVwYDVR0gBFAwTjBM BgZgTAECAQYwQjBABggrBgEFBQcCARY0aHR0cDovL3d3dy5jZXJ0aWZpY2Fkb2RpZ2l0YWwuY29t LmJyL3JlcG9zaXRvcmlvL2RwYzCB8AYDVR0fBIHoMIHlMEmgR6BFhkNodHRwOi8vd3d3LmNlcnRp ZmljYWRvZGlnaXRhbC5jb20uYnIvcmVwb3NpdG9yaW8vbGNyL3NlcmFzYWNkdjEuY3JsMEOgQaA/ hj1odHRwOi8vbGNyLmNlcnRpZmljYWRvcy5jb20uYnIvcmVwb3NpdG9yaW8vbGNyL3NlcmFzYWNk djEuY3JsMFOgUaBPhk1odHRwOi8vcmVwb3NpdG9yaW8uaWNwYnJhc2lsLmdvdi5ici9sY3IvU2Vy YXNhL3JlcG9zaXRvcmlvL2xjci9zZXJhc2FjZHYxLmNybDCBlwYIKwYBBQUHAQEEgYowgYcwPAYI KwYBBQUHMAGGMGh0dHA6Ly9vY3NwLmNlcnRpZmljYWRvZGlnaXRhbC5jb20uYnIvc2VyYXNhY2R2 MTBHBggrBgEFBQcwAoY7aHR0cDovL3d3dy5jZXJ0aWZpY2Fkb2RpZ2l0YWwuY29tLmJyL2NhZGVp YXMvc2VyYXNhY2R2MS5wN2IwDQYJKoZIhvcNAQEFBQADggEBAD/JqxgwPOjItKlivZy0AgXNVqbQ HyEhfB39dKMHsm4pPwE+BKJXHU8l1xcc/CYFJ8yfGSYbFGs6ixbyS8Bpeeg4x0wftTg5zEZ/fHDP zXh1C7lQea7IMzO1AcwmTUtGzHlgsNkfm7OjthsDLj4GD2DfF2Z+eIExPiIi72mVczYztSWXTGXg vQhTOu4g2dQcNl5qbzLo4tdGCnrNv6DJnswP09FRGcjC8Ao38YMQYw3HpGgVl53V8Qmmqvh1LKx4 y80jEL2/HNA3r/XCx22cmaMM32o1+eHDN8jEYaJbBsswurhxLLqziiBCiQGLUVHFuCAF47vk7PzY Q9HzkWyN+Xs=&lt;/X509Certificate&gt; <br />   &lt;/X509Data&gt;<br />   &lt;/KeyInfo&gt;<br />   &lt;/Signature&gt;<br />   &lt;/NFe&gt;<br /> <br /> quando envio o xml, retorna o erro 225 - Falha no schema xml. <br /> Porém consigo abrir ele normalmente pelo Visualizador NFeCTe 4.0 fornecido pela receita. E também consigo fazer a validação da estrutura e assinatura através de um programa AssinadorRS fornecido pelo sefaz do RS.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/766132/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/766132/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 22 Oct 2009 12:52:12]]> GMT</pubDate>
				<author><![CDATA[ acmedis]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ só dei uma olhada por cima pq estou saindo do escritorio agora mas da uma olhada no name space da tag "infNFe" seu não me engano não pode ter aquilo ali não...XD]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/766473/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/766473/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 22 Oct 2009 17:04:31]]> GMT</pubDate>
				<author><![CDATA[ alexborges]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ também tentei dessa forma na tag infNFe:<br /> &lt;infNFe Id="NFe41091010257545000131550020000002903885489006" versao="1.10"&gt;<br /> <br /> mas retorna o mesmo erro 225. ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/766665/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/766665/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 23 Oct 2009 07:36:34]]> GMT</pubDate>
				<author><![CDATA[ acmedis]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=acmedis]também tentei dessa forma na tag infNFe:<br /> &lt;infNFe Id="NFe41091010257545000131550020000002903885489006" versao="1.10"&gt;<br /> <br /> mas retorna o mesmo erro 225. [/quote]<br /> <br /> acmedis joguei seu xml no validador da sefaz do RS e os seguintes problemas foram encontrados no shema<br /> <br /> The 'xmlnssi' attribute is not declared. //AQUI ESTÁ SE REFERINDO AO NAMESPACE NA TAG "infNFe" VC TEM Q REMOVER ELE<br /> <br /> The 'http://www.portalfiscal.inf.br/nfe:dEmi' element has an invalid value according to its data type. //SUA DATA ESTA FORMATADA ERRADA "2009 10 21" ONDE DEVERIA SER 2009-10-21 "yyyy-MM-dd"<br /> <br /> The 'http://www.portalfiscal.inf.br/nfe:dSaiEnt' element has an invalid value according to its data type.//SUA DATA ESTA FORMATADA ERRADA "2009 10 22" ONDE DEVERIA SER 2009-10-22 "yyyy-MM-dd" <br /> <br /> The 'http://www.portalfiscal.inf.br/nfe:CNPJ' element has an invalid value according to its data type.//O CNPJ ESTÁ COM 11 DIGITOS ONDE DEVERIAM CONTER 14<br /> <br /> The value of the 'Algorithm' attribute does not equal its fixed value.//O ATRIBUTO "Algorithm" DA ASSINATURA ESTA ERRADO <a class="snap_shots" href="http://www.w3.org/2000/09/xmldsig#rsa" target="_blank" rel="nofollow">http://www.w3.org/2000/09/xmldsig#rsa</a> sha1 ONDE DEVERIA SER <a class="snap_shots" href="http://www.w3.org/2000/09/xmldsig#rsa-sha1" target="_blank" rel="nofollow">http://www.w3.org/2000/09/xmldsig#rsa-sha1</a> NOTE Q NO SEU ESTÁ COM UM ESPAÇO EM BRANCO...<br /> <br /> <br /> da uma revisada nisso, depois posta aqui se conseguiu solucionar seu problema]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/766907/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/766907/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 23 Oct 2009 10:59:55]]> GMT</pubDate>
				<author><![CDATA[ alexborges]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Sobre o ambiente de homologação,<br /> <br /> -Eu posso usar o certificado da empresa que está desenvolvendo o sistema?<br /> -Onde encontro a chave pública do sefaz virtual?]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/767259/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/767259/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 23 Oct 2009 18:19:52]]> GMT</pubDate>
				<author><![CDATA[ LuksS]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ O erro esta relacionado com a validade da Assinatura.<br /> <br /> [list]O arquivo XML foi assinado e a assinatura contém o HASH (DIGEST) do conteudo do arquivo.[/list]<br /> [list]Se por algum motivo o conteudo do arquivo for alterado, será necessário gerar um novo HASH.[/list]<br /> <br /> Sobre assinatura digital: [url]http://www.infowester.com/assincertdigital.php[/url]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/811701/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/811701/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Mon, 18 Jan 2010 16:02:07]]> GMT</pubDate>
				<author><![CDATA[ yross]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ boa tarde a todos, estou com o seguinte problema : preciso inserir no XML que será enviado as informações ref. ao protocolo de autorização e fazer a assinatura digital da nota. Porem quando mando fazer a assinatura fica da sequinte forma o xml :<br />   &lt;?xml version="1.0" encoding="UTF-8" standalone="no" ?&gt; <br /> - &lt;nfeProc xmlns="http://www.portalfiscal.inf.br/nfe" xmlns:ds="http://www.w3.org/2000/09/xmldsig#" xmlns<img src="http://www.guj.com.br/images/smilies/1069449046bcd664c21db15b1dfedaee.gif" border="0">si="http://www.w3.org/2001/XMLSchema-instance" versao="1.10" xsi:schemaLocation="http://www.portalfiscal.inf.br/nfe procNFe_v1.00.xsd"&gt;<br /> - &lt;NFe&gt;<br /> - &lt;infNFe Id="NFe41100280337553000173550030000005056447753010" versao="1.10"&gt;<br /> <br />     .... { tag's da NFe}  <br /> <br />   &lt;/infNFe&gt;<br />   &lt;/NFe&gt;<br /> - &lt;protNFe versao="1.10"&gt;<br /> - &lt;infProt&gt;<br />   &lt;tpAmb&gt;2&lt;/tpAmb&gt; <br />   &lt;verAplic&gt;v3706&lt;/verAplic&gt; <br />   &lt;chNFe&gt;41100280337553000173550030000005056447753010&lt;/chNFe&gt; <br />   &lt;dhRecbto&gt;2010-02-10T15:29:54&lt;/dhRecbto&gt; <br />   &lt;nProt&gt;141100000384752&lt;/nProt&gt; <br />   &lt;digVal&gt;CqvBBuqGUyBd2VBXqALlQISVtX8=&lt;/digVal&gt; <br />   &lt;cStat&gt;100&lt;/cStat&gt; <br />   &lt;xMotivo&gt;Autorizado o uso de NF-e&lt;/xMotivo&gt; <br />   &lt;/infProt&gt;<br />   &lt;/protNFe&gt;<br /> - &lt;Signature xmlns="http://www.w3.org/2000/09/xmldsig#"&gt;<br /> - &lt;SignedInfo&gt;<br />   &lt;CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /&gt; <br />   &lt;SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1" /&gt; <br /> - &lt;Reference URI="#NFe41100280337553000173550030000005056447753010"&gt;<br /> - &lt;Transforms&gt;<br />   &lt;Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature" /&gt; <br />   &lt;Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315" /&gt; <br />   &lt;/Transforms&gt;<br />   &lt;DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1" /&gt; <br />   &lt;DigestValue&gt;ZOQL7z8psu4IFcCeh9IIzVwCFU8=&lt;/DigestValue&gt; <br />   &lt;/Reference&gt;<br />   &lt;/SignedInfo&gt;<br />   &lt;SignatureValue&gt;HK5IxwbfneFTbIwAwO/X+gtb0aQqE/IHuxmtyB/d9oybQivp0Et4tHgqubezIziGgXb8F4Tq2Igr zttLT52o9eu2ap2g3rHkzjnEbXouhW3KOuiaAkAjmsntbQEe6htFWBOn4NsjdCf1619AWlAQ//oV XtQPLnFirLYj0v8sGfRRkXRhxBStuJYe2B3X2ppVRqUdDYHbA267Se/mHniR1QYs/p+za+9Rjn5c zm6RasNbji4L2tjtxFbqnLSpOunVseJ36IEFpcRK2Nm0xBB7qybsJgLAXeRAi8x+PGr5HTEQCOOg V10IaAQxSuIH79S0fn22aOs3ZXkjZ2kPz6wEiA==&lt;/SignatureValue&gt; <br /> - &lt;KeyInfo&gt;<br /> - &lt;X509Data&gt;<br />   &lt;X509Certificate&gt;MIIGiTCCBXGgAwIBAgIQMjAwOTA4MjAxMjM1MDQwMjANBgkqhkiG9w0BAQUFADCBijELMAkGA1UE BhMCQlIxEzARBgNVBAoTCklDUC1CcmFzaWwxNjA0BgNVBAsTLVNlY3JldGFyaWEgZGEgUmVjZWl0 YSBGZWRlcmFsIGRvIEJyYXNpbCAtIFJGQjEuMCwGA1UEAxMlQXV0b3JpZGFkZSBDZXJ0aWZpY2Fk b3JhIGRvIFNFUlBST1JGQjAeFw0wOTA4MjAxODM0NDVaFw0xMDA4MjAxODE1MjVaMIH4MQswCQYD VQQGEwJCUjETMBEGA1UEChMKSUNQLUJyYXNpbDE2MDQGA1UECxMtU2VjcmV0YXJpYSBkYSBSZWNl aXRhIEZlZGVyYWwgZG8gQnJhc2lsIC0gUkZCMREwDwYDVQQLEwhDT1JSRUlPUzETMBEGA1UECxMK QVJDT1JSRUlPUzEWMBQGA1UECxMNUkZCIGUtQ05QSiBBMTERMA8GA1UEBxMIQ2FzY2F2ZWwxCzAJ BgNVBAgTAlBSMTwwOgYDVQQDEzNJTkRVU1RSSUEgREUgUExBU1RJQ09TIENBU0NBVkVMIExUREE6 ODAzMzc1NTMwMDAxNzMwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDRvzotG/1J6uvG gn58iRV/Z6HYMlcgIRVN3T6+8czokkoH1bOYRszU8MstRal1S5d5Qf6yb2viuA2WeDKUrqVkUpvi 9IsFkvfKFTbzrfn3B8SW97gILuNrcWT20DBxS+h6tgjqtmyfrwjRh/pfsOeWC5xpq+MLM+OPWZFl dAUURB1Zhr8xAoYt3obUxZ4qnfZInYtypZld6D22AncNlxGG8Tl6RQk6Qt1BEo3CHR2m0G5mNMRW H4xcVY4DPqdggfhUDlwiiIWUi44M5kGRn3oWuEt+qbPtZPSlLqi1oScNAx20M28khLbDctTUw18X gYIGczIWhQeEp3pw3Ge8NDw/AgMBAAGjggJ5MIICdTAPBgNVHRMBAf8EBTADAQEAMB8GA1UdIwQY MBaAFLkii4YkRueirecpO4xoO02tdJEUMA4GA1UdDwEB/wQEAwIF4DBgBgNVHSAEWTBXMFUGBmBM AQIBCjBLMEkGCCsGAQUFBwIBFj1odHRwczovL2NjZC5zZXJwcm8uZ292LmJyL2Fjc2VycHJvcmZi L2RvY3MvZHBjYWNzZXJwcm9yZmIucGRmMIGzBgNVHREEgaswgaigPQYFYEwBAwSgNAQyMjgxMDE5 NDUwMTYwNTc4MDk0NDAwMDAwMDAwMDAwMDAwMDAwMDA2NDA5ODczU1NQUFKgGwYFYEwBAwKgEgQQ RG9taW5nb3MgU2FsdmF0aaAZBgVgTAEDA6AQBA44MDMzNzU1MzAwMDE3M6AXBgVgTAEDB6AOBAww MDAwMDAwMDAwMDCBFmFuZHJlQHBsYXN0aXZlbC5jb20uYnIwIAYDVR0lAQH/BBYwFAYIKwYBBQUH AwIGCCsGAQUFBwMEMIGoBgNVHR8EgaAwgZ0wMqAwoC6GLGh0dHA6Ly9jY2Quc2VycHJvLmdvdi5i ci9sY3IvYWNzZXJwcm9yZmIuY3JsMDOgMaAvhi1odHRwOi8vY2NkMi5zZXJwcm8uZ292LmJyL2xj ci9hY3NlcnByb3JmYi5jcmwwMqAwoC6GLGh0dHA6Ly93d3cuaXRpLmdvdi5ici9zZXJwcm8vYWNz ZXJwcm9yZmIuY3JsMEwGCCsGAQUFBwEBBEAwPjA8BggrBgEFBQcwAoYwaHR0cDovL2NjZC5zZXJw cm8uZ292LmJyL2NhZGVpYXMvYWNzZXJwcm9yZmIucDdiMA0GCSqGSIb3DQEBBQUAA4IBAQAYwG7a 8xneLZE1MEhIRDJe2vqvc62A8G/LgL+YzeowJOfqnsTgL2OBsK9R+7Ajq4Wu6vK4/TcYE/IpLyij b6fxheTKgLxIjhbvT5ZJBbeXy6qn+JzEJv7TQiD2sX6DiS0zexfIdgH1J7EOUfRbj/dTDscT3aYk shhFfSdK4Flehz/xErWwovBxxj/S7MuG8Q62YT7cdb+exUXhKv7M25ZXD1M0Hv78Cf/xfyJ+aquN rux8jls49z3T7RGkUlrmgd4Qdy1ipZ+MpNfTUHvPRRoXIW/kyCS0h9Yikbz9JlS/795Z2TSmA+hE yeNmHX608GY7IDJfHfv9ximuxkn2NjnE&lt;/X509Certificate&gt; <br />   &lt;/X509Data&gt;<br />   &lt;/KeyInfo&gt;<br />   &lt;/Signature&gt;<br />   &lt;/nfeProc&gt;<br /> <br /> A assinatura digital deveria ficar logo abaixo da tag &lt;/infNFe&gt; ?<br /> Utilizei a classe que o " gilmaslima " postou. <br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/994332/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/994332/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 11 Feb 2010 15:48:27]]> GMT</pubDate>
				<author><![CDATA[ acmedis]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Você deve gerar ou ler o xml da NFe já assinada e concatenar com as outras partes do<br /> xml de distribuição.<br /> <br /> Uma dica: armazene o xml assinado que você enviou no arquivo de lote.<br /> Pode ser que ao regerar o xml da mesma nota e assinar este novo arquivo, o<br /> digestValue fique diferente. Neste caso, o segundo xml não terá validade fiscal.<br /> <br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/994347/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/994347/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 11 Feb 2010 15:56:43]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal,<br /> <br /> Graças a muita leitura aqui no Forum, consegui gerar.. assinar..e enviar uma NFe.<br /> <br /> No momento estou enviando e recebendo um XML de resposta que apresenta a mensagem de sucesso: <br /> <br /> [quote]&lt;xMotivo&gt;Lote recebido com sucesso&lt;/xMotivo&gt;[/quote]<br /> <br /> Como eu faço agora para consultar essa nota fiscal enviada para o ambiente de homologação??<br /> <br /> Existe algum site onde eu possao digitar a chave dela e ver como ela chegou até lá??<br /> <br /> estou tentando no endereço a seguir, porem ele diz que a Nfe consultada não existe.. será que estou consultando no endereço correto?<br /> <br /> [quote]http://homologacao.nfe.fazenda.sp.gov.br/nfo/areapublica/consultanfe.aspx[/quote]<br /> <br /> Vale lembrar que estou enviando para o ambiente de homologação ainda...<br /> <br /> A validação do meu XML esta ok, conforme podem observar abaixo:<br /> <br /> [code]Resultado da Validação do Schema e Conferência da Assinatura:<br /> <br /> PARSER XML:	OK<br /> TIPO DE MENSAGEM:	NF-e<br /> SCHEMA:	OK<br /> ASSINATURA XML:	Assinatura VÁLIDA[/code]<br /> <br /> Obrigado pela respostas... sem dúvida irá me ajudar bastante.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1018231/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1018231/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 23 Mar 2010 00:59:58]]> GMT</pubDate>
				<author><![CDATA[ marpinheiro]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal,<br /> <br /> Acabei criando um método próprio para consultar o Status da NFe via webservice... e o resultado que obtenho é o seguinte:<br /> <br /> [code]&lt;retConsSitNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00"&gt;&lt;tpAmb&gt;2&lt;/tpAmb&gt;&lt;verAplic&gt;SP_NFE_PL_006&lt;/verAplic&gt;&lt;cStat&gt;226&lt;/cStat&gt;&lt;xMotivo&gt;Rejeição: Código da UF do Emitente diverge da UF autorizadora&lt;/xMotivo&gt;&lt;cUF&gt;35&lt;/cUF&gt;&lt;chNFe /&gt;&lt;/retConsSitNFe&gt;[/code]<br /> <br /> [quote]Rejeição: Código da UF do Emitente diverge da UF autorizadora[/quote]<br /> <br /> Conferi o Estado do emitente no XML e esta correto, ou seja "SP". O certificado também é de "SP". O CNPJ do emitente é o mesmo do Certificado.<br /> <br /> O que pode estar havendo??<br /> <br /> Obrigado pela ajuda.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1018240/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1018240/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 23 Mar 2010 02:07:14]]> GMT</pubDate>
				<author><![CDATA[ marpinheiro]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=marpinheiro]Pessoal,<br /> <br /> Acabei criando um método próprio para consultar o Status da NFe via webservice... e o resultado que obtenho é o seguinte:<br /> <br /> [code]&lt;retConsSitNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="2.00"&gt;&lt;tpAmb&gt;2&lt;/tpAmb&gt;&lt;verAplic&gt;SP_NFE_PL_006&lt;/verAplic&gt;&lt;cStat&gt;226&lt;/cStat&gt;&lt;xMotivo&gt;Rejeição: Código da UF do Emitente diverge da UF autorizadora&lt;/xMotivo&gt;&lt;cUF&gt;35&lt;/cUF&gt;&lt;chNFe /&gt;&lt;/retConsSitNFe&gt;[/code]<br /> <br /> [quote]Rejeição: Código da UF do Emitente diverge da UF autorizadora[/quote]<br /> <br /> Conferi o Estado do emitente no XML e esta correto, ou seja "SP". O certificado também é de "SP". O CNPJ do emitente é o mesmo do Certificado.<br /> <br /> [/quote]<br /> <br /> Código da UF é diferente de sigla da UF. Sigla = "SP", código = "35"<br /> <br /> Deve ser isso.<br /> <br /> Alencar]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1018296/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1018296/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 23 Mar 2010 08:24:31]]> GMT</pubDate>
				<author><![CDATA[ philler]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ É por no caso específico da Consulta de Notas Ficais você deve sempre consultar no Estado do Emitente. <br /> Os dois primeiros digitos da Chave Representam o código do IBGE do Estado. Você deve então pela chave identificar qual é o código Estado, e consultar a nota do estado em que ela foi emitida.<br /> <br /> Seguem os códigos<br /> <br /> [code]<br /> "UF"	"IBGE"<br /> "AC"	12<br /> "AL"	27<br /> "AM"	13<br /> "AP"	16<br /> "BA"	29<br /> "ES"	32<br /> "MA"	21<br /> "PB"	25<br /> "PE"	26<br /> "PI"	22<br /> "RO"	11<br /> "RR"	14<br /> "TO"	17<br /> "SP"	35<br /> "CE"	23<br /> "DF"	53<br /> "GO"	52<br /> "MG"	31<br /> "MS"	50<br /> "MT"	51<br /> "PA"	15<br /> "PR"	41<br /> "RJ"	33<br /> "RN"	24<br /> "RS"	43<br /> "SC"	42<br /> "SE"	28<br /> [/code]<br /> <br /> As URLS para cada estado, você encontra aqui:<br /> <br /> http://www.nfe.fazenda.gov.br/portal/WebServices.aspx<br /> <br /> ATENÇÃO: Isso se aplica apenas a Consulta, no caso de emissão você deve enviar sempre para o mesmo estado em que o seu certificado foi emitido.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1018297/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1018297/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 23 Mar 2010 08:29:13]]> GMT</pubDate>
				<author><![CDATA[ andrefariagomes]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Olá Senhores, <br /> <br />         Eu vi em outro tópico sobre a extração do dados do assinante com base no certificado, eu testei e funcionou, mas agora eu gostaria de saber se é possível extrair as mesmas informações do arquivo XML da NFe com base no conteúdo da tag X509Certificate ou X509Data ou qualquer coisas assim abaixo segue o código, eu estou obtendo apenas com o X509 imagino que precise da Signature também.<br />         No código abaixo o método test funciona e o testAlheio não, que é o que eu quero fazer funcionar.<br /> [code]<br /> import java.io.ByteArrayInputStream;<br /> import java.io.File;<br /> import java.io.FileInputStream;<br /> import java.io.IOException;<br /> import java.io.InputStream;<br /> import java.security.KeyStore;<br /> import java.security.PrivateKey;<br /> import java.security.cert.CertificateException;<br /> import java.security.cert.CertificateFactory;<br /> import java.security.cert.CertificateParsingException;<br /> import java.security.cert.X509Certificate;<br /> import java.util.Enumeration;<br /> import java.util.List;<br /> import org.bouncycastle.asn1.ASN1InputStream;<br /> import org.bouncycastle.asn1.ASN1TaggedObject;<br /> import org.bouncycastle.asn1.DERObject;<br /> import org.bouncycastle.asn1.DERObjectIdentifier;<br /> import org.bouncycastle.asn1.DEROctetString;<br /> import org.bouncycastle.asn1.DERSequence;<br /> import org.bouncycastle.asn1.DERString;<br /> <br /> /**<br />  *<br />  * @author Murilo<br />  */<br /> public class Main {<br /> <br />     private void testAlheio() throws CertificateException, IOException {<br />         String x509content = "conteudo da tag &lt;509Certificate&gt;";<br />         CertificateFactory fact = CertificateFactory.getInstance("X.509");<br />         ByteArrayInputStream bais = new ByteArrayInputStream(x509content.getBytes());<br />         while (bais.available() &gt; 0) {<br />             X509Certificate x509 = (X509Certificate) fact.generateCertificate(bais);<br />             exibeCertificado(x509);<br />         }<br />         bais.close();<br />     }<br /> <br />     private void exibeCertificado(X509Certificate certificate) throws CertificateParsingException, IOException {<br />         for (List&lt;?&gt; subjectAlternativeName : certificate.getSubjectAlternativeNames()) {<br />             String email;<br />             Pair&lt;DERObjectIdentifier, String&gt; otherName;<br />             // O primeiro elemento é um Integer com o valor 0 = otherName, 1 = rfc822name etc.<br />             // O segundo valor é um byte array ou uma String. Veja o javadoc de<br />             // getSubjectAlternativeNames.<br />             switch (((Number) subjectAlternativeName.get(0)).intValue()) {<br />                 case 0: // OtherName - contém CPF, CNPJ etc.<br />                     otherName = getOtherName((byte[]) subjectAlternativeName.get(1));<br />                     System.out.println("First : " + otherName.first);<br />                     System.out.println("Second : " + otherName.second);<br />                     // o OID fica em otherName.first<br />                     break;<br />                 case 1: // rfc822Name - usado para email<br />                     email = (String) subjectAlternativeName.get(1);<br />                     System.out.println("email : "+email);<br />                     break;<br />                 default:<br />                     break;<br />             }<br />         }<br />     }<br /> <br />     /**<br />      * Uma classe que encapsula pares de objetos.<br />      * Inspirado no template pair&lt;&gt; da STL.<br />      *<br />      * @param &lt;T&gt; O primeiro tipo.<br />      * @param &lt;U&gt; O segundo tipo.<br />      */<br />     class Pair&lt;T, U&gt; {<br /> <br />         /** O primeiro objeto. */<br />         public T first;<br />         /** O segundo objeto. */<br />         public U second;<br /> <br />         /** Construtor */<br />         public Pair(T t, U u) {<br />             first = t;<br />             second = u;<br />         }<br />     }<br /> <br />     /**<br />      * Interpreta um dado do tipo otherName.<br />      * Obs. O JDK 5.0 não tem classes que lidem com um dado do tipo OtherName.<br />      * É necessário usar o BouncyCastle.<br />      * @param encoded O dado em ASN.1.<br />      * @return Um par contendo o OID e o conteúdo.<br />      */<br />     private Pair&lt;DERObjectIdentifier, String&gt; getOtherName(byte[] encoded) throws IOException {<br />         // O JDK 5.0 não tem classes que lidem com um dado do tipo OtherName.<br />         // É necessário usar o BouncyCastle.<br />         ASN1InputStream inps = new ASN1InputStream(encoded);<br />         DERSequence seq = null;<br />         DERObjectIdentifier oid = null;<br />         String conteudo = "";<br />         seq = (DERSequence) inps.readObject();<br />         inps.close();<br />         Enumeration en = seq.getObjects();<br />         oid = (DERObjectIdentifier) en.nextElement();<br />         DERObject obj = ((ASN1TaggedObject) ((ASN1TaggedObject) en.nextElement()).getObject()).getObject();<br />         if (obj instanceof DERString) { // Certificados antigos SERASA - incorretos<br />             conteudo = ((DERString) obj).getString();<br />         } else if (obj instanceof DEROctetString) { // Certificados corretos<br />             conteudo = new String(((DEROctetString) obj).getOctets(), "ISO-8859-1");<br />         }<br />         return new Pair&lt;DERObjectIdentifier, String&gt;(oid, conteudo);<br />     }<br /> <br /> //<br />     /**<br />      * @param args the command line arguments<br />      */<br />     public static void main(String[] args) throws CertificateParsingException, IOException, CertificateException {<br /> //        new Main().test();<br />         new Main().testAlheio();<br />     }<br /> <br />     private void test() throws CertificateParsingException, IOException {<br />         File file = new File("CERT.pfx");<br />         X509Certificate certificate = null;<br /> <br />         if (file.exists()) {<br /> <br /> //            CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");<br /> //            InputStream is = new FileInputStream(file);<br /> //            Certificate certificate = certificateFactory.generateCertificate(is);<br /> //            System.out.println("Tipo de certificado "+certificate.getType());<br /> //            is.close();<br />             try {<br />                 KeyStore keyStore = KeyStore.getInstance("PKCS12");<br />                 InputStream is = new FileInputStream(file);<br />                 String senha = "senha";<br />                 keyStore.load(is, senha.toCharArray());<br />                 is.close();<br /> <br />                 String alias = "";<br /> <br />                 PrivateKey privateKey = null;<br />                 Enumeration e = keyStore.aliases();<br />                 while (e.hasMoreElements()) {<br />                     alias = (String) e.nextElement();<br />                     certificate = (X509Certificate) keyStore.getCertificate(alias);<br />                     privateKey = (PrivateKey) keyStore.getKey(alias, senha.toCharArray());<br />                     System.out.println(certificate + " " + privateKey.getAlgorithm());<br />                 }<br />             } catch (Exception ex) {<br />                 ex.printStackTrace();<br />                 System.out.println(ex.getCause());<br />             }<br />         } else {<br />             System.out.println("Certificado nao encontrado em " + file.getAbsolutePath());<br />         }<br />         exibeCertificado(certificate);<br />     }<br /> }<br /> <br /> [/code]]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1021933/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1021933/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 26 Mar 2010 22:20:04]]> GMT</pubDate>
				<author><![CDATA[ murilo.tuvani]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=julianosott]<br /> <br /> ou seja, não pode ter o xmlns:ns2="http://www.w3.org/2000/09/xmldsig#"<br /> <br /> o mesmo vale para o enviNFe:<br /> [code]<br /> &lt;enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.10"&gt;<br />   &lt;idLote&gt;1&lt;/idLote&gt; <br />   &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br /> [/code]<br /> <br /> nesse caso tanto o envi como cada nfe devem ter xmlns="http://www.portalfiscal.inf.br/nfe" e o envi não pode ter o xmlns:ns2="http://www.w3.org/2000/09/xmldsig#". Se por acaso o xml estiver do jeito errado, pode usar esses códigos no assinador, ou criar outro método:<br /> <br /> esse aqui remove o xmlns:ns2 do elemento raíz:<br /> [code]<br /> 	doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> [/code]<br /> <br /> esse aqui adiciona o xmlns necessário a tag NFe:<br /> [code]<br /> 	((Element) doc.getDocumentElement().getElementsByTagName("NFe").item(i)).setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> [/code]<br /> <br /> Quem quiser verificar o xml pode usar esse site: http://www.sefaz.rs.gov.br/AAE_ROOT/NFE/SAT-WEB-NFE-VAL_1.asp Acho que ele só valida os certificados do Rio Grande do Sul, mas o bom é que ele verifica a estrutura do xml tb.<br /> <br /> É isso por enquanto, qualquer coisa é só perguntar.[/quote]<br /> <br /> <br /> Só para ajudar os próximos, essa solução ai em cima funcionou pra mim q estava com problema de assinatura, porém além disso também fiz:<br /> [code]<br /> 		docs.getDocumentElement().removeAttribute("xmlns:ns2");<br /> 		docs.getDocumentElement().removeAttribute("xmlns:ds");<br /> 		docs.getDocumentElement().removeAttribute("xmlns:xsi");<br /> [/code]<br /> <br /> funcionou direitinho depois q fiz isso]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1029360/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1029360/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 8 Apr 2010 10:17:35]]> GMT</pubDate>
				<author><![CDATA[ Rafael Rossignol]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=O Grande Bé][quote=julianosott]<br /> <br /> ou seja, não pode ter o xmlns:ns2="http://www.w3.org/2000/09/xmldsig#"<br /> <br /> o mesmo vale para o enviNFe:<br /> [code]<br /> &lt;enviNFe xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.10"&gt;<br />   &lt;idLote&gt;1&lt;/idLote&gt; <br />   &lt;NFe xmlns="http://www.portalfiscal.inf.br/nfe"&gt;<br /> [/code]<br /> <br /> nesse caso tanto o envi como cada nfe devem ter xmlns="http://www.portalfiscal.inf.br/nfe" e o envi não pode ter o xmlns:ns2="http://www.w3.org/2000/09/xmldsig#". Se por acaso o xml estiver do jeito errado, pode usar esses códigos no assinador, ou criar outro método:<br /> <br /> esse aqui remove o xmlns:ns2 do elemento raíz:<br /> [code]<br /> 	doc.getDocumentElement().removeAttribute("xmlns:ns2");<br /> [/code]<br /> <br /> esse aqui adiciona o xmlns necessário a tag NFe:<br /> [code]<br /> 	((Element) doc.getDocumentElement().getElementsByTagName("NFe").item(i)).setAttribute("xmlns", "http://www.portalfiscal.inf.br/nfe");<br /> [/code]<br /> <br /> Quem quiser verificar o xml pode usar esse site: http://www.sefaz.rs.gov.br/AAE_ROOT/NFE/SAT-WEB-NFE-VAL_1.asp Acho que ele só valida os certificados do Rio Grande do Sul, mas o bom é que ele verifica a estrutura do xml tb.<br /> <br /> É isso por enquanto, qualquer coisa é só perguntar.[/quote]<br /> <br /> <br /> Só para ajudar os próximos, essa solução ai em cima funcionou pra mim q estava com problema de assinatura, porém além disso também fiz:<br /> [code]<br /> 		docs.getDocumentElement().removeAttribute("xmlns:ns2");<br /> 		docs.getDocumentElement().removeAttribute("xmlns:ds");<br /> 		docs.getDocumentElement().removeAttribute("xmlns:xsi");<br /> [/code]<br /> <br /> funcionou direitinho depois q fiz isso[/quote]<br /> <br /> Só reforçando o que o Grande Bé comentou no manual de integração da NFe fala que não é permitida a utilização de prefixos de namespace...XD]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1038651/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1038651/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 23 Apr 2010 08:18:32]]> GMT</pubDate>
				<author><![CDATA[ alexborges]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Só para atualizar.... o validador via web para verificar os xmls do sefaz é <a class="snap_shots" href="http://www.sefaz.rs.gov.br/NFE/NFE-VAL.aspx" target="_blank" rel="nofollow">http://www.sefaz.rs.gov.br/NFE/NFE-VAL.aspx</a> não é mais o endereço antigo]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1048845/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1048845/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 11 May 2010 14:10:56]]> GMT</pubDate>
				<author><![CDATA[ leopoldof]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Amigos do forum,<br /> <br /> <br /> Eu sou programador em ambiente Mac Os X (amador).<br /> <br /> Tenho rotinas escritas onde controle há anos em minha pequena empresa a emissão de notas fiscais, recebimentos e etc...<br /> <br /> Com o surgimento da nota fiscal eletrônica, portei uma rotina que gera um arquivo em texto. (.txt) que uso na importação para o programa gratuito s]da Sefaz-SP, emissor gratuito de NFe.<br /> <br /> Gostaria de melhorar minhas próprias rotinas para assinar e transmitir o .xml da NFe. <br /> <br /> Creio que o primeiro passo seria assinar o XML.<br /> <br /> Procuro ajuda, e estou de acordo em pagar por sua ajuda.<br /> <br /> Alguém neste fórum poderia me ajudar escrevendo ou adaptando sua linha de código existente, para mim?<br /> <br /> Pensei em ter um comando de terminal, que posso invocar de dentro de meu programa existente, que assinasse o arquivo de texto que sou capaz de gerar, mas não sou capaz de assinar.<br /> <br /> Ou mesmo gravar numa pasta por exemplo: "Notas Fiscais por Assinar", e uma rotina automática assinasse o xml e automáticamente gravasse cópia dele em outra pasta "Notas Fiscais Assinadas".<br /> <br /> Creio que não deve ser difícil para alguém que já tem suas rotinas prontas.<br /> <br /> Aguardo contato,<br /> <br /> Obrigado,<br /> <br /> <br /> Bernardo Höhl<br /> <br /> Usina Brasileira de Cristobalita Ltda<br /> <a class="snap_shots" href="http://www.rutenium.com.br" target="_blank" rel="nofollow">http://www.rutenium.com.br</a><br /> <br /> Meu celular: 21-99775490<br /> <br /> eu endereço de email é:<br /> <br /> fundidor + arroba + mac.com]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1076167/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1076167/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Sun, 4 Jul 2010 19:29:30]]> GMT</pubDate>
				<author><![CDATA[ fundidor]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Pessoal, boa tarde.<br /> <br /> Meu problema é o seguinte: Preciso saber como me monunicar com o webservice e enviar os dados da minha NF. eu já fiz a assinatura do xml, o que preciso saber é como enviar a nfe para a prefeitura.<br /> <br /> vi alguns exemplos aqui mas não compreendi, pois eu tenho um keystore, um pfx, senha, o link, e o XMl. tudo isso deve ser passado como parâmetro(creio eu) na função que fará a comunicação com o webservice da prefeitura. se alguém puder me ajuda, grato pela atenção!]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1117809/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1117809/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Fri, 17 Sep 2010 15:39:13]]> GMT</pubDate>
				<author><![CDATA[ gambazinho]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Olá Pessoal<br /> <br /> Estou com problemas para validar a assinatura digital do XML de terceiros, sei que existe o próprio validador oferecido pelo governo, porem preciso fazer um que valide o XML também.<br /> <br /> Tem alguns XML que eu NÃO consigo validar e a aplicação do governo valida.<br /> <br /> Alguém tem algum exemplo de método de validação do XML assinado digitalmente?<br /> <br /> ]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1128665/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1128665/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 5 Oct 2010 18:02:08]]> GMT</pubDate>
				<author><![CDATA[ JavAlan]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ [quote=Yky Mattshawn][quote=julianosott]conseguimos fazer funcionar aqui. Quem tiver duvidas é só pedir. Estamos pensando em fazer um tutorial pra nfe :-p (se ninguem for contra :-p)[/quote]<br /> <br /> Bah, um tutorial seria muito bacana! Aqui na empresa temos planos para implementar a NFe nos próximos e ter um artigo sobre isso feito por alguém que já teve problemas e conseguiu resolver seria de muita valia! Pois você já tem noção dos problemas encontrados nesse processo.[/quote]<br /> <br /> Sou novo aqui, estou começando um projeto para criar componentes para NFe de campinas está faltando somente a assinatura do XML, você tem algum código fonte java com exemplo de como assinar a NFSe.]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1143823/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1143823/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Tue, 2 Nov 2010 17:59:30]]> GMT</pubDate>
				<author><![CDATA[ jpleiser@gmail.com]]></author>
			</item>
			<item>
				<title>Re:assinaturas de arquivos xml da NFe</title>
				<description><![CDATA[ Jpleiser você está tentando assinar Nfe 1.10 ou 2.0?<br /> <br /> []'s]]></description>
				<guid isPermaLink="true">http://www.guj.com.br/prepost/83758/1156658/reassinaturas-de-arquivos-xml-da-nfe
</guid>
				<link>http://www.guj.com.br/prepost/83758/1156658/reassinaturas-de-arquivos-xml-da-nfe
</link>
				<pubDate><![CDATA[Thu, 25 Nov 2010 17:04:09]]> GMT</pubDate>
				<author><![CDATA[ pohl]]></author>
			</item>
	</channel>
</rss>
