Utilitário para geração de TrustStore (JKS) – Java

Olá Pessoal,

Desenvolvi um utilitário que transforma um arquivo zip, contendo “n” certificados de Autoridades Certificadoras para um arquivo JKS.

Para referência segue um link que contém todas as CA’s brasileiras:

http://acraiz.icpbrasil.gov.br/credenciadas/CertificadosAC-ICP-Brasil/ACcompactado.zip

Como seria o processo normal ?

1 – Java Keytool – http://download.oracle.com/javase/6/docs/technotes/tools/windows/keytool.html
É um software que acompanha a máquina virtual Java (jdk), utilizado para diversas finalidades com relação à segurança de aplicações e pode ser usado para gerar o pacote JKS.
Seguem dois comandos exemplo para se trabalhar com arquivos JKS de truststore:

1. Listando todos os certificados contidos em um arquivo JKS:

keytool –list –v –keystore C:\meukeystore.jks

2. Importando um certificado de uma AC para dentro de um JKS pré-existente

keytool –import –trustcacerts –file C:\certificadoAC.cer –alias apelidoentrada –keystore C:\meutruststore.jks

Observação: Caso não exista um jks no diretório especificado em -keystore, será criado um automaticamente.
O arquivo ACcompactado.zip especificado na URL anteriormente, possui atualmente 84 certificados, portanto, deve-se executar o comando (2), 84 vezes, alterando o -alias e o –file. Por ser esta uma forma muito trabalhosa de se gerar um arquivo Trusted JKS, foi criado um utilitário que auxiliará nesta etapa, apresentado no próximo capítulo.

2 – Usando o utilitário – utilitarioTrustJKS.jar
O utilitário desenvolvido basicamente recebe como entrada um arquivo zip com todos os certificados desejados e gera um arquivo trust.jks.
Parâmetros de Entrada:
1 – caminhoZip – Diretório do arquivo zip que contém todos os certificados das AC’s
2 – caminhoSaida – Diretório de saída, onde será gerado o truststore.jks
3 – senhaKestore – Senha do arquivo TrustStore JKS
4 – incluirExpirados (opcional) – valor default => false) – Possui os valores true ou false. Informa se certificados expirados ou não válidos ainda deverão ser incluídos no arquivo JKS gerado.

Exemplo de utilização:

java -jar utilitarioTrustJKS.jar C:\ACcompactado.zip C:\truststore.jks 123456789 true

Link para Download do arquivo Jar:
http://arquivos.victorjabur.com/java/seguranca/utilitarioTrustJKS.jar

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.KeyStore;
import java.security.cert.CertificateExpiredException;
import java.security.cert.CertificateFactory;
import java.security.cert.CertificateNotYetValidException;
import java.security.cert.X509Certificate;
import java.util.LinkedList;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import com.sun.xml.internal.messaging.saaj.util.ByteInputStream;

public class Main {

	private String caminhoZIP = "C:\\ACcompactado.zip";
	private String caminhoSaida = "C:\\truststore.jks";
	private String senhaKeystore = "123456789";
	private Boolean incluirExpirados = false;

	public static void main(String[] args) throws Exception {
		Main main = new Main();
		main.validarParametrosEntrada(args);
		List<X509Certificate> listaCertificadosValidos = main.getListaCertificadosValidos();
		main.gerarJKS(listaCertificadosValidos);
		System.out.println("Arquivo JKS gerado com sucesso - " + listaCertificadosValidos.size() + " certificados incluidos");
	}

	public void validarParametrosEntrada(String[] args){
		if(args.length < 3){
			throw new RuntimeException("O numero minimo de parametros = 3. caminhoZip caminhoSaida senhaKeystore e incluirExpirados (Opcional) ");
		}else{
			String caminhoZip = args[0];
			validacaoLeituraArquivo(new File(caminhoZip));
			this.caminhoZIP = caminhoZip;
			String caminhoSaida = args[1];
			this.caminhoSaida = caminhoSaida;
			String senhaKeystore = args[2];
			this.senhaKeystore = senhaKeystore;
			if(args.length >= 4){
				String incluirExpirados = args[3];
				if(incluirExpirados.equals("true") || incluirExpirados.equals("false")){
					this.incluirExpirados = Boolean.valueOf(incluirExpirados);
				}else{
					throw new RuntimeException("O parametro incluirExpirados (4) deve ser true ou false");
				}
			}
		}
	}
	
