001// Copyright 2021 Paul Schaub, @maybeWeCouldStealAVan, @Dave L. 002// SPDX-FileCopyrightText: 2021 Paul Schaub <vanitasvitae@fsfe.org> 003// 004// SPDX-License-Identifier: Apache-2.0 005 006package sop.util; 007 008public class HexUtil { 009 010 private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray(); 011 012 /** 013 * Encode a byte array to a hex string. 014 * 015 * @see <a href="https://stackoverflow.com/a/9855338"> 016 * How to convert a byte array to a hex string in Java?</a> 017 * @param bytes bytes 018 * @return hex encoding 019 */ 020 public static String bytesToHex(byte[] bytes) { 021 char[] hexChars = new char[bytes.length * 2]; 022 for (int j = 0; j < bytes.length; j++) { 023 int v = bytes[j] & 0xFF; 024 hexChars[j * 2] = HEX_ARRAY[v >>> 4]; 025 hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F]; 026 } 027 return new String(hexChars); 028 } 029 030 /** 031 * Decode a hex string into a byte array. 032 * 033 * @see <a href="https://stackoverflow.com/a/140861"> 034 * Convert a string representation of a hex dump to a byte array using Java?</a> 035 * @param s hex string 036 * @return decoded byte array 037 */ 038 public static byte[] hexToBytes(String s) { 039 int len = s.length(); 040 byte[] data = new byte[len / 2]; 041 for (int i = 0; i < len; i += 2) { 042 data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) 043 + Character.digit(s.charAt(i + 1), 16)); 044 } 045 return data; 046 } 047}