pedruhenrik:
Olá!
fiz o seguinte código q funciona com o meu token, "eToken Pro 32k" da marca "Aladdin"
import java.io.IOException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.Provider;
import java.security.Security;
import java.security.cert.CertificateException;
import java.util.Enumeration;
public class TokenA3 {
public static void main(String[] args) throws KeyStoreException,
NoSuchAlgorithmException, CertificateException, IOException {
Provider p = new sun.security.pkcs11.SunPKCS11("Diretorio .cfg"); // exemplo "C:\\NFE\\token.cfg"
try {
Security.addProvider(p);
} catch (Exception e) {
e.printStackTrace();
throw new KeyStoreException(
"Não foi possivel inicializar a API Sun PKCS#11 security. Motivo: "
+ e.getCause().getMessage());
}
char[] pin = "senha".toCharArray();// senha do certificado a3
Security.getProviders();
KeyStore keyStore = KeyStore.getInstance("PKCS11", p);
keyStore.load(null, pin);
System.out.println("KeyStore: " + keyStore);
Enumeration aliasesEnum = keyStore.aliases();
String alias = "";
while (aliasesEnum.hasMoreElements()) {
alias = (String) aliasesEnum.nextElement();
if (keyStore.isKeyEntry(alias)) {
System.out.println("Alias Cert: " + alias);
break;
}
}
}
}
Meu arquivo token.cfg:
name = eToken
library = C:\WINDOWS\system32\eTpkcs11.dll
tentem utilizar este código com os drivers do token instalados corretamente e o arquivo .cfg apontado para a .dll do token.
Para ver se o token esta instalado corretamente tente acessar a seguinte url: [url]https://nfe.sefaz.am.gov.br/ws/services/NfeRecepcao[/url] no IE, uma "janelinha" deve aparecer, exibir o certificado A3 e após escolhido solicitara a senha do certificado. Após a inserção da senha uma tela de "boas vindas" do AXIS será exibida.
Esse procedimento descarta problemas de instalação do token.
O que acontece?
Qual a versão do jre utilizada? 1.6.0_18 ??
espero ter ajudado ^^
Amigo saberia me dizer a razão de estar recebendo essa Exception para um certificado A3 enquanto que para o outro não estou tendo problema algum, todas as cadeias foram importadas e continuo recebendo esse erro 403, estou ficando maluco com isso já, vi que você entende de A3 e estou te perguntando.
Quando tento acessar o status do serviço, e antes registro as propriedades do certificado, sempre recebo esse 403.
Código que eu uso:
String arquivoConfigCertificado = NFe.CAMINHO_ARQUIVO_CONFIG_TOCKPRINT;
String senhaCertificado = NFe.SENHA_CERTIFICADO_TOCKPRINT;
String provedorCertificado = "SunPKCS11-eToken-Tockprint";
Provider p = new sun.security.pkcs11.SunPKCS11(arquivoConfigCertificado);
Security.addProvider(p);
KeyStore ks;
try {
ks = KeyStore.getInstance("PKCS11", p); //
ks.load(null, senhaCertificado.toCharArray());
} catch (KeyStoreException ex) {
Logger.getLogger(EmissorUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
Logger.getLogger(EmissorUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(EmissorUI.class.getName()).log(Level.SEVERE, null, ex);
} catch (CertificateException ex) {
Logger.getLogger(EmissorUI.class.getName()).log(Level.SEVERE, null, ex);
}
// para resolver: HelloRequest followed by an unexpected handshake message
System.setProperty("sun.security.ssl.allowUnsafeRenegotiation", "true");
System.setProperty("java.protocol.handler.pkgs", "com.sun.net.ssl.internal.www.protocol");
System.setProperty("javax.net.ssl.keyStore", "NONE");
System.setProperty("javax.net.ssl.keyStoreType", "PKCS11");
System.setProperty("javax.net.ssl.keyStorePassword", senhaCertificado);
System.setProperty("javax.net.ssl.keyStoreProvider", provedorCertificado);
String keystoreSEFAZ = Global.ARQUIVO_KS_SEFAZ_HOMOLOGACAO;
//System.out.println("Keysore SEFAZ: " + keystoreSEFAZ);
System.setProperty("javax.net.ssl.trustStoreType", "JKS");
System.setProperty("javax.net.ssl.trustStore", keystoreSEFAZ);
System.setProperty("javax.net.ssl.trustStorePassword", Global.SENHA_KEYSTORE_SEFAZ);
String nfeDadosMsg = ""
+ "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"
+ "<consStatServ " + " versao=\"" + NFe.VERSAO_LEIAUTE_NFE + "\"" + " xmlns=\"http://www.portalfiscal.inf.br/nfe\">"
+ " <tpAmb>2</tpAmb>"
+ " <cUF>35</cUF>"
+ " <xServ>STATUS</xServ>"
+ "</consStatServ>";
TRetConsStatServ retorno = null;
try {
String urlStatus = "https://homologacao.nfe.fazenda.sp.gov.br/nfeweb/services/NfeStatusServico2.asmx";
//System.out.println("Url consulta status: " + urlStatus + " - ambiente: " + Global.TIPO_AMBIENTE_NFe);
NfeStatusServico2Stub stub = new NfeStatusServico2Stub(urlStatus);
NfeCabecMsgE nfeCabecMsg = new NfeCabecMsgE();
NfeCabecMsg param = new NfeCabecMsg();
param.setCUF("35");
param.setVersaoDados(NFe.VERSAO_LEIAUTE_NFE);
nfeCabecMsg.setNfeCabecMsg(param);
OMElement ome = AXIOMUtil.stringToOM(nfeDadosMsg);
NfeDadosMsg nf = new NfeDadosMsg();
nf.setExtraElement(ome);
NfeStatusServicoNF2Result resp = stub.nfeStatusServicoNF2(nf, nfeCabecMsg);
String strXmlRetorno = resp.getExtraElement().toString();
//System.out.println("retorno: \n" + strXmlRetorno);
strXmlRetorno = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" + strXmlRetorno;
//System.out.println("retorno: \n" + strXmlRetorno);
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setNamespaceAware(true);
//Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(strXmlRetorno.getBytes()));
Document doc = factory.newDocumentBuilder().parse(new ByteArrayInputStream(strXmlRetorno.trim().getBytes("UTF8")));
Element root = doc.getDocumentElement();
// Para colocar o xml de retorno no objeto TRetConsStatServ
JAXBContext context = JAXBContext.newInstance(TRetConsStatServ.class);
Unmarshaller unmarshaller = context.createUnmarshaller();
retorno = unmarshaller.unmarshal(root, TRetConsStatServ.class).getValue();
} catch (AxisFault ex) {
retorno = new TRetConsStatServ();
retorno.setCStat("999");
retorno.setXMotivo(ex.getMessage());
Logger.getLogger(NFe.class.getName()).log(Level.SEVERE, null, ex);
} catch (XMLStreamException ex) {
retorno = new TRetConsStatServ();
retorno.setCStat("999");
retorno.setXMotivo(ex.getMessage());
Logger.getLogger(NFe.class.getName()).log(Level.SEVERE, null, ex);
} catch (IOException ex) {
retorno = new TRetConsStatServ();
retorno.setCStat("999");
retorno.setXMotivo(ex.getMessage());
//Lib.Warning(null, "Verificando status do serviço no SEFAZ", ex.getMessage(), 0);
Logger.getLogger(NFe.class.getName()).log(Level.SEVERE, null, ex);
} catch (ParserConfigurationException ex) {
retorno = new TRetConsStatServ();
retorno.setCStat("999");
retorno.setXMotivo(ex.getMessage());
//Lib.Warning(null, "Verificando status do serviço no SEFAZ", ex.getMessage(), 0);
Logger.getLogger(NFe.class.getName()).log(Level.SEVERE, null, ex);
} catch (SAXException ex) {
retorno = new TRetConsStatServ();
retorno.setCStat("999");
retorno.setXMotivo(ex.getMessage());
//Lib.Warning(null, "Verificando status do serviço no SEFAZ", ex.getMessage(), 0);
Logger.getLogger(NFe.class.getName()).log(Level.SEVERE, null, ex);
} catch (JAXBException ex) {
retorno = new TRetConsStatServ();
retorno.setCStat("999");
retorno.setXMotivo(ex.getMessage());
//Lib.Warning(null, "Verificando status do serviço no SEFAZ", ex.getMessage(), 0);
Logger.getLogger(NFe.class.getName()).log(Level.SEVERE, null, ex);
} catch (java.security.ProviderException ex) {
retorno = new TRetConsStatServ();
retorno.setCStat("999");
retorno.setXMotivo(ex.getMessage());
Logger.getLogger(NFe.class.getName()).log(Level.SEVERE, null, ex);
}
Exception no Axis2:
org.apache.axis2.AxisFault: Transport error: 403 Error: Forbidden
at org.apache.axis2.transport.http.HTTPSender.handleResponse(HTTPSender.java:310)
at org.apache.axis2.transport.http.HTTPSender.sendViaPost(HTTPSender.java:200)
at org.apache.axis2.transport.http.HTTPSender.send(HTTPSender.java:76)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.writeMessageWithCommons(CommonsHTTPTransportSender.java:400)
at org.apache.axis2.transport.http.CommonsHTTPTransportSender.invoke(CommonsHTTPTransportSender.java:225)
at org.apache.axis2.engine.AxisEngine.send(AxisEngine.java:435)
at org.apache.axis2.description.OutInAxisOperationClient.send(OutInAxisOperation.java:402)
at org.apache.axis2.description.OutInAxisOperationClient.executeImpl(OutInAxisOperation.java:229)
at org.apache.axis2.client.OperationClient.execute(OperationClient.java:165)
at emissor.ws.h.status.NfeStatusServico2Stub.nfeStatusServicoNF2(NfeStatusServico2Stub.java:173)
at emissor.ui.EmissorUI$2.run(EmissorUI.java:193)
O detalhe é que o certificado está OK porque eu consigo enviar uma nota com o Emissor da NFe (aquele de testes), o que estou fazendo de errado se com o outro tudo funciona?