Come posso generare un hash MD5?


Esiste un metodo per generare hash MD5 di una stringa in Java?

Author: bjb568, 2009-01-06

30 answers

java.security.MessageDigest e ' tuo amico. Chiama getInstance("MD5") per ottenere un digest del messaggio MD5 è possibile utilizzare.

 547
Author: Bombe, 2018-07-10 13:52:38

La classe MessageDigest può fornire un'istanza del digest MD5.

Quando si lavora con le stringhe e le classi di crittografia, assicurarsi di specificare sempre la codifica in cui si desidera la rappresentazione del byte. Se usi solo string.getBytes() userà la piattaforma predefinita. (Non tutte le piattaforme utilizzano le stesse impostazioni predefinite)

import java.security.*;

..

byte[] bytesOfMessage = yourString.getBytes("UTF-8");

MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);

Se hai molti dati dai un'occhiata al metodo .update(byte[]) che può essere chiamato ripetutamente. Quindi chiamare .digest() per ottenere l'hash risultante.

 649
Author: koregan, 2013-12-17 15:52:55

Potresti anche voler guardare la classe DigestUtilsdel progetto apache commons codec, che fornisce metodi molto convenienti per creare digest MD5 o SHA.

 251
Author: lutzh, 2014-04-28 13:57:27

Se vuoi effettivamente la risposta come una stringa anziché un array di byte, puoi sempre fare qualcosa del genere:

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;
}
 247
Author: user49913, 2013-11-18 16:33:00

Trovato questo:

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;
}

Sul sito qui sotto, non mi prendo alcun merito per questo, ma è una soluzione che funziona! Per me un sacco di altro codice non ha funzionato correttamente, ho finito per mancare 0s nell'hash. Questo sembra essere lo stesso di PHP. fonte: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093

 149
Author: dac2009, 2011-07-03 21:11:33

Ecco come lo 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));

Dove Hex è: org.apache.commons.codec.binary.Hexdal progetto Apache Commons .

 84
Author: adranale, 2012-02-29 08:49:36

Ho appena scaricato commons-codec.jar e ottenuto php perfetto come md5. Ecco manuale .

Basta importarlo nel tuo progetto e usare

String Url = "your_url";

System.out.println( DigestUtils.md5Hex( Url ) );

E il gioco è fatto.

 79
Author: Eugene, 2013-07-22 08:20:20

Ho trovato questo il modo più chiaro e conciso per farlo:

MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(StandardCharsets.UTF_8.encode(string));
return String.format("%032x", new BigInteger(1, md5.digest()));
 60
Author: rednoah, 2016-04-11 06:05:10

Ha trovato questa soluzione che è molto più pulita in termini di recupero di una rappresentazione di stringa da un 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));
    }
}

Il codice è stato estratto da qui.

 32
Author: Heshan Perera, 2013-01-31 09:21:37

Un'altra opzione è quella di utilizzare i metodi di hashing Guava :

Hasher hasher = Hashing.md5().newHasher();
hasher.putString("my string");
byte[] md5 = hasher.hash().asBytes();

Utile se stai già usando Guava (che se non lo sei, probabilmente dovresti essere).

 31
Author: andrewrjones, 2012-11-12 16:50:22

Un'altra implementazione:

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
 29
Author: stacker, 2014-04-24 15:26:17

Ho una Classe (Hash) per convertire il testo normale in hash in formati: md5 o sha1, simillar che funzioni 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");
    }
}

Test con JUnit e PHP

Script PHP:

<?php

echo 'MD5 :' . md5('Hello World') . "\n";
echo 'SHA1:' . sha1('Hello World') . "\n";

Output script PHP:

MD5 :b10a8db164e0754105b7a99be72e3fe5
SHA1:0a4d55a8d778e5022fab701977c5d840bbc486d0

Utilizzo di esempio e test con JUnit:

    public class HashTest {

    @Test
    public void test() {
        String txt = "Hello World";
        assertEquals("b10a8db164e0754105b7a99be72e3fe5", Hash.md5(txt));
        assertEquals("0a4d55a8d778e5022fab701977c5d840bbc486d0", Hash.sha1(txt));
    }

}

Codice in GitHub

Https://github.com/fitorec/java-hashes

 27
Author: fitorec, 2014-08-11 19:43:17

La mia risposta non molto rivelatrice:

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;
}
 22
Author: marioosh, 2012-04-17 17:19:08

Non c'è bisogno di renderlo troppo complicato. DigestUtils funziona bene e ti rende comodo mentre lavori con gli hash md5.

DigestUtils.md5Hex(_hash);

O

DigestUtils.md5(_hash);

È possibile utilizzare altri metodi di crittografia come sha o md.

 18
Author: Fatih Karatana, 2018-10-06 14:55:29

