SAXException - NF-e + A3

Olá Pessoal,

Precisava de uma força de voces, eu estou utilizando um certificado A3 em minha aplicação, agora eu consigo acessar os certificados e tal, mas, quando eu tento enviar a mensagem ele recebe a excessão abaixo.

org.xml.sax.SAXException: Processing instructions are not allowed within SOAP messages

Segue abaixo o meu codigo:

System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");

Provider p = new sun.security.pkcs11.SunPKCS11("c:/sistema/token.cfg");
Security.addProvider(p);
		
KeyStore ks = null;
try {
     ks = KeyStore.getInstance("PKCS11");
} catch (KeyStoreException e2) {
     // TODO Auto-generated catch block
     e2.printStackTrace();
}

try {
     ks.load(null, "safeweb".toCharArray());
} catch (NoSuchAlgorithmException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
} catch (CertificateException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
} catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
}
		
Enumeration aliasesEnum = null;
try {
aliasesEnum = ks.aliases();
} catch (KeyStoreException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

while (aliasesEnum.hasMoreElements()) {
   String alias = (String)aliasesEnum.nextElement();
   System.out.println("Alias: " + alias);
   X509Certificate cert = null;
   try {
   cert = (X509Certificate) ks.getCertificate(alias);
   } catch (KeyStoreException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   }
   System.out.println("Certificate: " + cert);

   PrivateKey privateKey = null;
   try {
   privateKey = (PrivateKey) ks.getKey(alias, null);
   } catch (UnrecoverableKeyException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   } catch (KeyStoreException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
   } catch (NoSuchAlgorithmException e) {
   // TODO Auto-generated catch block
   e.printStackTrace();
  }
  System.out.println("Private key: " + privateKey);
}

System.setProperty("javax.net.ssl.trustStoreType", "JKS");
System.setProperty("javax.net.ssl.trustStore", "c:/sistema/certificado/servidorNfe.keystore");//Aqui vem o arquivo criado através do comando keytool no passo 3
System.setProperty("javax.net.ssl.trustStorePassword", "nfe123");//Aqui a senha deste keystore
      
String retornoProc = null;
NfeStatusServico servico = new NfeStatusServicoLocator();
try {  
	NfeStatusServicoSoap nfeStatus = servico.getNfeStatusServicoSoap();
	retornoProc = nfeStatus.nfeStatusServicoNF(nfeCabecMsg, nfeDadosMsg);// O retorno deve ser um XML com o status do serviço  
} catch (Throwable e1) {  
	e1.printStackTrace();
} 

Será que eu estou esquecendo de setar alguma coisa, ou estou setando alguma coisa errada?

Olá galera, já consegui resolver essa parte, agora eu não consigo assinar.

Se alguem já conseguiu assinar com A3 dá uma ajuda ai.

Abraço.

Seguinte moçada, consegui resolver, para assinar a conexão deve se usar as linhas abaixo.

Provider p = new sun.security.pkcs11.SunPKCS11("c:/sistema/token.cfg");
		Security.addProvider(p);
				
		KeyStore ks = null;
		try {
			ks = KeyStore.getInstance("PKCS11");
		} catch (KeyStoreException e2) {
			// TODO Auto-generated catch block
			e2.printStackTrace();
		}
		try {
			ks.load(null, "safeweb".toCharArray());			
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (CertificateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		Enumeration aliasesEnum = null;
		try {
			aliasesEnum = ks.aliases();
		} catch (KeyStoreException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		while (aliasesEnum.hasMoreElements()) {
		   String alias = (String)aliasesEnum.nextElement();
		   System.out.println("Alias: " + alias);
		   X509Certificate cert = null;
		   try {
			   cert = (X509Certificate) ks.getCertificate(alias);			   
			   certificadoVector.add(cert);
		   } catch (KeyStoreException e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   }
		   
		   //System.out.println("Certificate: " + cert);
		   PrivateKey privateKey = null;
		   try {
			   privateKey = (PrivateKey) ks.getKey(alias, null);
		   } catch (UnrecoverableKeyException e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   } catch (KeyStoreException e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   } catch (NoSuchAlgorithmException e) {
			   // TODO Auto-generated catch block
			   e.printStackTrace();
		   }
		   //System.out.println("Private key: " + privateKey);
		}
		
		System.setProperty("javax.net.ssl.keyStoreType", ks.getType());   
        System.setProperty("javax.net.ssl.keyStore", "NONE"); 
        //Essa informação vc tem que pegar do cartão, senão da erro e não abre.
        System.setProperty("javax.net.ssl.keyStoreProvider", "SunPKCS11-Safeweb");   
        System.setProperty("javax.net.ssl.keyStorePassword", "safeweb");   
		
        System.setProperty("javax.net.ssl.trustStoreType", "JKS");
        System.setProperty("javax.net.ssl.trustStore", "C:/sistema/servidor.keystore");//Aqui vem o arquivo criado através do comando keytool no passo 3
        System.setProperty("javax.net.ssl.trustStorePassword", "n1f2e3");//Aqui a senha deste keystore

Ai pra assinar o arquivo usando certificado A1 esse abaixo

try {
			String tag = "infNFe";
			String caminhoCertificado = Utilitario.caminhoCertCli();
			String senha = Utilitario.senhaCertCli();
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setNamespaceAware(false);
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document docs = builder.parse(new File(caminhoNfe));
			
			NodeList elements = docs.getElementsByTagName(tag);
			Element el = (Element) elements.item(0);
			String id = el.getAttribute("Id");
			
			NodeList elements2 = docs.getElementsByTagName("nNF");
			Element elIdNfe = (Element) elements2.item(0);
			idNfeS = elIdNfe.getTextContent();
			
			String providerName = System.getProperty(PROVIDER_NAME, PROVIDER_CLASS_NAME);
			XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());		

		                ArrayList transformList = new ArrayList(); 
			TransformParameterSpec tps = null; 
			Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,tps); 
			Transform c14NTransform = fac.newTransform(C14N_TRANSFORM_METHOD, tps); 
			transformList.add(envelopedTransform); 
			transformList.add(c14NTransform); 

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

			KeyStore ks = KeyStore.getInstance(Utilitario.tipoCertCli());
			ks.load(new FileInputStream(caminhoCertificado), senha.toCharArray()); 
			
			KeyStore.PrivateKeyEntry keyEntry = (KeyStore.PrivateKeyEntry) ks.getEntry(alias, new KeyStore.PasswordProtection(senha.toCharArray())); 
			X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
			
			KeyInfoFactory kif = fac.getKeyInfoFactory(); 
			List x509Content = new ArrayList(); 
			
			x509Content.add(cert);
			X509Data xd = kif.newX509Data(x509Content); 
			KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); 

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
			dbf.setNamespaceAware(true); 
			Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(caminhoNfe)); 

			DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement().getElementsByTagName("NFe").item(0));
			
			XMLSignature signature = fac.newXMLSignature(si, ki); 
			signature.sign(dsc); 

			doc.setXmlStandalone(true);
			
			NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); 
			
			if (nl.getLength() == 0) { 
				throw new Exception("Elemento assinatura não encontrado"); 
			} 
			DOMValidateContext valContext = new DOMValidateContext( new X509KeySelector(ks), nl.item(0)); 
			XMLSignature signatures = fac.unmarshalXMLSignature(valContext); 
			boolean coreValidity = signatures.validate(valContext); 
			if (coreValidity == false) { 
				System.err.println("Falha na Assinatura!");			
				log.info("Falha na Assinatura da NF-e " + idNfeS);				
			} else { 
				System.out.println("Assinatura Correta!");				
				log.info("Assinatura  da NF-e " + idNfeS + " correta.");
			} 
						
			OutputFormat format    = new OutputFormat(doc); 
			StringWriter stringOut = new StringWriter ();    
	    	XMLSerializer serial   = new XMLSerializer (stringOut,format);
		    serial.serialize(doc);