	public List<X509Certificate> getListaCertificadosValidos() {
		File arquivoZipEntrada = new File(this.caminhoZIP);
		validacaoLeituraArquivo(arquivoZipEntrada);
		List<X509Certificate> x509CertificateList = new LinkedList<X509Certificate>();
		try {
			InputStream in = new FileInputStream(arquivoZipEntrada);
			ZipInputStream zipInputStream = new ZipInputStream(in);

			ZipEntry zipentry = zipInputStream.getNextEntry();
			while (zipentry != null) {
				byte[] buffer = new byte[(int) zipentry.getSize()];
				int offset = 0;
				int numRead = 0;
				while (offset < buffer.length && (numRead = zipInputStream.read(buffer, offset, buffer.length - offset)) >= 0) {
					offset += numRead;
				}
				InputStream bis = new ByteInputStream(buffer, 0, buffer.length);
				CertificateFactory cf = CertificateFactory.getInstance("X.509");
				X509Certificate cert = (X509Certificate) cf.generateCertificate(bis);
				try {
					cert.checkValidity();
					x509CertificateList.add(cert);
				} catch (CertificateExpiredException e) {
					if(this.incluirExpirados){
						x509CertificateList.add(cert);
						System.out.println("Certificado Expirado - " + zipentry.getName());
					}else{
						System.out.println("Certificado Expirado - " + zipentry.getName() + " - nao sera adicionado no JKS");
					}
				} catch (CertificateNotYetValidException e) {
					if(this.incluirExpirados){
						x509CertificateList.add(cert);
						System.out.println("Certificado não válido ainda - " + zipentry.getName());
					}else{
						System.out.println("Certificado não válido ainda - " + zipentry.getName() + " - nao sera adicionado no JKS");
					}
				}
				zipInputStream.closeEntry();
				zipentry = zipInputStream.getNextEntry();
			}
			zipInputStream.close();
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		return x509CertificateList;
	}

	public OutputStream gerarJKS(List<X509Certificate> listaCertificados){
		OutputStream out = null;
		try {
			KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
			keystore.load(null, null);
			int indice = 0;
			for (X509Certificate cert : listaCertificados) {
				keystore.setCertificateEntry("ac_" + indice, cert);
				indice++;
			}
			File jks = new File(this.caminhoSaida);
			String diretorioDestino = jks.getParent();
			new File(diretorioDestino).mkdirs();
			out = new FileOutputStream(this.caminhoSaida);
			keystore.store(out, this.senhaKeystore.toCharArray());
			out.close();
			out.flush();
		} catch (Exception e) {
			throw new RuntimeException("Erro ao gerar o arquivo de Keystore - " + e.getCause() + " - " + e.getMessage());
		}
		return out;
	}
	
	public void validacaoLeituraArquivo(File arquivo) {
		if (!arquivo.exists()) {
			throw new RuntimeException("Arquivo Inexistente - " + arquivo.getAbsolutePath());
		}
		if (!arquivo.canRead()) {
			throw new RuntimeException("Sem permissão de Leitura do Arquivo - " + arquivo.getAbsolutePath());
		}
	}
}

Abraços,
Victor Jabur

How to access server MBean properties at weblogic 11g using Java – JMX

Hi,

If you want to get any property of Admin or Managed Server (Weblogic) using Java, then this post will help you.

The Oracle Enterprise Manager have a useful tool for explore MBean (System MBean Browser).

As you can see in the picture bellow:

Do you can to capture any server property desired with these java code:

1 – Reading a property if the application is deployed at server (local connection)

import javax.management.MBeanServer;
import javax.management.ObjectName;
import javax.naming.InitialContext;

String serverName = System.getProperty("weblogic.Name");
InitialContext ctx = new InitialContext();
MBeanServer server = (MBeanServer)ctx.lookup("java:comp/env/jmx/runtime");
ObjectName objName = new ObjectName("com.bea:Name=" + serverName + ",Type=Server");
String pathJKS = (String) server.getAttribute(objName, "CustomTrustKeyStoreFileName");

2 – Reading a property if the application is remote (remote connection)

import java.util.Hashtable;
import javax.management.ObjectName;
import javax.management.remote.JMXConnector;
import javax.management.remote.JMXConnectorFactory;
import javax.management.remote.JMXServiceURL;
import javax.naming.Context;

  public static void main(String [] args) throws Exception{
    String serverName = "AdminServer";
    String hostName = "192.168.1.192";
    String username = "weblogic";
    String password = "welcome1";
    int port = 10000;
    String protocol = "t3";
    String jndiroot = "/jndi/";
    String mserver = "weblogic.management.mbeanservers.domainruntime";
    JMXServiceURL serviceURL = new JMXServiceURL(protocol, hostName, port, jndiroot + mserver);
    Hashtable h = new Hashtable();
    h.put(Context.SECURITY_PRINCIPAL, username);
    h.put(Context.SECURITY_CREDENTIALS, password);
    h.put(JMXConnectorFactory.PROTOCOL_PROVIDER_PACKAGES, "weblogic.management.remote");
    JMXConnector connector = JMXConnectorFactory.connect(serviceURL, h);
    ObjectName objName = new ObjectName("com.bea:Name=" + serverName + ",Type=Server");
    String pathJKS = (String) connector.getMBeanServerConnection().getAttribute(objName, "CustomTrustKeyStoreFileName");
    System.out.println(pathJKS);
  }

In the cases above, i’m reading a property that is called “CustomTrustKeyStoreFileName”, that’s a string path of the Trusted Keystore. But many and many properties could be read, for example:

  • CustomIdentityKeyStoreFileName
  • ListenPort
  • UploadDirectoryName

That’s it.

Victor Jabur

How to capture programmatically (Java – Adf Faces) an attribute from payload task (Human Task Form)

Hi Guys,

This is an useful code that capture the value of an attribute inside of payload from Human Task generated automatically from bpel.

Here is a list of attributes that exists in your human task form.

With this code, you can capture the value of any attribute.

You can to call this method this way: getValueAttributeFromHumanTask(“numeroPedido”)


import oracle.adf.model.BindingContext;
import oracle.adf.view.rich.context.AdfFacesContext;
import oracle.binding.AttributeBinding;
import oracle.binding.BindingContainer;
import oracle.bpel.services.datacontrol.data.DataObject;

public String getValueAttributeFromHumanTask(String attributeName){
    String response = "";
    BindingContainer bindings = BindingContext.getCurrent().getCurrentBindingsEntry();
    AttributeBinding attr = (AttributeBinding)bindings.getControlBinding(attributeName);
    DataObject data = null;
    if(attr != null){
        data = (DataObject)attr.getInputValue();
    }
    if(data != null){
        response = data.getValue();
    }
    return response;
}

How to set recursively component properties using Java Server Faces (JSF)

Hello,

I am using a piece of code that setting disabled=true and readonly=true to all components inside of a Form, but you can use this in other situations:

In your .jspx File:

<f:view beforePhase="#{someController.makeFormReadOnly}">

In your .java File:


import javax.faces.application.Application;
import javax.faces.context.FacesContext;
import javax.faces.component.UIComponent;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import java.lang.reflect.Method;

public void makeFormReadOnly(FacesContext facesContext, UIComponent component) {
    try {
        Method[] methods = component.getClass().getMethods();
        for (Method method : methods) {
            if (method.getName().equals("getChildren")) {
                List<UIComponent> listaComp = (List<UIComponent>)method.invoke(component);
                for (UIComponent comp : listaComp) {
                    makeFormReadOnly(facesContext, comp);
                }
            }
        }
        component.setValueExpression("readOnly", getValueExpression(facesContext, "#{true}"));
        component.setValueExpression("disabled", getValueExpression(facesContext, "#{true}"));
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

private ValueExpression getValueExpression(FacesContext facesContext, String name) {
    Application app = facesContext.getApplication();
    ExpressionFactory elFactory = app.getExpressionFactory();
    ELContext elContext = facesContext.getELContext();
    return elFactory.createValueExpression(elContext, name, Object.class);
}

Invoking a Java Method by Name using Reflection

This is an example:

Class<?> c = Class.forName("class name");
Method  method = c.getDeclaredMethod ("method name", parameterTypes);
method.invoke (objectToInvokeOn, params);

Just It
Bye

How to propagate FacesMessage between two jsf pages

Hello,

The JSF don’t propagate a FacesMessage between two jsf pages, i discovery this when i trying to make something like this:

1 -
User click in a Jsf Button

2 - Call the action method in the Managed Bean, something like this:

	public String someMethod(){
		// Execute some code
		FacesMessage msg = new FacesMessage(FacesMessage.SEVERITY_INFO, "", "Something message");
		FacesContext.getCurrentInstance().addMessage(null, msg);
		return "otherPage";
	}

3 - Suppose that the string “otherPage” cause a normal redirect to other Jsf page, through faces-config.xml, in this exact point the FacesMessage is losted.

Resolution: For resolve this problem, follow this steps, basically this will affect all lifecycle of your jsf application:

1 - In your faces-config.xml, put this code:

  <lifecycle>
    <phase-listener>com.somepackage.MultiPageMessagesSupport</phase-listener>  
  </lifecycle>

2 – Put the below java class in the package specified above:

import java.util.HashSet;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;
import javax.faces.event.PhaseEvent;
import javax.faces.event.PhaseId;
import javax.faces.event.PhaseListener;

/**
 * Enables messages to be rendered on different pages from which they were set.
 * To produce this behaviour, this class acts as a <code>PhaseListener</code>.
 * 
 * This is performed by moving the FacesMessage objects:
 * <li>After each phase where messages may be added, this moves the messages
 * from the page-scoped FacesContext to the session-scoped session map.
 * <li>Before messages are rendered, this moves the messages from the
 * session-scoped session map back to the page-scoped FacesContext.
 * 
 * Only messages that are not associated with a particular component are ever
 * moved. These are the only messages that can be rendered on a page that is
 * different from where they originated. * To enable this behaviour, add a
 * <code>lifecycle</code> block to your faces-config.xml file. That block
 * should contain a single <code>phase-listener</code> block containing the
 * fully-qualified classname of this file.
 * 
 * @author <a href="mailto:jesse@odel.on.ca">Jesse Wilson</a>
 * 
 * @version This version have the bug corrected: The bug was:
 * In the same page, the FacesMessage was displayed many times,
 * with this patch, only different messages is added into new context.
 */
public class MultiPageMessagesSupport implements PhaseListener {

	private static final long serialVersionUID = 3328743500652081238L;

	/** a name to save messages in the session under */
	private static final String sessionToken = "MULTI_PAGE_MESSAGES_SUPPORT";

	/**
	 * Return the identifier of the request processing phase during which this
	 * listener is interested in processing PhaseEvent events.
	 */
	public PhaseId getPhaseId() {
		return PhaseId.ANY_PHASE;
	}

	/**
	 * Handle a notification that the processing for a particular phase of the
	 * request processing lifecycle is about to begin.
	 */
	public void beforePhase(PhaseEvent event) {
		if (event.getPhaseId() == PhaseId.RENDER_RESPONSE) {
			FacesContext facesContext = event.getFacesContext();
			restoreMessages(facesContext);
		}
	}

	/**
	 * Handle a notification that the processing for a particular phase has just
	 * been completed.
	 */
	public void afterPhase(PhaseEvent event) {
		if (event.getPhaseId() == PhaseId.APPLY_REQUEST_VALUES
				|| event.getPhaseId() == PhaseId.PROCESS_VALIDATIONS
				|| event.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
			FacesContext facesContext = event.getFacesContext();
			saveMessages(facesContext);
		}
	}

	/**
	 * Remove the messages that are not associated with any particular component
	 * from the faces context and store them to the user's session.
	 * 
	 * @return the number of removed messages.
	 */
	@SuppressWarnings("unchecked")
	private int saveMessages(FacesContext facesContext) {
		// remove messages from the context
		Set<FacesMessage> messages = new HashSet<FacesMessage>();
		for (Iterator i = facesContext.getMessages(null); i.hasNext();) {
			FacesMessage msg = (FacesMessage) i.next();
			messages.add(msg);
			i.remove();
		}
		// store them in the session
		if (messages.size() == 0)
			return 0;
		Map sessionMap = facesContext.getExternalContext().getSessionMap();
		// if there already are messages
		Set<FacesMessage> existingMessages = (Set<FacesMessage>) sessionMap
				.get(sessionToken);
		if (existingMessages != null) {
			existingMessages.addAll(messages);
			// if these are the first messages
		} else {
			sessionMap.put(sessionToken, messages);
		}
		return messages.size();
	}

	/**
	 * Remove the messages that are not associated with any particular component
	 * from the user's session and add them to the faces context.
	 * 
	 * @return the number of removed messages.
	 */
	@SuppressWarnings("unchecked")
	private int restoreMessages(FacesContext facesContext) {
		// remove messages from the session
		Map sessionMap = facesContext.getExternalContext().getSessionMap();
		Set<FacesMessage> messages = (Set<FacesMessage>) sessionMap
				.remove(sessionToken);
		// store them in the context
		if (messages == null)
			return 0;
		int restoredCount = messages.size();

		// set that contains wich messages already exists in the FacesContext
		Set<FacesMessage> facesContextMessages = new HashSet<FacesMessage>();
		for (Iterator i = facesContext.getMessages(null); i.hasNext();) {
			FacesMessage msg = (FacesMessage) i.next();
			facesContextMessages.add(msg);
			i.remove();
		}

		// add the messages that aren't in the FacesContext 
		for (FacesMessage facesMessage : messages) {
			if (!facesContextMessages.contains(facesMessage))
				facesContext.addMessage(null, facesMessage);
		}
		return restoredCount;
	}
}

Validador e Gerador de Renavam (Veículos) em Java – Novo Padrão 11 Digitos – A Partir de Abril 2013

Olá Pessoal,

Seguem abaixo 2 classes java para validação e geração de código renavam para veículos:

ValidadorRenavam.java

public class ValidadorRenavam {

    public boolean validarRenavam(String renavam){
        if(!renavam.matches("[0-9]{11}")){
            return false;
        }
        int soma = 0;
        for (int i = 0; i < 10; i++) {
            soma += Integer.parseInt(renavam.substring(i,i+1))*(i+2);
        }
        soma = soma % 11;
        int ultimoDigito = (soma == 10 ? 0 : soma);
        int digitoInformado = Integer.valueOf(renavam.substring(renavam.length()-1, renavam.length()));
        if(ultimoDigito == digitoInformado){
            return true;
        }
        return false;
    }
}

GeradorRenavam.java

import java.util.Random;

public class GeradorRenavam {

	public static void main(String[] args) throws Exception {
		int maximo = 0;
		try {
			maximo = Integer.valueOf(args[0]);
		} catch (Exception e) {
			throw new Exception("Especifique um valor de entrada válido");
		}
		for (int i = 0; i < maximo; i++) {
			String renavam = GeradorRenavam.geraNumeroRenavam();
			System.out.println(renavam);
		}
	}

	public static String geraNumeroRenavam() {
		Random r = new Random();
		String senha = "";
		for (int i = 0; i < 10; i++) {
			senha += Math.abs(r.nextInt(9));
		}
		int soma = 0;
		for (int i = 0; i < 10; i++) {
			soma += Integer.parseInt(senha.substring(i, i + 1)) * (i + 2);
		}
		soma = soma % 11;
		int ultimoDigito = (soma == 10 ? 0 : soma);
		return senha + ultimoDigito;
	}
}

Créditos deste Post para ViniGodoy: Link : http://www.guj.com.br/posts/list/149379.java

Espero que ajude alguém, …
Abraços.

Victor Jabur.

Follow

Get every new post delivered to your Inbox.

Join 447 other followers