Java – バイトを16進数に変換する方法
Javaでは、 `String.format(”%02x “、bytes)`を使ってバイトを簡単に16進数に変換することができます。
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. 16進数のバイト – SHA-256
SHA-256アルゴリズムを使用してパスワードをハッシュするJavaの完全な例。
ByesToHex.java
package com.mkyong.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
参考文献
JavaDoc]。
https://docs.oracle.com/javase/7/docs/api/java/lang/String.html#format(java.lang.String,%20java.lang.Object…
)[String.format
JavaDoc]。リンク://java/java-sha-hashing-example/[Java SHAハッシングの例]