Ai pra assinar o arquivo usando certificado A3 esse abaixo

try {
			String tag = "infNFe";
			
			DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
			factory.setNamespaceAware(false);
			DocumentBuilder builder = factory.newDocumentBuilder();
			Document docs = builder.parse(new File(caminhoNfe));
			
			NodeList elements = docs.getElementsByTagName(tag);
			Element el = (Element) elements.item(0);
			String id = el.getAttribute("Id");
			
			NodeList elements2 = docs.getElementsByTagName("nNF");
			Element elIdNfe = (Element) elements2.item(0);
			idNfeS = elIdNfe.getTextContent();
			
		                String providerName = System.getProperty(PROVIDER_NAME, PROVIDER_CLASS_NAME);
			XMLSignatureFactory fac = XMLSignatureFactory.getInstance("DOM", (Provider) Class.forName(providerName).newInstance());		

			ArrayList transformList = new ArrayList(); 
			TransformParameterSpec tps = null; 
			Transform envelopedTransform = fac.newTransform(Transform.ENVELOPED,tps); 
			Transform c14NTransform = fac.newTransform(C14N_TRANSFORM_METHOD, tps); 
			transformList.add(envelopedTransform); 
			transformList.add(c14NTransform); 

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

			Provider p = new sun.security.pkcs11.SunPKCS11("c:/sistema/token.cfg");
			Security.addProvider(p);
			
			X509Certificate certificado = null;
			KeyStore ks = null;
			try {
				ks = KeyStore.getInstance("PKCS11");
			} catch (KeyStoreException e2) {
				// TODO Auto-generated catch block
				e2.printStackTrace();
			}
			log.info("entrou 6");
			try {
				ks.load(null, "safeweb".toCharArray());
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			} catch (CertificateException e) {
				e.printStackTrace();
			} catch (IOException e) {
				e.printStackTrace();
			}
			
			Enumeration aliasesEnum = ks.aliases(); 
			String alias = ""; 
			while (aliasesEnum.hasMoreElements()) { 
				alias = (String) aliasesEnum.nextElement(); 
				System.out.println("alias " + alias);
				if (ks.isKeyEntry(alias)) {
					certificado = (X509Certificate) ks.getCertificate(alias);
					break; 
				} 
			} 

			
			KeyStore.PrivateKeyEntry keyEntry = (PrivateKeyEntry) ks.getEntry("nome do alias do seu certificado", new KeyStore.PasswordProtection("safeweb".toCharArray()));
			X509Certificate cert = (X509Certificate) keyEntry.getCertificate();
			
			KeyInfoFactory kif = fac.getKeyInfoFactory(); 
			List x509Content = new ArrayList(); 
			
			x509Content.add(cert);
			X509Data xd = kif.newX509Data(x509Content); 
			KeyInfo ki = kif.newKeyInfo(Collections.singletonList(xd)); 

			DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance(); 
			dbf.setNamespaceAware(true); 
			Document doc = dbf.newDocumentBuilder().parse(new FileInputStream(caminhoNfe)); 

			DOMSignContext dsc = new DOMSignContext(keyEntry.getPrivateKey(), doc.getDocumentElement().getElementsByTagName("NFe").item(0));
			
			XMLSignature signature = fac.newXMLSignature(si, ki); 
			signature.sign(dsc); 

			doc.setXmlStandalone(true);
			
			NodeList nl = doc.getElementsByTagNameNS(XMLSignature.XMLNS, "Signature"); 
			
			if (nl.getLength() == 0) { 
				throw new Exception("Elemento assinatura não encontrado"); 
			} 
			DOMValidateContext valContext = new DOMValidateContext( new X509KeySelector(ks), nl.item(0)); 
			XMLSignature signatures = fac.unmarshalXMLSignature(valContext); 
			boolean coreValidity = signatures.validate(valContext); 
			if (coreValidity == false) { 
				System.err.println("Falha na Assinatura!");			
				log.info("Falha na Assinatura da NF-e " + idNfeS);				
			} else { 
				System.out.println("Assinatura Correta!");				
				log.info("Assinatura  da NF-e " + idNfeS + " correta.");
			} 
						
			OutputFormat format    = new OutputFormat(doc); 
			StringWriter stringOut = new StringWriter ();    
	    	XMLSerializer serial   = new XMLSerializer (stringOut,format);
		    serial.serialize(doc);

Ta tudo ai, depois vou fazer um tuto pra acabar com o sofrimento geral da nação javanesa!!

abraço.