Cadena de hash a través de SHA-256 en Java


Mirando por aquí, así como el Internet en general, he encontrado Castillo hinchable. Quiero usar Bouncy Castle (o alguna otra utilidad disponible gratuitamente) para generar un Hash SHA-256 de una cadena en Java. Mirando su documentación no puedo encontrar ningún buen ejemplo de lo que quiero hacer. ¿Alguien puede ayudarme?

Author: Nikolaus Gradwohl, 2010-06-23

8 answers

Para hash una cadena, use la clase incorporada 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);
  }
}

En el fragmento de código anterior, digest contiene la cadena hash y hex contiene una cadena ASCII hexadecimal con relleno cero izquierdo.

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-10-02 14:41:20

Esto ya está implementado en las libs de tiempo de ejecución.

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

En un entorno JEE6 + también se podría usar 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-12 13:39:01

No necesita necesariamente la biblioteca BouncyCastle. El siguiente código muestra cómo hacerlo usando el entero.Función 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);
    }
}

Agradecimientos especiales a user1452273 de este post: ¿Cómo hash alguna cadena con sha256 en Java?

¡Sigan con el buen trabajo !

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 11:47:01

Al usar hashcodes con cualquier proveedor de jce, primero intenta obtener un instancia del algoritmo, luego actualícelo con los datos que desea que se hash y cuando haya terminado, llame a digest para obtener el valor hash.

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

Puede usar el resumen para obtener una versión codificada base64 o hexadecimal de acuerdo con sus necesidades

 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-19 22:05:34

Java 8: Base64 disponible:

    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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-18 23:52:32

Supongo que está utilizando una versión relativamente antigua de Java sin SHA-256. Por lo tanto, debe agregar el proveedor de BouncyCastle a los 'Proveedores de seguridad' ya proporcionados en su versión de 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/ajaxhispano.com/template/agent.layouts/content.php on line 61
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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-11-19 22:31:56

Esto funcionará con "org.bouncycastle.útil.codificador.Hex " siguiente paquete

return new String(Hex.encode(digest));

Está en tarro de pastelillo.

 -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/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-07 12:37:29