001/*
002 * Copyright (C) 2022-2023 The Prometheus jmx_exporter Authors
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017/*
018 * This product includes software based on Stackoverflow
019 * Code : toHex() method
020 * Author : maybeWeCouldStealAVan
021 * Reference: https://stackoverflow.com/questions/9655181/how-to-convert-a-byte-array-to-a-hex-string-in-java
022 */
023
024package io.prometheus.jmx.common.http.authenticator;
025
026public class HexString {
027
028    private static final char[] HEX_ARRAY = "0123456789abcdef".toCharArray();
029
030    /**
031     * Constructor
032     */
033    private HexString() {
034        // DO NOTHING
035    }
036
037    /**
038     * Method to convert a byte array to a lowercase hexadecimal String
039     *
040     * @param bytes bytes
041     * @return the return value
042     */
043    public static String toHex(byte [] bytes) {
044        char[] hexChars = new char[bytes.length * 2];
045        for (int i = 0, j = 0; i < bytes.length; i++) {
046            hexChars[j++] = HEX_ARRAY[(0xF0 & bytes[i]) >>> 4];
047            hexChars[j++] = HEX_ARRAY[0x0F & bytes[i]];
048        }
049        return new String(hexChars).toLowerCase();
050    }
051}