public static String passwordToMd5(char[] password, boolean clearPassword) {
String md5 = null;
if (password != null) {
try {
//Convertir la entrada a array de bytes, ya que así se requiere
// para poder codificarla a MD5. No se debe convertir a String
// por cuestiones de seguridad
CharBuffer charBuffer = CharBuffer.wrap(password);
ByteBuffer byteBuffer = Charset.forName("UTF-8").encode(charBuffer);
byte[] bytesPassword = Arrays.copyOfRange(byteBuffer.array(),
byteBuffer.position(), byteBuffer.limit());
//Realizar la codificación
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] arrayBytesMd5 = md.digest(bytesPassword);
//it is recommended that the returned character array be cleared
// after use by setting each character to zero
Arrays.fill(charBuffer.array(), \'\\u0000\'); // clear sensitive data
Arrays.fill(byteBuffer.array(), (byte) 0); // clear sensitive data
Arrays.fill(bytesPassword, (byte) 0);
if(clearPassword) {
Arrays.fill(password, \'\\u0000\');
}
//Convertir a hexadecimal pasándolo a BigInteger
BigInteger bigIntMd5 = new BigInteger(1, arrayBytesMd5);
md5 = bigIntMd5.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while (md5.length() < 32) {
md5 = "0" + md5;
}
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(MyClass.class.getName()).log(Level.SEVERE, null, ex);
}
}
return md5;
}