Como pegar a data de validade de um certificado digital usando uma classe java

2 respostas
P

Boa tarde!

Estou com o seguinte problema:

Eu tenho uma classe que basta eu apontar o caminho do certificado digital e a senha que ela já cria o certificado digital (JKS) em memória e já faz a comunicação com a SEFAZ, até aí tudo bem. Mas eu precisava extrair a data de validade deste certificado para avisar ao usuário quando o vencimento se aproxima.

Alguém já fez ou tem alguma dica?

Agradeço desde já…

2 Respostas

E

O método a ser usado é “getNotAfter”.
http://java.sun.com/javase/6/docs/api/java/security/cert/X509Certificate.html#getNotAfter()

Acredito que você saiba, a partir do tal arquivo com o certificado, criar um objeto java.security.cert.X509Certificate.

Se não souber fazer isso, e se você tiver o arquivo com o certificado em formato X.509 (usualmente é um arquivo com extensão .cer) , você pode procurar por algum exemplo que envolva a classe java.security.cert.CertificateFactory. Ela tem um método que, a partir de um arquivo (na verdade uma InputStream), gera um objeto que implementa java.security.cert.Certificate, e que normalmente é um X509Certificate.

P
Bom dia. Obrigado pela dica entanglement, porém eu já tentei fazer estes passos para tentar resgatar a data de validade do certificado, porém, acho que devido a minha inexperiência em certificados digitais eu não consegui. Vou postar minha classe talvez assim seja mais fácil de alguém saber
package br.com.sensatta.util;



import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.security.KeyManagementException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.Security;
import java.security.cert.CertificateException;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.util.Date;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLException;
import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import javax.net.ssl.X509TrustManager;

/**
 * @taken from the InstallCert program
 * @(#)InstallCert.java	1.1 06/10/09
 *
 * Copyright 2006 Sun Microsystems, Inc. All rights reserved.
 * Use is subject to license terms.
 *
 * @modified with Novell's sample TLSTrustManager code;
 * @modifies adequação de padrão de projeto da VJBrasil
 *
 * @author: Ng Hian James (T-est Pte Ltd), July 2007;
 * 
 * @author Valentin, Michel (VJ Brasil Ltda), maio 2009;
 *
 */

public class ConnectionSSL {
	private static final char[] HEXDIGITS = "0123456789abcdef".toCharArray();
	private int port = 443;
	private String host;
	private char[] passphrase = "changeit".toCharArray();
	private Date dataValidade;
	
	public Date getDataValidade() {
		return dataValidade;
	}
	
	/**
	 * Para certificado do tipo arquivo digital.
	 * @param propertie
	 * @throws IOException
	 * @throws CertificateException 
	 * @throws KeyStoreException 
	 * @throws NoSuchAlgorithmException 
	 * @throws KeyManagementException 
	 */
	public void loadCertificateConnection8(String cer, String senha,  String uri) throws IOException, KeyManagementException, NoSuchAlgorithmException, KeyStoreException, CertificateException {
		this.acrescentaCacerts(uri);
		File file = this.getFileCacerts();
		System.setProperty("java.protocol.handler.pkgs","com.sun.net.ssl.internal.www.protocol");
		Security.addProvider(new com.sun.net.ssl.internal.ssl.Provider());
		System.setProperty("javax.net.ssl.keyStoreType", "PKCS12");
		System.setProperty("javax.net.ssl.keyStore", cer);
		System.setProperty("javax.net.ssl.keyStorePassword", senha);
		System.setProperty("javax.net.ssl.trustStoreType", "JKS");
		System.setProperty("javax.net.ssl.trustStore", file.getAbsolutePath());
		
		
//		String host = "";
//		if(host != null && !host.equals("")){
//			this.setProxyByJVM(propertie);
//		}
	}
	
//	public void setProxyByJVM(String port, String user, String pass, String host) throws IOException{
//		 System.getProperties().put("http.proxyHost", host);
//		 
//		          System.getProperties().put("http.proxyPort", port);  
//		          System.getProperties().put("http.proxyUser", user);  
//		          System.getProperties().put("http.proxyPassword", pass);  
//		   
//		          System.getProperties().put("https.proxyHost", host);  
//		          System.getProperties().put("https.proxyPort", port);  
//		          System.getProperties().put("https.proxyUser", Propertie.getUserProxy(propertie));  
//		          System.getProperties().put("https.proxyPassword", Propertie.getPasswordProxy(propertie));  
//		            
//		          System.getProperties().put("https.proxySet", "true");  
//		          System.getProperties().put("http.proxySet", "true");  
//		            
//	}
	
	
	
	
	/**
	 * Metodo que acrescenta o certificado ao cacerts caso haja exception de SSLException
	 * METODO BASEADO NA CLASSE DE TRUSTCACERTS DA SUN.
	 * @param uri
	 * @throws IOException
	 * @throws NoSuchAlgorithmException
	 * @throws KeyStoreException
	 * @throws CertificateException
	 * @throws KeyManagementException
	 */
	public  void acrescentaCacerts( String uri)throws IOException, NoSuchAlgorithmException, KeyStoreException, CertificateException, KeyManagementException {
		
		this.loadHostCert(uri);
		File file  = this.getFileCacerts();
		KeyStore ks = this.getKeystore(file);
		SSLContext context = SSLContext.getInstance("TLS");
		TrustManagerFactory tmf = TrustManagerFactory
				.getInstance(TrustManagerFactory.getDefaultAlgorithm());
		tmf.init(ks);
		X509TrustManager defaultTrustManager = (X509TrustManager) tmf
				.getTrustManagers()[0];
		
		SavingTrustManager tm = new SavingTrustManager(defaultTrustManager);
		context.init(null, new TrustManager[] { tm }, null);
		SSLSocketFactory factory = context.getSocketFactory();

		SSLSocket socket = (SSLSocket) factory.createSocket(host, port);
		socket.setSoTimeout(10000);
	    		
		
		//Se nao tiver no cacerts acrescenta
		try {
			socket.startHandshake();
		}catch (SSLException e) {
			this.addCertificadosServer(tm, file, ks);
		}		
	}
	
