Java: How to get MD5 hash from password string
Recently I had the problem that I had to convert a normal password string to a MD5 Password String which is Base64-Encoded. I found a lot of results but they just worked on JBoss 4.2, so I changed it and now it will also run on JBoss 5.1.0GA::
[codesyntax lang="java" strict="yes"]
package com.sicap.ssis2.servlets;
import java.security.MessageDigest;
/**
* @author doonot
*
*/
public class MD5HashGenerator {
/**
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
// TODO Auto-generated method stub
String password = “testpassword”;
MessageDigest md = null;
try
{
md = MessageDigest.getInstance(“MD5″);
}
catch(Exception e)
{
e.printStackTrace();
}
byte[] passwordBytes = password.getBytes();
byte[] hash = md.digest(passwordBytes);
System.out.println(getHexString(hash));
String passwordHash = org.jboss.security.Base64Encoder.encode(hash);
System.out.println(“password hash: “+ passwordHash);
}
/**
* This method returns the hex string from the password byte array
* @param b Byte[]
* @return string hex password string
* @throws Exception
*/
public static String getHexString(byte[] b) throws Exception {
String result = “”;
for (int i=0; i < b.length; i++) {
result +=
Integer.toString( ( b[i] & 0xff ) + 0×100, 16).substring( 1 );
}
return result;
}
}
[/codesyntax]
Leave a short comment if you think that was usefull! Best regards!
An Twitter senden