opa!
Estou tendo retorno de “assinatura invalida”
Consegui assinar, mas não está valido, estou usando este codigo:
Metodo de web service que estou fazendo: nfeRecepcaoEventos( para a manifestação de destinatário)
package br.com.controles.util;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.InvalidAlgorithmParameterException;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.cert.X509Certificate;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Enumeration;
import java.util.List;
import javax.xml.crypto.dsig.CanonicalizationMethod;
import javax.xml.crypto.dsig.DigestMethod;
import javax.xml.crypto.dsig.Reference;
import javax.xml.crypto.dsig.SignatureMethod;
import javax.xml.crypto.dsig.SignedInfo;
import javax.xml.crypto.dsig.Transform;
import javax.xml.crypto.dsig.XMLSignature;
import javax.xml.crypto.dsig.XMLSignatureFactory;
import javax.xml.crypto.dsig.dom.DOMSignContext;
import javax.xml.crypto.dsig.keyinfo.KeyInfo;
import javax.xml.crypto.dsig.keyinfo.KeyInfoFactory;
import javax.xml.crypto.dsig.keyinfo.X509Data;
import javax.xml.crypto.dsig.spec.C14NMethodParameterSpec;
import javax.xml.crypto.dsig.spec.TransformParameterSpec;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
/**
*
* @author Accipiens
*/
public class AssinarXml {
private static final String INFEVENTO = "infEvento";
private static final String EVENTO = "evento";
private static final String ENVEVENTO = "envEvento";
private PrivateKey privateKey;
private KeyInfo keyInfo;
public String assinaEnvEvento(String xml, String certificado, String senha) throws Exception {
Document document = documentFactory(xml);
XMLSignatureFactory signatureFactory = XMLSignatureFactory.getInstance("DOM");
ArrayList<Transform> transformList = signatureFactory(signatureFactory);
loadCertificates(certificado, senha, signatureFactory);
for (int i = 0; i < document.getDocumentElement().getElementsByTagName(INFEVENTO).getLength(); i++) {
assinar(signatureFactory, transformList, privateKey, keyInfo, document, i);
}
return outputXML(document);
}
private void assinar(XMLSignatureFactory fac,
ArrayList<Transform> transformList, PrivateKey privateKey,
KeyInfo ki, Document document, int index) throws Exception {
NodeList elements = null;
elements = document.getElementsByTagName(INFEVENTO);
org.w3c.dom.Element el = (org.w3c.dom.Element) elements.item(index);
String id = el.getAttribute("Id");
el.setIdAttribute("Id", true);
System.out.println("INDEX "+index);
Reference ref = fac.newReference("#" + id,
fac.newDigestMethod(DigestMethod.SHA1, null), transformList,
null, null);
SignedInfo si = fac.newSignedInfo(fac.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null), fac
.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
XMLSignature signature = fac.newXMLSignature(si, ki);
DOMSignContext dsc = new DOMSignContext(privateKey,
document.getDocumentElement().getElementsByTagName(INFEVENTO).item(index));
signature.sign(dsc);
}
public ArrayList<Transform> signatureFactory(
XMLSignatureFactory signatureFactory)
throws NoSuchAlgorithmException, InvalidAlgorithmParameterException {
ArrayList<Transform> transformList = new ArrayList<Transform>();
TransformParameterSpec tps = null;
Transform envelopedTransform = signatureFactory.newTransform(
Transform.ENVELOPED, tps);
Transform c14NTransform = signatureFactory.newTransform(
"http://www.w3.org/TR/2001/REC-xml-c14n-20010315", tps);
transformList.add(envelopedTransform);
transformList.add(c14NTransform);
return transformList;
}
public Document documentFactory(String xml) throws SAXException,
IOException, ParserConfigurationException {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
Document document = factory.newDocumentBuilder().parse(
new ByteArrayInputStream(xml.getBytes()));
return document;
}
public void loadCertificates(String certificado, String senha,
XMLSignatureFactory signatureFactory) throws Exception {
InputStream entrada = new FileInputStream(certificado);
KeyStore ks = KeyStore.getInstance("pkcs12");
try {
ks.load(entrada, senha.toCharArray());
} catch (IOException e) {
throw new Exception("Senha do Certificado Digital incorreta ou Certificado inválido.");
}
KeyStore.PrivateKeyEntry pkEntry = null;
Enumeration<String> aliasesEnum = ks.aliases();
while (aliasesEnum.hasMoreElements()) {
String alias = (String) aliasesEnum.nextElement();
if (ks.isKeyEntry(alias)) {
pkEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias,
new KeyStore.PasswordProtection(senha.toCharArray()));
privateKey = pkEntry.getPrivateKey();
break;
}
}
X509Certificate cert = (X509Certificate) pkEntry.getCertificate();
info("SubjectDN: " + cert.getSubjectDN().toString());
KeyInfoFactory keyInfoFactory = signatureFactory.getKeyInfoFactory();
List<X509Certificate> x509Content = new ArrayList<X509Certificate>();
x509Content.add(cert);
X509Data x509Data = keyInfoFactory.newX509Data(x509Content);
keyInfo = keyInfoFactory.newKeyInfo(Collections.singletonList(x509Data));
}
public String outputXML(Document doc) throws TransformerException {
ByteArrayOutputStream os = new ByteArrayOutputStream();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(os));
String xml = os.toString();
if ((xml != null) && (!"".equals(xml))) {
xml = xml.replaceAll("\\r\\n", "");
xml = xml.replaceAll(" standalone=\"no\"", "");
}
return xml;
}
public static String lerXML(String fileXML) throws IOException {
String linha = "";
StringBuilder xml = new StringBuilder();
BufferedReader in = new BufferedReader(new InputStreamReader(
new FileInputStream(fileXML)));
while ((linha = in.readLine()) != null) {
xml.append(linha);
}
in.close();
return xml.toString();
}
/**
* Log ERROR.
*
* @param error
*/
public static void error(String error) {
System.out.println("| ERROR: " + error);
}
/**
* Log INFO.
*
* @param info
*/
public static void info(String info) {
System.out.println("| INFO: " + info);
}
}
}
e para executar a função estou fazendo isso:
[code]
String xmlEnviNFe = AssinarXml.lerXML(caminhoArqXml);
String xmlEnviNFeAssinado = assinarxml.assinaEnvEvento(xmlEnviNFe,
caminhoDoCertificadoDoCliente,
senhaDoCertificadoDoCliente);
AssinarXml.info("XML EnviNFe Assinado: " + xmlEnviNFeAssinado);[/code]
Esté é o xml com a assinatura invalida(mas assinado):
<?xml version="1.0" encoding="UTF-8"?>
<envEvento xmlns="http://www.portalfiscal.inf.br/nfe" versao="1.00">
<idLote>1</idLote>
<evento versao="1.00">
<infEvento Id="ID2102104314019301500600291455020000024141127099561901">
<cOrgao>43</cOrgao>
<tpAmb>1</tpAmb>
<CNPJ>06044680000121</CNPJ>
<chNFe>43140193015006002914550200000241411270995619</chNFe>
<dhEvento>2014-01-10T15:41:02-02:00</dhEvento>
<tpEvento>210210</tpEvento>
<nSeqEvento>1</nSeqEvento>
<verEvento>1.00</verEvento>
<detEvento versao="1.00">
<descEvento>Ciencia da Operacao</descEvento>
</detEvento>
</infEvento>
</evento>
<Signature xmlns="http://www.w3.org/2000/09/xmldsig#">
<SignedInfo>
<CanonicalizationMethod Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
<SignatureMethod Algorithm="http://www.w3.org/2000/09/xmldsig#rsa-sha1"/>
<Reference URI="#ID2102104314019301500600291455020000024141127099561901">
<Transforms>
<Transform Algorithm="http://www.w3.org/2000/09/xmldsig#enveloped-signature"/>
<Transform Algorithm="http://www.w3.org/TR/2001/REC-xml-c14n-20010315"/>
</Transforms>
<DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/>
<DigestValue>jGiw4TTvrO+jjx3RTehIMEtRfRI=</DigestValue>
</Reference>
</SignedInfo>
<SignatureValue>NJQn2Mii+lH23qCcamu1ggj2H1h62Yb6hdrCUT2/uO4m1YqRI3MZkqndW/RNTO+if9DLstxEHsDTM1yxSA+fwm/ElEy5Ao9tfsG+ODH9+zQ1wbQrr88tnWkMuFFQK+HW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