Como posso gerar um hash MD5?
Existe algum método para gerar hash MD5 de uma string em Java?
30 answers
java.security.MessageDigest
é teu amigo. Chamada getInstance("MD5")
para obter uma mensagem MD5 digest você pode usar.
A classe MessageDigest
pode fornecer-lhe uma instância do Digest MD5.
Ao trabalhar com strings e as classes de cifra, certifique-se de sempre indique a codificação em que deseja a representação de 'bytes'. Se você apenas usar string.getBytes()
ele irá usar a plataforma padrão. (Nem todas as plataformas usam os mesmos valores por omissão)
import java.security.*;
..
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
Se você tem um monte de dados dê uma olhada no método .update(byte[])
que pode ser chamado repetidamente. Então chame .digest()
para obter o hash resultante.
Você também pode querer olhar para a classeDigestUtils da classe apache commons codec , que fornece métodos muito convenientes para criar o MD5 ou o SHA digests.
Se você realmente quer a resposta de volta como uma string em oposição a uma matriz de bytes, você sempre pode fazer algo assim:
String plaintext = "your text here";
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
String hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
Encontrei isto:
public String MD5(String md5) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(md5.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
No site abaixo, Não tenho crédito por isso, mas é uma solução que funciona!
Para mim, muitos outros códigos não funcionaram bem, acabei por perder zero no hash.
Este parece ser o mesmo que PHP tem.
fonte: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093
É assim que eu o uso:
final MessageDigest messageDigest = MessageDigest.getInstance("MD5");
messageDigest.reset();
messageDigest.update(string.getBytes(Charset.forName("UTF8")));
final byte[] resultByte = messageDigest.digest();
final String result = new String(Hex.encodeHex(resultByte));
Onde está Hex: org.apache.commons.codec.binary.Hex
do projecto Apache Commons .
Basta importá-lo para o seu projecto e usar
String Url = "your_url";
System.out.println( DigestUtils.md5Hex( Url ) );
E aí está.
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(StandardCharsets.UTF_8.encode(string));
return String.format("%032x", new BigInteger(1, md5.digest()));
Encontrei esta solução que é muito mais limpa em termos de obter uma representação de cadeia de volta de um hash MD5.
import java.security.*;
import java.math.*;
public class MD5 {
public static void main(String args[]) throws Exception{
String s="This is a test";
MessageDigest m=MessageDigest.getInstance("MD5");
m.update(s.getBytes(),0,s.length());
System.out.println("MD5: "+new BigInteger(1,m.digest()).toString(16));
}
}
O código foi extraído de aqui.
Outra aplicação:
import javax.xml.bind.DatatypeConverter;
String hash = DatatypeConverter.printHexBinary(
MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
Eu tenho uma classe (Hash) para converter texto simples em hash em formatos: md5 ou sha1, simillar que funções php ( md5, sha1):
public class Hash {
/**
*
* @param txt, text in plain format
* @param hashType MD5 OR SHA1
* @return hash in hashType
*/
public static String getHash(String txt, String hashType) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance(hashType);
byte[] array = md.digest(txt.getBytes());
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1,3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
//error action
}
return null;
}
public static String md5(String txt) {
return Hash.getHash(txt, "MD5");
}
public static String sha1(String txt) {
return Hash.getHash(txt, "SHA1");
}
}
Teste com JUnit e PHP
Programa de PHP:
<?php
echo 'MD5 :' . md5('Hello World') . "\n";
echo 'SHA1:' . sha1('Hello World') . "\n";
Programa de saída do PHP:
MD5 :b10a8db164e0754105b7a99be72e3fe5
SHA1:0a4d55a8d778e5022fab701977c5d840bbc486d0
Usando o exemplo e testando com JUnit:
public class HashTest {
@Test
public void test() {
String txt = "Hello World";
assertEquals("b10a8db164e0754105b7a99be72e3fe5", Hash.md5(txt));
assertEquals("0a4d55a8d778e5022fab701977c5d840bbc486d0", Hash.sha1(txt));
}
}
Código em GitHub
private String md5(String s) {
try {
MessageDigest m = MessageDigest.getInstance("MD5");
m.update(s.getBytes(), 0, s.length());
BigInteger i = new BigInteger(1,m.digest());
return String.format("%1$032x", i);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return null;
}
DigestUtils.md5Hex(_hash);
Ou
DigestUtils.md5(_hash);
Pode usar quaisquer outros métodos de encriptação, como o sha ou o md.
A Resposta da Bombe está correcta, no entanto, note que, a menos que seja absolutamente necessário utilizar o MD5 (por exemplo, forcado a si para efeitos de interoperabilidade), uma melhor escolha é o SHA1, uma vez que o MD5 tem pontos fracos para utilização a longo prazo.
Devo acrescentar que o SHA1 também tem vulnerabilidades teóricas, mas não tão graves. O estado atual da arte em hashing é que há uma série de funções de hash de substituição candidato, mas nenhum ainda emergiu como a melhor prática padrão para substituir SHA1. Então, dependendo das suas necessidades seria aconselhável que o seu algoritmo de hash fosse configurável para que possa ser substituído no futuro.Existe uma classe DigestUtils
em Primavera também:
Esta classe contém o método {[1] } que faz o trabalho.
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class MD5Example {
public static void main(String[] args) throws Exception {
final String inputString = "Hello MD5";
System.out.println("MD5 hex for '" + inputString + "' :");
System.out.println(getMD5Hex(inputString));
}
public static String getMD5Hex(final String inputString) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("MD5");
md.update(inputString.getBytes());
byte[] digest = md.digest();
return convertByteToHex(digest);
}
private static String convertByteToHex(byte[] byteData) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
return sb.toString();
}
}
Outra implementação: Implementação MD5 rápida em Java
String hash = MD5.asHex(MD5.getHash(new File(filename)));
- obter um ficheiro de um dado URL e
- compare o seu MD5 com um valor conhecido.
import java.io.FileOutputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.net.URL;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ReadableByteChannel;
import java.nio.channels.WritableByteChannel;
import java.security.DigestOutputStream; // new
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
void downloadFile(String fromURL, String toFile, BigInteger md5)
throws IOException, NoSuchAlgorithmException
{
ReadableByteChannel in = Channels.newChannel(new URL(fromURL).openStream());
MessageDigest md5Digest = MessageDigest.getInstance("MD5");
WritableByteChannel out = Channels.newChannel(
//new FileOutputStream(toFile)); // old
new DigestOutputStream(new FileOutputStream(toFile), md5Digest)); // new
ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024); // 1 MB
while (in.read(buffer) != -1) {
buffer.flip();
//md5Digest.update(buffer.asReadOnlyBuffer()); // old
out.write(buffer);
buffer.clear();
}
BigInteger md5Actual = new BigInteger(1, md5Digest.digest());
if (! md5Actual.equals(md5))
throw new RuntimeException(
"MD5 mismatch for file " + toFile +
": expected " + md5.toString(16) +
", got " + md5Actual.toString(16)
);
}
Dê uma olhada no seguinte link, o exemplo obtém um hash MD5 de uma imagem fornecida: Hash MD5 de uma imagem
Em todo o caso, java.util.O UUID pode arranjar-te um bom fio dos bytes MD5.
return UUID.nameUUIDFromBytes(md5Bytes).toString();
Tenta isto:
public static String getHashMD5(String string) {
try {
MessageDigest md = MessageDigest.getInstance("MD5");
BigInteger bi = new BigInteger(1, md.digest(string.getBytes()));
return bi.toString(16);
} catch (NoSuchAlgorithmException ex) {
Logger.getLogger(MD5Utils.class
.getName()).log(Level.SEVERE, null, ex);
return "";
}
}
import java.security.*;
import javax.xml.bind.*;
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] bytesOfDigest = md.digest(bytesOfMessage);
String digest = DatatypeConverter.printHexBinary(bytesOfDigest).toLowerCase();
Este dá o md5 EXACTO à medida que se obtém da função md5 do mysql ou das funções md5 do php, etc. Este é o que eu uso (você pode mudar de acordo com suas necessidades)
public static String md5( String input ) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(input.getBytes( "UTF-8" ));
StringBuffer sb = new StringBuffer();
for (int i = 0; i < array.length; i++) {
sb.append( String.format( "%02x", array[i]));
}
return sb.toString();
} catch ( NoSuchAlgorithmException | UnsupportedEncodingException e) {
return null;
}
}
Ao contrário do PHP, onde pode fazer uma encriptação md5 do seu texto apenas chamando a função md5 ie md5($text)
, em java tornou-se um pouco complicado. Normalmente implementei-o chamando uma função que devolve o texto de hash md5.
Aqui está como eu o implementei, primeiro crie uma função chamada md5encryption
dentro de sua classe principal como indicado abaixo .
public static String md5encryption(String text)
{ String hashtext = null;
try
{
String plaintext = text;
MessageDigest m = MessageDigest.getInstance("MD5");
m.reset();
m.update(plaintext.getBytes());
byte[] digest = m.digest();
BigInteger bigInt = new BigInteger(1,digest);
hashtext = bigInt.toString(16);
// Now we need to zero pad it if you actually want the full 32 chars.
while(hashtext.length() < 32 ){
hashtext = "0"+hashtext;
}
} catch (Exception e1)
{
// TODO: handle exception
JOptionPane.showMessageDialog(null,e1.getClass().getName() + ": " + e1.getMessage());
}
return hashtext;
}
Agora ligue para a função quando necessário, como indicado abaixo.
String text = textFieldName.getText();
String pass = md5encryption(text);
Aqui você pode ver que o hashtext é adicionado com um zero a faz com que corresponda à encriptação md5 no PHP.
import java.security.MessageDigest
val digest = MessageDigest.getInstance("MD5")
//Quick MD5 of text
val text = "MD5 this text!"
val md5hash1 = digest.digest(text.getBytes).map("%02x".format(_)).mkString
//MD5 of text with updates
digest.update("MD5 ".getBytes())
digest.update("this ".getBytes())
digest.update("text!".getBytes())
val md5hash2 = digest.digest().map(0xFF & _).map("%02x".format(_)).mkString
//Output
println(md5hash1 + " should be the same as " + md5hash2)
Foi para isto que vim aqui - uma função scala útil que devolve uma sequência de hash MD5:
def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* MD5 encryption
*
* @author Hongten
*
*/
public class MD5 {
public static void main(String[] args) {
System.out.println(MD5.getMD5("123456"));
}
/**
* Use md5 encoded code value
*
* @param sInput
* clearly
* @ return md5 encrypted password
*/
public static String getMD5(String sInput) {
String algorithm = "";
if (sInput == null) {
return "null";
}
try {
algorithm = System.getProperty("MD5.algorithm", "MD5");
} catch (SecurityException se) {
}
MessageDigest md = null;
try {
md = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
byte buffer[] = sInput.getBytes();
for (int count = 0; count < sInput.length(); count++) {
md.update(buffer, 0, count);
}
byte bDigest[] = md.digest();
BigInteger bi = new BigInteger(bDigest);
return (bi.toString(16));
}
}
Há um artigo sobre Codingkit sobre isso. Confira: http://codingkit.com/a/JAVA/2013/1020/2216.html
private String hashuj(String dane) throws ServletException{
try {
MessageDigest m = MessageDigest.getInstance("MD5");
byte[] bufor = dane.getBytes();
m.update(bufor,0,bufor.length);
BigInteger hash = new BigInteger(1,m.dige`enter code here`st());
return String.format("%1$032X", hash);
} catch (NoSuchAlgorithmException nsae) {
throw new ServletException("Algorytm szyfrowania nie jest obsługiwany!");
}
}