Hash String via SHA-256 w języku Java

Rozglądając się tu i w ogóle w Internecie, znalazłem dmuchany zamek . Chcę użyć Bouncy Castle (lub innego darmowego narzędzia), aby wygenerować Hash SHA-256 ciągu znaków w Javie. Patrząc na ich dokumentację nie mogę znaleźć dobrych przykładów tego, co chcę zrobić. Czy ktoś może mi pomóc?

Author: Nikolaus Gradwohl, 2010-06-23

8 answers

Aby zahaszować łańcuch, użyj wbudowanej klasy MessageDigest :

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;

public class CryptoHash {
  public static void main(String[] args) throws NoSuchAlgorithmException {
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "Text to hash, cryptographically.";

    // Change this to UTF-16 if needed
    md.update(text.getBytes(StandardCharsets.UTF_8));
    byte[] digest = md.digest();

    String hex = String.format("%064x", new BigInteger(1, digest));
    System.out.println(hex);
  }
}

W powyższym fragmencie digest zawiera haszowany łańcuch, a hex zawiera szesnastkowy łańcuch ASCII z lewym, zerowym wypełnieniem.

 238
Author: Brendan Long,
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-02 14:41:20

Jest to już zaimplementowane w bibliotekach runtime.

public static String calc(InputStream is) {
    String output;
    int read;
    byte[] buffer = new byte[8192];

    try {
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        while ((read = is.read(buffer)) > 0) {
            digest.update(buffer, 0, read);
        }
        byte[] hash = digest.digest();
        BigInteger bigInt = new BigInteger(1, hash);
        output = bigInt.toString(16);
        while ( output.length() < 32 ) {
            output = "0"+output;
        }
    } 
    catch (Exception e) {
        e.printStackTrace(System.err);
        return null;
    }

    return output;
}

W środowisku JEE6+ można również użyć JAXB DataTypeConverter :

import javax.xml.bind.DatatypeConverter;

String hash = DatatypeConverter.printHexBinary( 
           MessageDigest.getInstance("MD5").digest("SOMESTRING".getBytes("UTF-8")));
 28
Author: stacker,
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-12 13:39:01

Niekoniecznie potrzebujesz Biblioteki BouncyCastle. Poniższy kod pokazuje, jak to zrobić za pomocą liczby całkowitej.funkcja toHexString

public static String sha256(String base) {
    try{
        MessageDigest digest = MessageDigest.getInstance("SHA-256");
        byte[] hash = digest.digest(base.getBytes("UTF-8"));
        StringBuffer hexString = new StringBuffer();

        for (int i = 0; i < hash.length; i++) {
            String hex = Integer.toHexString(0xff & hash[i]);
            if(hex.length() == 1) hexString.append('0');
            hexString.append(hex);
        }

        return hexString.toString();
    } catch(Exception ex){
       throw new RuntimeException(ex);
    }
}

Specjalne podziękowania dla user1452273 z tego postu: Jak hashować jakiś ciąg z sha256 w Javie?

Tak trzymać !
 15
Author: Whiplash,
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-05-23 11:47:01

Podczas korzystania z hashcodes z dowolnym dostawcą jce najpierw spróbuj uzyskać instancja algorytmu, a następnie zaktualizuj go danymi, które chcesz zahaszować a po zakończeniu wywołujesz digest, aby uzyskać wartość hash.

MessageDigest sha = MessageDigest.getInstance("SHA-256");
sha.update(in.getBytes());
byte[] digest = sha.digest();

Możesz użyć digest, aby uzyskać kodowaną wersję base64 lub hex zgodnie z Twoimi potrzebami

 8
Author: Nikolaus Gradwohl,
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
2010-08-19 22:05:34

Java 8: Base64 Dostępny:

    MessageDigest md = MessageDigest.getInstance( "SHA-512" );
    md.update( inbytes );
    byte[] aMessageDigest = md.digest();

    String outEncoded = Base64.getEncoder().encodeToString( aMessageDigest );
    return( outEncoded );
 7
Author: Mike Dever,
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-07-18 23:52:32

Przypuszczam, że używasz stosunkowo starej wersji Javy bez SHA-256. Musisz więc dodać dostawcę BouncyCastle do już dostarczonych "dostawców zabezpieczeń" w swojej wersji java.

    // NEEDED if you are using a Java version without SHA-256    
    Security.addProvider(new BouncyCastleProvider());

    // then go as usual 
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "my string...";
    md.update(text.getBytes("UTF-8")); // or UTF-16 if needed
    byte[] digest = md.digest();
 5
Author: obe6,
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-29 10:13:44
return new String(Hex.encode(digest));
 1
Author: Kay,
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-11-19 22:31:56

To będzie działać z " org.bouncycastle.util.Enkodery.Hex " following package

return new String(Hex.encode(digest));
Jest w bouncycastle jar.
 -1
Author: Shrikant Karvade,
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-07-07 12:37:29