La risposta di Bombe è corretta, tuttavia nota che a meno che tu non debba assolutamente usare MD5 (ad esempio forzato per l'interoperabilità), una scelta migliore è SHA1 poiché MD5 ha punti deboli per un uso a lungo termine.

Dovrei aggiungere che SHA1 ha anche vulnerabilità teoriche, ma non così gravi. Lo stato attuale dell'arte nell'hashing è che ci sono un certo numero di funzioni hash sostitutive candidate, ma nessuna è ancora emersa come la migliore pratica standard per sostituire SHA1. Quindi, a seconda delle tue esigenze sarebbe bene che il tuo algoritmo hash fosse configurabile in modo che possa essere sostituito in futuro.

 16
Author: frankodwyer, 2009-01-06 10:17:05

C'è una classe DigestUtils in Spring anche:

Http://static.springsource.org/spring/docs/3.0.x/javadoc-api/org/springframework/util/DigestUtils.html

Questa classe contiene il metodo md5DigestAsHex() che esegue il lavoro.

 15
Author: Raul Luna, 2012-09-25 02:01:14

Puoi provare a seguire. Vedi dettagli e codici di download qui: http://jkssweetlife.com/java-hashgenerator-md5-sha-1 /

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();
}
}
 14
Author: ylu, 2018-09-09 21:21:25

Un'altra implementazione: Implementazione MD5 veloce in Java

String hash = MD5.asHex(MD5.getHash(new File(filename)));
 10
Author: Lukasz R., 2011-03-16 13:16:30

Non so se questo è rilevante per chiunque legga questo, ma ho appena avuto il problema che volevo

  • scarica un file da un determinato URL e
  • confronta il suo MD5 con un valore noto.

Volevo farlo solo con le classi JRE (nessun Apache Commons o simile). Una rapida ricerca sul Web non mi ha mostrato frammenti di codice di esempio facendo entrambi allo stesso tempo, solo ogni attività separatamente. Perché questo richiede di leggere lo stesso file due volte, l'ho capito potrebbe valere la pena scrivere del codice che unifica entrambe le attività, calcolando il checksum al volo durante il download del file. Questo è il mio risultato (scusa se non è Java perfetto, ma immagino che tu abbia comunque l'idea):

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)
        );
}
 9
Author: kriegaex, 2015-12-26 12:09:44

Dai un'occhiata al seguente link, l'esempio ottiene un Hash MD5 di un'immagine fornita: Hash MD5 di un'immagine

 6
Author: , 2009-01-07 03:24:12

Per quello che vale, mi sono imbattuto in questo perché voglio sintetizzare GUID da una chiave naturale per un programma che installerà componenti COM; Voglio syhthesize in modo da non gestire il ciclo di vita del GUID. Userò MD5 e quindi userò la classe UUID per ricavarne una stringa. (http://stackoverflow.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439 solleva questo problema).

In ogni caso, java.util.UUID può ottenere una bella stringa dai byte MD5.

return UUID.nameUUIDFromBytes(md5Bytes).toString();
 6
Author: Mihai Danila, 2012-10-26 17:01:41

MD5 va perfettamente bene se non hai bisogno della migliore sicurezza, e se stai facendo qualcosa come controllare l'integrità dei file, la sicurezza non è una considerazione. In tal caso potresti prendere in considerazione qualcosa di più semplice e veloce, come Adler32, che è anche supportato dalle librerie Java.

 5
Author: , 2009-01-08 08:42:23

Prova questo:

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 "";
    }
}
 4
Author: Marcelo Lopes, 2015-01-13 00:06:43
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();
 4
Author: Giancarlo Romeo, 2018-02-23 14:05:50

Questo dà l'esatto md5 come si ottiene dalla funzione md5 di mysql o dalle funzioni md5 di php, ecc. Questo è quello che uso (puoi cambiare in base alle tue esigenze)

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;            
    }

}
 3
Author: Aurangzeb, 2016-04-18 15:00:38

A differenza di PHP in cui è possibile eseguire una crittografia md5 del testo semplicemente chiamando la funzione md5 ie md5($text), in java è stato reso un po ' complicato. Di solito l'ho implementato chiamando una funzione che restituisce il testo hash md5. Ecco come l'ho implementato, prima creare una funzione denominata md5encryption all'interno della classe principale come indicato di seguito .

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;     
    }

Ora chiama la funzione quando hai bisogno come indicato di seguito.

String text = textFieldName.getText();
String pass = md5encryption(text);

Qui puoi vedere che hashtext è aggiunto con uno zero per farlo partita con la crittografia md5 in PHP.

 3
Author: Geordy James, 2016-11-10 10:45:43
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)
 3
Author: HimalayanCoder, 2017-01-04 10:26:57

Questo è quello per cui sono venuto qui - una comoda funzione scala che restituisce una stringa di hash MD5:

def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
 2
Author: Priyank Desai, 2015-10-20 18:27:54
 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));
 }
}

C'è un articolo su Codingkit a riguardo. Controlla: http://codingkit.com/a/JAVA/2013/1020/2216.html

 0
Author: shouyu, 2013-10-20 17:29:20
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!");
    }
}
 -2
Author: Radek, 2016-04-11 19:39:56