Jak mogę wygenerować hash MD5?
Czy jest jakaś metoda generowania hasha MD5 ciągu znaków w Javie?
30 answers
java.security.MessageDigest
to twój przyjaciel. Call getInstance("MD5")
Aby uzyskać skrót wiadomości MD5 możesz użyć.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-10 13:52:38
Klasa MessageDigest
może dostarczyć Ci instancję MD5 digest.
Podczas pracy z łańcuchami znaków i klasami kryptograficznymi upewnij się, że zawsze określa kodowanie, w którym chcesz reprezentować bajt. Jeśli tylko użyjesz string.getBytes()
, użyje domyślnej platformy. (Nie wszystkie platformy używają tych samych wartości domyślnych)
import java.security.*;
..
byte[] bytesOfMessage = yourString.getBytes("UTF-8");
MessageDigest md = MessageDigest.getInstance("MD5");
byte[] thedigest = md.digest(bytesOfMessage);
Jeśli masz dużo danych, spójrz na metodę .update(byte[])
, którą można wywoływać wielokrotnie. Następnie wywołaj .digest()
, Aby uzyskać wynikowy hash.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-17 15:52:55
Warto również przyjrzeć się klasie DigestUtils projektu Apache commons codec , który dostarcza bardzo wygodnych metod do tworzenia md5 lub SHA digestów.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-28 13:57:27
Jeśli chcesz, aby odpowiedź była z powrotem ciągiem znaków, a nie tablicą bajtów, zawsze możesz zrobić coś takiego:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-18 16:33:00
Znalazłem to:
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;
}
Na poniższej stronie nie biorę za to kredytu, ale to rozwiązanie, które działa! Dla mnie wiele innych kodu nie działa poprawnie, skończyło się brak 0s w hash. Ten wydaje się być taki sam jak PHP. źródło: http://m2tec.be/blog/2010/02/03/java-md5-hex-0093
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-07-03 21:11:33
Oto jak go używam:
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));
Gdzie Hex to: org.apache.commons.codec.binary.Hex
z projektu Apache Commons .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-02-29 08:49:36
Właśnie ściągnąłem commons-codec.jar i ma doskonałe php jak md5. Oto Instrukcja .
Po prostu zaimportuj go do swojego projektu i użyj
String Url = "your_url";
System.out.println( DigestUtils.md5Hex( Url ) );
No i proszę.Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-22 08:20:20
Uważam, że jest to najbardziej jasny i zwięzły sposób, aby to zrobić:
MessageDigest md5 = MessageDigest.getInstance("MD5");
md5.update(StandardCharsets.UTF_8.encode(string));
return String.format("%032x", new BigInteger(1, md5.digest()));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-11 06:05:10
Znalazłem rozwiązanie, które jest znacznie czystsze, jeśli chodzi o odzyskanie reprezentacji ciągu znaków z skrótu 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));
}
}
Kod został wydobyty z tutaj .
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-01-31 09:21:37
Inną opcją jest użycie metody hashowania Guava :
Hasher hasher = Hashing.md5().newHasher();
hasher.putString("my string");
byte[] md5 = hasher.hash().asBytes();
Przydatne, jeśli używasz już Guava(a jeśli nie, prawdopodobnie powinieneś).
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-11-12 16:50:22
Kolejna implementacja:
import javax.xml.bind.DatatypeConverter;
String hash = DatatypeConverter.printHexBinary(
MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-04-24 15:26:17
Mam klasę (Hash) do konwersji zwykłego tekstu w hash w formatach: md5 lub sha1, która działa w 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");
}
}
Testowanie z JUnit i PHP
Skrypt PHP:
<?php
echo 'MD5 :' . md5('Hello World') . "\n";
echo 'SHA1:' . sha1('Hello World') . "\n";
Wyjście skryptu PHP:
MD5 :b10a8db164e0754105b7a99be72e3fe5
SHA1:0a4d55a8d778e5022fab701977c5d840bbc486d0
Używanie przykładu i testowania z JUnit:
public class HashTest {
@Test
public void test() {
String txt = "Hello World";
assertEquals("b10a8db164e0754105b7a99be72e3fe5", Hash.md5(txt));
assertEquals("0a4d55a8d778e5022fab701977c5d840bbc486d0", Hash.sha1(txt));
}
}
Kod w GitHub
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-08-11 19:43:17
Moja niezbyt odkrywcza odpowiedź:
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;
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-04-17 17:19:08
Nie musisz tego komplikować. DigestUtils działa dobrze i zapewnia komfort podczas pracy z hashami md5.
DigestUtils.md5Hex(_hash);
Lub
DigestUtils.md5(_hash);
Albo możesz użyć innych metod szyfrowania, takich jak sha lub md.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-10-06 14:55:29
Odpowiedź Bombe ' a jest poprawna, jednak zauważ, że jeśli nie musisz bezwzględnie używać MD5( np. zmuszać cię do interoperacyjności), lepszym wyborem jest SHA1, ponieważ MD5 ma słabe strony w długotrwałym użytkowaniu.
Dodam, że SHA1 ma również teoretyczne luki, ale nie tak poważne. Obecny stan techniki w hashowaniu polega na tym, że istnieje wiele kandydujących funkcji hashujących, ale żadna z nich nie pojawiła się jeszcze jako standardowa najlepsza praktyka zastępowania SHA1. Tak więc, w zależności od potrzeb dobrze byłoby, aby twój algorytm hash był konfigurowalny, aby można go było zastąpić w przyszłości.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2009-01-06 10:17:05
Istnieje DigestUtils
klasa w Wiosna również:
Ta klasa zawiera metodę md5DigestAsHex()
, która wykonuje zadanie.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-09-25 02:01:14
Możesz spróbować śledzić. Zobacz szczegóły i pobierz kody tutaj: 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();
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-09-09 21:21:25
Kolejna implementacja: Szybka implementacja MD5 w Javie
String hash = MD5.asHex(MD5.getHash(new File(filename)));
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-03-16 13:16:30
Nie wiem, czy jest to istotne dla kogoś, kto to czyta, ale właśnie miałem problem, który chciałem
- Pobierz Plik z podanego adresu URL i
- porównaj jego MD5 ze znaną wartością.
Chciałem to zrobić tylko z klasami JRE (bez Apache Commons lub podobnych). Szybkie wyszukiwanie w sieci nie pokazało mi przykładowych fragmentów kodu wykonujących oba w tym samym czasie, TYLKO każde zadanie osobno. Ponieważ wymaga to dwukrotnego odczytania tego samego pliku, pomyślałem, że może warto napisać jakiś kod, który jednoczy oba zadania, obliczając sumę kontrolną w locie podczas pobierania pliku. To jest mój wynik (sorry jeśli nie jest idealny Java, ale chyba i tak masz pomysł):
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)
);
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-12-26 12:09:44
Spójrz na poniższy link, przykład pobiera hash MD5 dostarczonego obrazu: MD5 Hash obrazu
Jeśli to coś warte, natknąłem się na to, ponieważ chcę zsyntetyzować GUID z naturalnego klucza dla programu, który zainstaluje komponenty COM; chcę syhthesize, aby nie zarządzać cyklem życia GUID. Użyję MD5, a następnie użyję klasy UUID, aby uzyskać z niej ciąg znaków. (http://stackoverflow.com/questions/2190890/how-can-i-generate-guid-for-a-string-values/12867439 podnosi ten problem).
W każdym razie java.util.UUID może uzyskać ładny ciąg znaków z bajtów MD5.
return UUID.nameUUIDFromBytes(md5Bytes).toString();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-10-26 17:01:41
MD5 jest w porządku, jeśli nie potrzebujesz najlepszego zabezpieczenia, a jeśli robisz coś takiego jak sprawdzanie integralności plików, bezpieczeństwo nie jest brane pod uwagę. W takim przypadku warto rozważyć coś prostszego i szybszego, na przykład Adler32, który jest również obsługiwany przez biblioteki Java.
Spróbuj tego:
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 "";
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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();
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-02-23 14:05:50
Ten podaje dokładną wartość md5, jaką można uzyskać z funkcji MD5 mysql lub funkcji MD5 php itp. To jest ten, którego używam (możesz zmienić w zależności od potrzeb)
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;
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-18 15:00:38
W przeciwieństwie do PHP, gdzie można wykonać szyfrowanie md5 swojego tekstu przez wywołanie funkcji md5 ie md5($text)
, w Javie było to nieco skomplikowane. Zwykle zaimplementowałem go przez wywołanie funkcji, która zwraca tekst skrótu md5.
Oto jak to zaimplementowałem , najpierw Utwórz funkcję o nazwie md5encryption
wewnątrz swojej głównej klasy, jak podano poniżej .
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;
}
Teraz wywołaj funkcję, gdy kiedykolwiek potrzebujesz, jak podano poniżej.
String text = textFieldName.getText();
String pass = md5encryption(text);
Tutaj możesz zobaczyć, że hashtext jest dołączany z zero, aby to zrobić zgodność z szyfrowaniem md5 w PHP.
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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)
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-04 10:26:57
Po to tu przyszedłem-poręczna funkcja scala, która zwraca łańcuch hash MD5:
def md5(text: String) : String = java.security.MessageDigest.getInstance("MD5").digest(text.getBytes()).map(0xFF & _).map { "%02x".format(_) }.foldLeft(""){_ + _}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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));
}
}
Jest na ten temat artykuł o Codingkit. Sprawdź: http://codingkit.com/a/JAVA/2013/1020/2216.html Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
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!");
}
}
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-04-11 19:39:56