Problemas com Login + Criptografia

1 resposta
CaioTakei

:smiley: Pessoal ja analisei o outro topico que fala de criptografia aqui mas infelizmente não consegui solucionar meu problema…
eu estou construindo um login que use MD5 para criptografar a senha, porém ta dando erro espero que possam me ajudar segue abaixo meu código quee sta dentro do evento do botão do login, e em baixo a classe que tem os metodos que criptografam a senha.

private void btnLoginActionPerformed(java.awt.event.ActionEvent evt) {
    //busca Driver
        try{       
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

//conecta no BD
Connection con=DriverManager.getConnection("jdbc:odbc:Estudo","Douglas","123@telecom");
Statement stmt = con.createStatement();
 



//começa aqui
 stmt = con.prepareStatement("select * from users where nome = ?");

String nome = txtNome.getText();
String senha = txtSenha.getText();

 stmt.setString(1, Usuario.getNome());
 ResultSet rs = stmt.executeQuery();
 
 
 if (rs.next()) {
     senhaNoBanco = rs.getString("senha");
 } else {
     throw new MinhaException("Usuário " + Usuario.getNome() + " não encontrado");
 }
   
 try {
     byte[] b = CriptoUtils.digest(Usuario.getSenha().getBytes(), "md5");
 } catch (NoSuchAlgorithmException e) {
     e.printStackTrace();
     return false;
 }
 
 String senhaCriptografada = CriptoUtils.byteArrayToHexString(b);
 
 if (senhaNoBanco.equalsIgnoreCase(senhaCriptografada )) {
     return true;
 } else {
     return false;
 }
//termina aqui
        
 
 
 
 
 
 
 
 
// fecha conexão com BD         
con.close(); 
}       catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex);
//trata os erros            
        } catch( SQLException e){ 
JOptionPane.showMessageDialog(this, "Erro Cmdo SQL " +
e.getMessage() );
} catch( ClassNotFoundException e){
JOptionPane.showMessageDialog( this, " Driver não encontrado " );
}
       

}
package cadastroteste;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public final class CriptoUtils {
    private static final String hexDigits = "0123456789abcdef";
     /**
    * Realiza um digest em um array de bytes através do algoritmo especificado
    * @param input - O array de bytes a ser criptografado
    * @param algoritmo - O algoritmo a ser utilizado
     * @return byte[] - O resultado da criptografia
     * @throws NoSuchAlgorithmException - Caso o algoritmo fornecido não seja
     * válido
     */
     public static byte[] digest(byte[] input, String algoritmo)
             
         throws NoSuchAlgorithmException {
         MessageDigest md = MessageDigest.getInstance(algoritmo);
         md.reset();
         return md.digest(input);
     }
   
     /**
      * Converte o array de bytes em uma representação hexadecimal.
      * @param input - O array de bytes a ser convertido.
      * @return Uma String com a representação hexa do array
      */
     public static String byteArrayToHexString(byte[] b) {
         StringBuffer buf = new StringBuffer();
     
         for (int i = 0; i < b.length; i++) {
             int j = ((int) b[i]) & 0xFF; 
             buf.append(hexDigits.charAt(j / 16)); 
             buf.append(hexDigits.charAt(j % 16)); 
         }
         
         return buf.toString();
     }
   
     /**
      * Converte uma String hexa no array de bytes correspondente.
      * @param hexa - A String hexa
      * @return O vetor de bytes
      * @throws IllegalArgumentException - Caso a String não sej auma
      * representação haxadecimal válida
      */
     public static byte[] hexStringToByteArray(String hexa)
         throws IllegalArgumentException {
       
         //verifica se a String possui uma quantidade par de elementos
         if (hexa.length() % 2 != 0) {
             throw new IllegalArgumentException("String hexa inválida");  
         }
       
         byte[] b = new byte[hexa.length() / 2];
       
         for (int i = 0; i < hexa.length(); i+=2) {
             b[i / 2] = (byte) ((hexDigits.indexOf(hexa.charAt(i)) << 4) |
                 (hexDigits.indexOf(hexa.charAt(i + 1))));          
         }
         return b;
     }

    
}

esta segunda classe peguei num tutorial aqui.
Pessoal por favor me ajudem, agradeço desde já.

1 Resposta

gui_sv

maaaaaaaas ql o erro que da ???

Criado 13 de agosto de 2008
Ultima resposta 13 de ago. de 2008
Respostas 1
Participantes 2