Essa foi a unica diferença que apresenta do seu código para o meu em relação a seu comentário.
O restante do meu código creio que no seu faça antes da chamada do método assinar. Porem essa alteração também não surtiu efeito.
Segue versão que estou utilizando do java: [quote]java version “1.7.0_25”
Java™ SE Runtime Environment (build 1.7.0_25-b17)
Java HotSpot™ Client VM (build 23.25-b01, mixed mode, sharing)[/quote]
Segue código alterado
[code]public String assinar(int tipo, String xml) throws NFEException {
java.lang.System.setProperty(“org.jcp.xml.dsig.secureValidation”, “false”);
// tipo
// ‘1’ - NFE
// ‘2’ - CANCELAMENTO
// ‘3’ - INUTILIZACAO
// ‘4’ - EVENTO / Carta de correção eletrônica
// ‘5’ - EVENTO / Manifestação do Destinatário
// ‘6’ - EVENTO / Download da NFe
// ‘7’ - EVENTO / Consulta da NFe
String tag = “”;
String xsd = “”;
if(tipo == 1) {
tag = “infNFe”;
//xsd = xsdEnvNFe; //só é feita a validação do lote
} else if (tipo == 2 || tipo == 4 || tipo == 5 || tipo == 6 || tipo == 7) {
tag = “infEvento”;
if(tipo == 2){
xsd = xsdCancNFe;
}else if(tipo == 4){
xsd = xsdEnvCCe;
}else if(tipo == 5){
xsd = xsdManDest;
}
} else if (tipo == 3) {
tag = “infInut”;
xsd = xsdInutNFe;
}
try {
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(false);
DocumentBuilder builder = factory.newDocumentBuilder();
Document docs = builder.parse(new StringBufferInputStream(xml));
// Obtem elemento do documento a ser assinado, será criado uma
// REFERENCE para o mesmo
NodeList elements = docs.getElementsByTagName(tag);
Element el = (Element) elements.item(0);
String id = el.getAttribute("Id");
//System.out.println(id);
el.setIdAttribute("Id", true);
// Create a DOM XMLSignatureFactory that will be used to
// generate the enveloped signature.
String providerName = System.getProperty(PROVIDER_NAME, PROVIDER_CLASS_NAME);
XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());
//XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", new org.jcp.xml.dsig.internal.dom.XMLDSigRI());
// Create a Reference to the enveloped document (in this case,
// you are signing the whole document, so a URI of "" signifies
// that, and also specify the SHA1 digest algorithm and
// the ENVELOPED Transform.
ArrayList<Transform> transformList = new ArrayList<Transform>();
TransformParameterSpec tps = null;
Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,tps);
Transform c14NTransform = fac.newTransform(C14N_TRANSFORM_METHOD, tps);
transformList.add(envelopedTransform);
transformList.add(c14NTransform);
Reference ref = fac.newReference("#" + id, fac.newDigestMethod(DigestMethod.SHA1, null), transformList, null, null);
// Create the SignedInfo.
SignedInfo si = fac
.newSignedInfo(fac.newCanonicalizationMethod(
CanonicalizationMethod.INCLUSIVE,
(C14NMethodParameterSpec) null), fac
.newSignatureMethod(SignatureMethod.RSA_SHA1, null),
Collections.singletonList(ref));
// Load the KeyStore and get the signing key and certificate.
KeyStore ks = null;
if (certTipo.equals("PKCS11")) { //A3
Provider p = new sun.security.pkcs11.SunPKCS11(parametros.getProperty("nfe.certificado.token"));
Security.addProvider(p);
ks = KeyStore.getInstance("PKCS11");
ks.load(null, parametros.getProperty("nfe.certificado.pass").toCharArray());
} else { //A1
System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
ks = KeyStore.getInstance("PKCS12");
ks.load(
new FileInputStream(parametros.getProperty("nfe.certificado.pfx")),
parametros.getProperty("nfe.certificado.pass").toCharArray()
);
}
KeyStore.PrivateKeyEntry keyEntry = null;
Enumeration<String> aliasesEnum = ks.aliases();
while (aliasesEnum.hasMoreElements())
{
String alias = (String) aliasesEnum.nextElement();
if (ks.isKeyEntry(alias))
{
keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(parametros.getProperty("nfe.certificado.pass").toCharArray()));
break;
}
}
X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
// Create the KeyInfo containing the X509Data.
KeyInfoFactory kif = fac.getKeyInfoFactory();
List<X509Certificate> x509Content = new ArrayList<X509Certificate>();
// x509Content.add(cert.getSubjectX500Principal().getName());
x509Content.add(cert);
X509Data xd = kif.newX509Data(x509Content);
KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd));
// Instantiate the document to be signed.
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
Document doc = dbf.newDocumentBuilder().parse(new StringBufferInputStream(xml));
// Create a DOMSignContext and specify the RSA PrivateKey and
// location of the resulting XMLSignature's parent element.
/**DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement());**/
DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(),
doc.getDocumentElement().getElementsByTagName(tag).item(0));
dsc.setBaseURI("ok");
// Create the XMLSignature, but don't sign it yet.
XMLSignature signature = fac.newXMLSignature(si, ki);
// Marshal, generate, and sign the enveloped signature.
signature.sign(dsc);
// Output the resulting document.
//OutputStream os = new FileOutputStream(caminhoXmlNovo);
StringWriter sw = new StringWriter();
TransformerFactory tf = TransformerFactory.newInstance();
Transformer trans = tf.newTransformer();
trans.transform(new DOMSource(doc), new StreamResult(sw));
// Find Signature element.
NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature");
if (nl.getLength() == 0) {
throw new NFEException("Cannot find Signature element");
}
// Create a DOMValidateContext and specify a KeySelector and document
// context.
DOMValidateContext valContext = new DOMValidateContext( new X509KeySelector(ks), nl.item(0));
// Unmarshal the XMLSignature.
XMLSignature signatures = fac.unmarshalXMLSignature(valContext);
// Validate the XMLSignature.
boolean coreValidity = signatures.validate(valContext);
// Check core validation status.
if (coreValidity == false)
throw new Exception("Assinatura inválida.");
String retorno = sw.toString();
if (tipo != 1)
validaXML(retorno, xsd);
System.out.println("XML assinado: " + retorno);
return retorno;
} catch (Exception e) {
e.printStackTrace();
throw new NFEException(e.getMessage());
}
}[/code]