Baseado no post "Java md5 example with MessageDigest", adaptei uma classe para gerar md5 de uma forma um pouco parecida com a do PHP.
Abaixo segue o código fonte da classe:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* SimpleMessageDigest
*
* this class has static methods to ease the way to use message digest functions
* @author adolfo
*/
public final class SimpleMessageDigest {
/**
* md5 algorithm message digest method
* @param text
* @return
*/
public static final String md5 (String text) {
// starts digesting the received text
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("MD5");
md.reset();
md.update(text.getBytes());
byte[] messageDigest = md.digest();
for (int i = 0; i < messageDigest.length; i++) {
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
}
} catch (NoSuchAlgorithmException e) {
// I know that java implements md5 algorithm
}
return hexString.toString();
}
/**
* sha1 algorithm message digest method
* @param text
* @return
*/
public static final String sha1 (String text) {
// starts digesting the received text
StringBuffer hexString = new StringBuffer();
try {
MessageDigest md = MessageDigest.getInstance("SHA1");
md.reset();
md.update(text.getBytes());
byte[] messageDigest = md.digest();
for (int i = 0; i < messageDigest.length; i++) {
hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
}
} catch (NoSuchAlgorithmException e) {
// I know that java implements sha1 algorithm
}
return hexString.toString();
}
}
Nenhum comentário:
Postar um comentário