1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39
|
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/*
* Fonctions utilitaires pour le cryptage MD5
* Encode une chaine et renvoi son résultat crypté en
* héxadécimal avec l'algorithme MD5
*/
public class SecurityTools
{
/*
* Encode la chaine passé en paramètre avec l'algorithme MD5
* @param key : la chaine à encoder
* @return la valeur (string) hexadécimale sur 32 bits
*/
public static String getEncodedString(String key) {
byte[] uniqueKey = key.getBytes();
byte[] hash = null;
try {
hash = MessageDigest.getInstance("MD5").digest(uniqueKey);
} catch (NoSuchAlgorithmException e) {
throw new Error("no MD5 support in this VM");
}
StringBuffer hashString = new StringBuffer();
for ( int i = 0; i < hash.length; ++i ) {
String hex = Integer.toHexString(hash[i]);
if ( hex.length() == 1 ) {
hashString.append('0');
hashString.append(hex.charAt(hex.length()-1));
} else {
hashString.append(hex.substring(hex.length()-2));
}
}
return hashString.toString();
}
} |