Java - Как конвертировать байты в шестнадцатеричные
В Java вы можете использоватьString.format("%02x", bytes)
для простого преобразования байтов в шестнадцатеричный формат.
private static String bytesToHex(byte[] hashInBytes) { StringBuilder sb = new StringBuilder(); for (byte b : hashInBytes) { sb.append(String.format("%02x", b)); } return sb.toString(); }
Альтернативное решение.
private static String bytesToHex1(byte[] hashInBytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashInBytes.length; i++) { sb.append(Integer.toString((hashInBytes[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } private static String bytesToHex2(byte[] hashInBytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashInBytes.length; i++) { String hex = Integer.toHexString(0xff & hashInBytes[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } return sb.toString(); }
1. Байт в шестнадцатеричный формат - SHA-256
Полный пример Java для использования алгоритма SHA-256 для хеширования пароля.
ByesToHex.java
package com.example.hashing; import java.nio.charset.StandardCharsets; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class ByesToHex { public static void main(String[] args) throws NoSuchAlgorithmException { String password = "123456"; MessageDigest md = MessageDigest.getInstance("SHA-256"); byte[] hashInBytes = md.digest(password.getBytes(StandardCharsets.UTF_8)); System.out.println(bytesToHex(hashInBytes)); System.out.println(bytesToHex2(hashInBytes)); System.out.println(bytesToHex3(hashInBytes)); } private static String bytesToHex(byte[] hashInBytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashInBytes.length; i++) { sb.append(Integer.toString((hashInBytes[i] & 0xff) + 0x100, 16).substring(1)); } return sb.toString(); } private static String bytesToHex2(byte[] hashInBytes) { StringBuilder sb = new StringBuilder(); for (int i = 0; i < hashInBytes.length; i++) { String hex = Integer.toHexString(0xff & hashInBytes[i]); if (hex.length() == 1) sb.append('0'); sb.append(hex); } return sb.toString(); } private static String bytesToHex3(byte[] hashInBytes) { StringBuilder sb = new StringBuilder(); for (byte b : hashInBytes) { sb.append(String.format("%02x", b)); } return sb.toString(); } }
Выход
8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92 8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92