	/**
	 * Metodo que acrescenta o trust no cacerts do java
	 * METODO BASEADO NA CLASSE DE TRUSTCACERTS DA SUN.
	 * @param tm
	 * @param file
	 * @param ks
	 * @throws KeyStoreException
	 * @throws NoSuchAlgorithmException
	 * @throws CertificateException
	 * @throws IOException
	 */
	private void addCertificadosServer(SavingTrustManager tm, File file, KeyStore ks ) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{

		X509Certificate[] chain = tm.chain;
		if (chain == null) {
			System.out.println("Could not obtain server certificate chain");
			return;
		}
				
		BufferedReader reader = new BufferedReader(new InputStreamReader(
				System.in));
		MessageDigest sha1 = MessageDigest.getInstance("SHA1");
		MessageDigest md5 = MessageDigest.getInstance("MD5");
		X509Certificate cert = null;
		
		String alias = null;
		for (int i = 0; i < chain.length; i++) {
			cert = chain[i];
			alias = host + "" + (i + 7);
			ks.setCertificateEntry(alias, cert);
			dataValidade= chain[i].getNotAfter();
			OutputStream out = new FileOutputStream(file);
			ks.store(out, passphrase);
			out.close();
		}
		OutputStream out = new FileOutputStream(file);
		
		ks.store(out, passphrase);
		out.close();

	}
	
	/**
	 * Carrega o host com a url de acesso.
	 * @param uriService
	 */
	private void loadHostCert(String uriService){
		String h = null;
		String[] p = uriService.split("https://");
		if(p.length>1){
			p = p[1].split("/");
			if(p.length>0){
				h = p[0];
			}
		}
		host = h;
	}
	
	/**
	 * Carrega o keystore do java
	 * @param file
	 * @return
	 * @throws KeyStoreException
	 * @throws NoSuchAlgorithmException
	 * @throws CertificateException
	 * @throws IOException
	 */
	private KeyStore getKeystore(File file) throws KeyStoreException, NoSuchAlgorithmException, CertificateException, IOException{
		InputStream in = new FileInputStream(file);
		KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
		ks.load(in, passphrase);
		in.close();
		return ks;
	}
	
	/**
	 * Transforma Exa em string
	 * @param bytes
	 * @return
	 */
	private static String toHexString(byte[] bytes) {
		StringBuilder sb = new StringBuilder(bytes.length * 3);
		for (int b : bytes) {
			b &= 0xff;
			sb.append(HEXDIGITS[b >> 4]);
			sb.append(HEXDIGITS[b & 15]);
			sb.append(' ');
		}
		return sb.toString();
	}
	
	/**
	 * Retorna o cacerts do java windows/linux.
	 * 
	 * @param file
	 */
	private File getFileCacerts(){
		//Obtem o separador padrao do sistema operacional
		char SEP = File.separatorChar;
		//File do certificado
		File file;
		//Carrega o diretorio do jre e acrescenta o local onde esta o security do java
		File dir = new File(System.getProperty("java.home")+ SEP + "lib"
				+ SEP + "security");
		//Acrescenta-se o nome padrao para linux
		file = new File(dir, "jssecacerts");
		//Testa se o diretorio refere-se ao linux se for nao coloca-se o padrao windows
		if(file.exists() == false){
			file = new File(dir, "cacerts");
		}
		//retorna o file referente ao arquivo de trustcacerts.
		return file;
	}
	
	
	
	/**
	 * Classe de auxilio ao gerenciamento de certificados
	 * @author Michel
	 *
	 */
	private static class SavingTrustManager implements X509TrustManager {

		private final X509TrustManager tm;
		private X509Certificate[] chain;
	    
		SavingTrustManager(X509TrustManager tm) {
			this.tm = tm;
			}
               
		
		public X509Certificate[] getAcceptedIssuers() {
			throw new UnsupportedOperationException();
		}

		public void checkClientTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			throw new UnsupportedOperationException();
		}

		public void checkServerTrusted(X509Certificate[] chain, String authType)
				throws CertificateException {
			this.chain = chain;
			tm.checkServerTrusted(chain, authType);
			
		}
	}

		  
	public void setDataValidade(Date dataValidade) {
		this.dataValidade = dataValidade;
	}
	

}

Desde já agradeço

Criado 24 de março de 2010
Ultima resposta 25 de mar. de 2010
Respostas 2
Participantes 2