All Downloads are FREE. Search and download functionalities are using the official Maven repository.

org.signal.libsignal.protocol.util.Hex Maven / Gradle / Ivy

There is a newer version: 0.62.0
Show newest version
//
// Copyright 2014-2016 Signal Messenger, LLC.
// SPDX-License-Identifier: AGPL-3.0-only
//

package org.signal.libsignal.protocol.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;

/** Utility for generating hex dumps. */
public class Hex {

  private static final char[] HEX_DIGITS = {
    '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'
  };

  public static String toString(byte[] bytes) {
    return toString(bytes, 0, bytes.length);
  }

  public static String toString(byte[] bytes, int offset, int length) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < length; i++) {
      appendHexCharWithPrefix(buf, bytes[offset + i]);
      buf.append(", ");
    }
    return buf.toString();
  }

  public static String toStringCondensed(byte[] bytes) {
    StringBuffer buf = new StringBuffer();
    for (int i = 0; i < bytes.length; i++) {
      appendHexChar(buf, bytes[i]);
    }
    return buf.toString();
  }

  public static byte[] fromStringCondensed(String encoded) throws IOException {
    final char[] data = encoded.toCharArray();
    final int len = data.length;

    if ((len & 0x01) != 0) {
      throw new IOException("Odd number of characters.");
    }

    final byte[] out = new byte[len >> 1];

    for (int i = 0, j = 0; j < len; i++) {
      int f = Character.digit(data[j], 16) << 4;
      j++;
      f = f | Character.digit(data[j], 16);
      j++;
      out[i] = (byte) (f & 0xFF);
    }

    return out;
  }

  public static byte[] fromStringCondensedAssert(String encoded) {
    try {
      return fromStringCondensed(encoded);
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  public static byte[] fromStringsCondensedAssert(String... encoded) {
    try {
      ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
      for (String next : encoded) {
        outputStream.write(fromStringCondensed(next));
      }
      return outputStream.toByteArray();
    } catch (IOException e) {
      throw new AssertionError(e);
    }
  }

  private static void appendHexCharWithPrefix(StringBuffer buf, int b) {
    buf.append("(byte)0x");
    appendHexChar(buf, b);
  }

  private static void appendHexChar(StringBuffer buf, int b) {
    buf.append(HEX_DIGITS[(b >> 4) & 0xf]);
    buf.append(HEX_DIGITS[b & 0xf]);
  }
}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy