Java tutorial
/* * Copyright (C) 2012 * * Jefferson dos Santos Felix (jsfelix [at] gmail [dot] com) * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; either version 2 * of the License, or any later version. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * */ package com.sisfin.util; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import javax.annotation.PostConstruct; import javax.annotation.Resource; import javax.ejb.LocalBean; import javax.ejb.Stateless; import org.apache.commons.codec.binary.Base64; /** * Session Bean que implementa servios de criptografia e hashing. Utiliza a API * Java Security e Apache Commons Codec. */ @Stateless @LocalBean public class CryptService { private MessageDigest md; @Resource(name = "messageDigestAlgorithm") private String messageDigestAlgorithm; /** * Inicializa o session bean com o algoritmo de codificao definido no * arquivo de configurao dos beans. */ @PostConstruct public void init() { try { md = MessageDigest.getInstance(messageDigestAlgorithm); } catch (NoSuchAlgorithmException e) { // TODO: arrumar isso e.printStackTrace(); } } /** * Codifica uma palavra para um formato de hash Base64. Utilizado para * criptografar senhas. * * @param input * a palavra a ser codificada para hash * @return uma string Base64 representando o hash * @throws IllegalArgumentException * lana esta exceo se a palavra de entrada nula */ public String hash(String input) throws IllegalArgumentException { if (input == null) { throw new IllegalArgumentException("A entrada no pode ser nula."); } byte[] out = md.digest(input.getBytes()); return Base64.encodeBase64String(out); } }