Compact MD5 class library for J2ME / JavaME app

 

For some reason, you might want to have MD5 functionality for your J2ME application. MD5 functionality is crucial for hashing password for safe keeping and is used in some web application for authentication method, the downside is that the MIDP/CLDC specification does not include MD5 functionality for J2ME platform.

Luckily somebody has implemented MD5 class suitable for use in J2ME application. It is fairly easy to use. Here's how I use it in my demo application :
//convert plaintext into bytes byte plain[] = plaintext.getString().getBytes();

// create MD5 object

MD5 md5 = new MD5(plain);

//get the resulting hashed byte

byte[] result = md5.doFinal();

//convert the hashed byte into hexadecimal character for display

String hashResult = md5.toHex(result);

Download the MD5 class here.

I've prepared J2ME application that demostrate the MD5 functionality in J2ME, it can be downloaded here : MD5test.zip , the resulting application is only around 5KB and it is small enough for practical use.

Tags: , , , , , , ,

Bookmark this post : These icons link to social bookmarking sites where readers can share and discover new web pages.
  • co.mments
  • del.icio.us
  • digg
  • YahooMyWeb
  • DZone
  • StumbleUpon
  • Technorati

Recommended Reading

7 smashing comments for this post.

  1. MD5 or other encryption Said:

    [...] You can take a look at this http://mobilepit.com/10/compact-md5-class-library-for-j2me-javame-app.html [...]

  2. Devmedia - WebMobile - Criptografia utilizando MD5 para aplicativos J2ME Said:

    [...] Esta é uma dica de implementação da funcionalidade de criptografia MD5. Como não existe uma lib nativa para J2ME, utilizaremos uma classe disponível na web que realiza os mesmos processos do Método de Hash. A lib pode ser encontrada com exemplos e código fonte abertos em Móbile PitStop.     /*  * MD5Hash.java  *  * Created on 11 de Agosto de 2007, 14:13  */   import javax.microedition.midlet.*; import javax.microedition.lcdui.*; import com.twmacinta.util.MD5;   /**  *  * @author  damazio  * @version  */ public class MD5Hash extends MIDlet  implements CommandListener {         private Display display;     private Form FormTeste;     private TextField textField1;     private TextField textField2;     private Command comandoDeSaida;     private Command comandoConverte;             public void startApp() {           display.setCurrent(FormTeste);            }         public void pauseApp() {     }         public void destroyApp(boolean unconditional) {             display.setCurrent(null);               // notificando o encerramento do aplicativo ao gerenciador do dispositivo             notifyDestroyed();            }         public MD5Hash() {           display = Display.getDisplay(this);           // quando iniciado o aplicativo, o construtor é invocado           // neste ponto montamos o formulario criando 2 objetos de texto           // a opção ANY diz que aceita qualquer caracter digitado           textField1 = new TextField(”Texto 1″, null, 120, TextField.ANY);           textField2 = new TextField(”Texto 2″, null, 120, TextField.ANY);                     // criando um objeto do tipo formulário. Este objeto é essencial para exibir os outros objetos texto           FormTeste = new Form(”Formulário Teste”);                     // adicionando os objetos texto ao formulário           FormTeste.append(textField1);           FormTeste.append(textField2);                     // criando o comando de sair e converter. O comando converter irá invocar o conversor           comandoDeSaida = new Command(”Sair”, Command.EXIT,1);           comandoConverte = new Command(”Converter”, Command.OK,1);                     // adicionando os comando de sair e atualizar ao formulario           FormTeste.addCommand(comandoConverte);           FormTeste.addCommand(comandoDeSaida);             // setando os comandos para serem reconhecidos ao manipular o teclado           // é preciso que a assinatura da classe implemente o CommandListener           FormTeste.setCommandListener(this);               }         public void commandAction(Command comando, Displayable s)     {         // Caso algum comando seja acionado, verifica-se se foi o comando de saída         if (comando == comandoDeSaida)         {             // invocando o método que encerra o aplicativo             destroyApp(false);         }         if (comando == comandoConverte)         {             Conversor();         }      }            public void Conversor() {         //converter o texto em bytes          byte plain[] = textField1.getString().getBytes();           // criar um objeto MD5Hash passando a sequencia de bytes resultante do texto digitado         MD5 md5 = new MD5(plain);           // pegando o resultado hash gerado         byte[] result = md5.doFinal();           // convertendo o conjunto de bytes em hexadecimal e aplicando ao objeto texto do display        textField2.setString(md5.toHex(result));             } } function EmptyString(s) { var Count; var Nblank = 0; if (s.length == 0) return (true); // empty string // count the number of blank chars for (Count = 0; Count < s.length; Count++) { if (s.charAt(Count) == ” “) Nblank++; } if (Nblank == s.length) return (true); else return (false); } function ValidEmail(s) { var Count; var s2; // empty or blank email if (EmptyString(s) == true) return (false); // email without @ if (s.indexOf(’@') == -1) return (false); // email with @ as the 1st char if (s.indexOf(’@') == 0) return (false); // email with @ as the last char if ((s.indexOf(’@')+1) == s.length) return (false); // email without . if (s.indexOf(’.') == -1) return (false); // email with . as the 1st char if (s.indexOf(’.') == 0) return (false); // email with . as the last char if ((s.indexOf(’.')+1) == s.length) return (false); // Now look for the first . after the first @ // s2 = string after the first @ s2=s.substring(s.indexOf(’@')+1,s.length); // email without a dot after the first @ if (s2.indexOf(’.') == -1) return (false); // email dot right after the first @ if (s2.indexOf(’.') == 0) return (false); return (true); } [...]

  3. voyager Said:

    just searching for MD5 in J2ME and found Timothy W Macinta library and then this site with a good example of how to use it.

    great!!
    thank you!!!!!!!!!!!!!!

  4. dd Said:

    http://mobile.mypapit.net/j/MD5test.zip
    not exist ;(

    please send me this code.
    ZnJvbmRhMUB0bGVuLnBs

  5. dd Said:

    not working propertly ;(

    echo “o” | md5sum
    e73af36376314c7c0022cb1d204f76b3
    is different to this program

  6. mypapit Said:

    depends on how do you validate it against

  7. developer Said:

    Hi.
    I dont know why, but i cant open your example file with netbeans, can you give me any tip how to do it?
    thanks

Leave a Comment

Subscribe by Email


Powered by FeedBlitz

 


Your Ad Here