Comment hacher une chaîne avec sha256 en Java?
Comment hacher une chaîne avec sha256 en Java ? Est-ce que quelqu'un connaît une bibliothèque gratuite pour cela ?
10 answers
SHA-256 n'est pas un "encodage" - c'est un hachage à sens unique.
Vous convertissez essentiellement la chaîne en octets (par exemple en utilisant text.getBytes(StandardCharsets.UTF_8)
), puis hachez les octets. À noter que le résultat du hachage serait - aussi être des données binaires arbitraires, et si vous voulez représenter que dans une chaîne, vous devez utiliser base64 ou hex... n'essayez pas d'utiliser le constructeur String(byte[], String)
.
Par exemple
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
Je pense que la solution la plus simple est d'utiliser Apache Codec Commun:
String sha256hex = org.apache.commons.codec.digest.DigestUtils.sha256Hex(stringText);
Une autre alternative est Guavaqui a une suite facile à utiliser de Hachage utilitaires. Par exemple, pour hacher une chaîne en utilisant SHA256 comme chaîne hexadécimale, vous feriez simplement:
final String hashed = Hashing.sha256()
.hashString("your input", StandardCharsets.UTF_8)
.toString();
Exemple Complet de hachage à la chaîne comme une autre chaîne.
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);
}
}
Si vous utilisez Java 8, vous pouvez encoder la byte[]
en faisant
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(text.getBytes(StandardCharsets.UTF_8));
String encoded = Base64.getEncoder().encodeToString(hash);
Convertir une chaîne Java en hachage Sha-256
import java.security.MessageDigest;
public class CodeSnippets {
public static String getSha256(String value) {
try{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(value.getBytes());
return bytesToHex(md.digest());
} catch(Exception ex){
throw new RuntimeException(ex);
}
}
private static String bytesToHex(byte[] bytes) {
StringBuffer result = new StringBuffer();
for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
return result.toString();
}
}
J'ai tracé le code Apache via DigestUtils
et sha256
semble par défaut java.security.MessageDigest
pour le calcul. Apache n'implémente pas de solution indépendante sha256
. Je cherchais une implémentation indépendante pour comparer avec la bibliothèque java.security
. À titre d'information seulement.
String hashWith256(String textToHash) {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] byteOfTextToHash = textToHash.getBytes(StandardCharsets.UTF_8);
byte[] hashedByetArray = digest.digest(byteOfTextToHash);
String encoded = Base64.encode(hashedByetArray);
return encoded;
}
Voici une façon un peu plus performante de transformer le digest en une chaîne hexadécimale:
private static final char[] hexArray = "0123456789abcdef".toCharArray();
public static String getSHA256(String data) {
StringBuilder sb = new StringBuilder();
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
byte[] byteData = md.digest();
sb.append(bytesToHex(byteData);
} catch(Exception e) {
e.printStackTrace();
}
return sb.toString();
}
private static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return String.valueOf(hexChars);
}
Quelqu'un connaît-il un moyen plus rapide en Java?
Vous pouvez utiliser MessageDigest de la manière suivante:
public static String getSHA256(String data){
StringBuffer sb = new StringBuffer();
try{
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(data.getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
} catch(Exception e){
e.printStackTrace();
}
return sb.toString();
}