Produce a string hexdump of src, for debug output.

    Input: bytestring; output: text string
435716
def hexdump(src, length=8, colorize=False):
    
    if not src:
        return str(src)
    if type(src) is not bytes:
        raise yubico_exception.InputError('Hexdump \'src\' must be bytestring (got %s)' % type(src))
    offset = 0
    result = ''
    for this in group(src, length):
        if colorize:
            last, this = this[-1], this[:-1]
            colors = DumpColors()
            color = colors.get('RESET')
            if ord_byte(last) & yubikey_defs.RESP_PENDING_FLAG:
                # write to key
                color = colors.get('BLUE')
            elif ord_byte(last) & yubikey_defs.SLOT_WRITE_FLAG:
                color = colors.get('GREEN')
            hex_s = color + ' '.join(["%02x" % ord_byte(x) for x in this]) + colors.get('RESET')
            hex_s += " %02x" % ord_byte(last)
        else:
            hex_s = ' '.join(["%02x" % ord_byte(x) for x in this])
        result += "%04X   %s\n" % (offset, hex_s)
        offset += length
    return result
556429
def string(self, *args):
        
        data = self.bytes(*args)
        if data is not None:
            return data.rstrip(b"\x00").decode('utf-8')
201393
private static String bytesToHex(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int i = 0; i < bytes.length; i++) {
            int v = bytes[i] & 0xFF;
            hexChars[i * 2] = hexArray[v >>> 4];
            hexChars[i * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
724861
public static String encodeHexString(byte[] bytes) {
        char[] hexChars = new char[bytes.length * 2];
        for (int j = 0; j < bytes.length; j++) {
            int v = bytes[j] & 0xFF;
            hexChars[j * 2] = hexArray[v >>> 4];
            hexChars[j * 2 + 1] = hexArray[v & 0x0F];
        }
        return new String(hexChars);
    }
1022726
public static String toHexStringPadded(byte[] src, int offset, int length) {
        return toHexStringPadded(new StringBuilder(length << 1), src, offset, length).toString();
    }
584254
public static String hexDump(String prefix, byte[] data) {
        byte byte_value;

        StringBuffer str = new StringBuffer(data.length * 3);

        str.append(prefix);

        for (int i = 0; i < data.length; i += 16) {
            // dump the header: 00000000:
            String offset = Integer.toHexString(i);

            // "0" left pad offset field so it is always 8 char's long.
            str.append("  ");
            for (int offlen = offset.length(); offlen < 8; offlen++) {
                str.append("0");
            }
            str.append(offset);
            str.append(":");

            // dump hex version of 16 bytes per line.
            for (int j = 0; (j < 16) && ((i + j) < data.length); j++) {
                byte_value = data[i + j];

                // add spaces between every 2 bytes.
                if ((j % 2) == 0) {
                    str.append(" ");
                }

                // dump a single byte.
                byte high_nibble = (byte) ((byte_value & 0xf0) >>> 4);
                byte low_nibble = (byte) (byte_value & 0x0f);

                str.append(HEX_TABLE[high_nibble]);
                str.append(HEX_TABLE[low_nibble]);
            }

            // IF THIS IS THE LAST LINE OF HEX, THEN ADD THIS
            if (i + 16 > data.length) {
                // for debugging purposes, I want the last bytes always padded
                // over so that the ascii portion is correctly positioned
                int last_row_byte_count = data.length % 16;
                int num_bytes_short = 16 - last_row_byte_count;
                // number of spaces to add = (num bytes remaining * 2 spaces per byte) + (7 - (num bytes % 2))
                int num_spaces = (num_bytes_short * 2) + (7 - (last_row_byte_count / 2));
                for (int v = 0; v < num_spaces; v++) {
                    str.append(" ");
                }
            }

            // dump ascii version of 16 bytes
            str.append("  ");

            for (int j = 0; (j < 16) && ((i + j) < data.length); j++) {
                char char_value = (char) data[i + j];

                // RESOLVE (really want isAscii() or isPrintable())
                //if (Character.isLetterOrDigit(char_value))
                if (isPrintableChar(char_value)) {
                    str.append(String.valueOf(char_value));
                } else {
                    str.append(".");
                }
            }

            // new line
            str.append("\n");
        }

        // always trim off the last newline
        str.deleteCharAt(str.length() - 1);

        return (str.toString());
    }
658251
private static String byte2hex(byte[] bytes) {
        char[] hexChars =
                {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b',
                        'c', 'd', 'e', 'f'};

        StringBuffer sb = new StringBuffer();
        for (byte b : bytes) {
            sb.append(hexChars[b >> 4 & 0xf]);
            sb.append(hexChars[b & 0xf]);
        }

        return new String(sb);
    }
965292
public static void main(String[] args) {
    for (int i = 0; i < args.length; i++)
      System.out.println("'" + args[i] + "' becomes '" + obfuscate(args[i]) + "'");
  }

  /**
   * Takes a string and returns an obfuscated string with no more than 2x a many characters as the
   * original. Only works in the DEV environment.
   */
  public static String obfuscate(String plaintext) {
    String blargtext = StringMan.encodeBytesToString(mangleArray(plaintext.getBytes()));
    blargtext = StringMan.compressHexString(blargtext);
    return blargtext;
  }

  /** Opposite of {@link #obfuscate(String)} */
  public static String clarify(String blargtext) {
    if (blargtext == null)
      return null;
    byte blargBytes[] = decodeStringToBytes(blargtext);
    String plaintext = new String(mangleArray(blargBytes));
    return plaintext;
  }

  /** Inlined from StringManipulator due to static init circular references, called by clarify */
  private static byte[] decodeStringToBytes(String hex) {
    hex = decompressHexString(hex);
    int stringLength = hex.length();
    byte[] b = new byte[stringLength / 2];
    for (int i = 0, j = 0; i < stringLength; i += 2, j++) {
      int high = charToNibble(hex.charAt(i));
      int low = charToNibble(hex.charAt(i + 1));
      b[j] = (byte) ((high << 4) | low);
    }
    return b;
  }

  /** Inlined from StringManipulator due to static init circular references, called by clarify */
  private static int charToNibble(char c) {
    if ('0' <= c && c <= '9')
      return c - '0';
    else if ('a' <= c && c <= 'f')
      return c - 'a' + 0xa;
    else if ('A' <= c && c <= 'F')
      return c - 'A' + 0xa;
    else
      throw new IllegalArgumentException("Invalid hex character: " + c);
  }

  /** Inlined from StringManipulator due to static init circular references, called by clarify */
  private static String decompressHexString(String in) {
    StringBuffer out = new StringBuffer();
    for (int i = 0; i < in.length(); i++) {
      char thisChar = in.charAt(i);
      if (thisChar != '^') {
        out.append(thisChar);
      } else {
        thisChar = in.charAt(i + 1);
        int count = "abcdefghijklmnopqrstuvwxyz01234567890".indexOf(in.charAt(i + 2));
        for (int j = 0; j < count; j++)
          out.append(thisChar);
        i += 2;
      }
    }
    return out.toString();
  }

  /**
   * Takes a given byte array and mangles it by XOR'ing it with a secret garbage hash. It is
   * reversible, so calling mangleArray(mangleArray(blah)) will return the original array.
   * 
   * @return the mangled array (Same size as the input array)
   */
  private static byte[] mangleArray(byte plainBytes[]) {
    if (plainBytes == null)
      return null;
    byte mangled[] = new byte[plainBytes.length];
    byte hash[] = SUPER_SECRET_MANGLE_STRING.getBytes();
    for (int i = 0; i < plainBytes.length; i++) {
      byte current = (byte) (plainBytes[i] ^ hash[i % hash.length]);
      mangled[i] = current;
    }
    return mangled;
  }

}
427441
public static String hexDump(String label, byte[] bytes) {
        final int modulo = 16;
        final int brk = modulo / 2;
        int indent = (label == null) ? 0 : label.length();

        StringBuffer sb = new StringBuffer(indent + 1);

        while (indent > 0) {
            sb.append(" ");
            indent--;
        }

        String ind = sb.toString();

        if (bytes == null) {
            return null;
        }

        sb = new StringBuffer(bytes.length * 4);

        StringBuffer cb = new StringBuffer(16);
        boolean nl = true;
        int i = 0;

        for (i = 1; i <= bytes.length; i++) {
            // start of line?
            if (nl) {
                nl = false;

                if (i > 1) {
                    sb.append(ind);
                } else if (label != null) {
                    sb.append(label);
                }

                String ha = Integer.toHexString(i - 1);

                for (int j = ha.length(); j <= 8; j++) {
                    sb.append("0");
                }

                sb.append(ha).append(" ");
            }

            sb.append(" ");

            int c = (bytes[i - 1] & 0xFF);
            String hx = Integer.toHexString(c).toUpperCase();

            if (hx.length() == 1) {
                sb.append("0");
            }

            sb.append(hx);
            cb.append((c < 0x21 || c > 0x7e) ? '.' : (char) (c));

            if ((i % brk) == 0) {
                sb.append(" ");
            }

            if ((i % modulo) == 0) {
                sb.append("|").append(cb).append("|\n");
                nl = true;
                cb = new StringBuffer(16);
            }
        }

        int mod = i % modulo;

        if (mod != 1) {
            // Fill the rest of the line
            while (mod <= modulo) {
                sb.append("   ");

                if ((mod % brk) == 0) {
                    sb.append(" ");
                }

                mod++;
            }

            sb.append("|").append(cb).append("|\n");
        }

        return sb.toString();
    }
1244228
public static String getHexdump(IoBuffer in, int lengthLimit) {
        if (lengthLimit == 0) {
            throw new IllegalArgumentException("lengthLimit: " + lengthLimit + " (expected: 1+)");
        }

        boolean truncate = in.remaining() > lengthLimit;
        int size;
        if (truncate) {
            size = lengthLimit;
        }
        else {
            size = in.remaining();
        }

        if (size == 0) {
            return "empty";
        }

        StringBuilder out = new StringBuilder(in.remaining() * 3 - 1);

        int mark = in.position();

        // fill the first
        int byteValue = in.get() & 0xFF;
        out.append((char) highDigits[byteValue]);
        out.append((char) lowDigits[byteValue]);
        size--;

        // and the others, too
        for (; size > 0; size--) {
            out.append(' ');
            byteValue = in.get() & 0xFF;
            out.append((char) highDigits[byteValue]);
            out.append((char) lowDigits[byteValue]);
        }

        in.position(mark);

        if (truncate) {
            out.append("...");
        }

        return out.toString();
    }
269518
def debugDumpString(output, str):
    
    if output is not None: output.flush()
    libxml2mod.xmlDebugDumpString(output, str)
1072718
def encode_string(data, encoding='hex'):
    '''
    
    '''
    if six.PY2:
        return data.encode(encoding)
    else:
        if isinstance(data, str):
            data = bytes(data, 'utf-8')
        return codecs.encode(data, encoding).decode('ascii')
1164058
def hexdump( src, length=16, sep='.', start = 0):
	'''
	
	'''
	result = [];

	# Python3 support
	try:
		xrange(0,1);
	except NameError:
		xrange = range;

	for i in xrange(0, len(src), length):
		subSrc = src[i:i+length];
		hexa = '';
		isMiddle = False;
		for h in xrange(0,len(subSrc)):
			if h == length/2:
				hexa += ' ';
			h = subSrc[h];
			if not isinstance(h, int):
				h = ord(h);
			h = hex(h).replace('0x','');
			if len(h) == 1:
				h = '0'+h;
			hexa += h+' ';
		hexa = hexa.strip(' ');
		text = '';
		for c in subSrc:
			if not isinstance(c, int):
				c = ord(c);
			if 0x20 <= c < 0x7F:
				text += chr(c);
			else:
				text += sep;
		if start == 0:
			result.append(('%08x:  %-'+str(length*(2+1)+1)+'s  |%s|') % (i, hexa, text));
		else:
			result.append(('%08x(+%04x):  %-'+str(length*(2+1)+1)+'s  |%s|') % (start+i, i, hexa, text));
	return '\n'.join(result);
86379
@SuppressWarnings("unused")
    private static final void dump(IoBuffer data) {
        log.debug("Hex: {}", data.getHexDump());
        int pos = data.position();
        byte[] bar = new byte[data.limit() - data.position()];
        data.get(bar);
        log.debug("Str {}", new String(bar));
        bar = null;
        data.position(pos);
    }
117501
def _create_hexdump(src, start_offset=0, length=16):
        
        FILTER = "".join((len(repr(chr(x))) == 3) and chr(x) or "." for x in range(256))
        pattern = "{{0:04X}}   {{1:<{0}}}  {{2}}\n".format(length * 3)

        # Convert raw data to str (Python 3 compatibility)
        src = to_str(src, "latin-1")

        result = []
        for i in range(0, len(src), length):
            s = src[i : i + length]
            hexa = " ".join("{0:02X}".format(ord(x)) for x in s)
            printable = s.translate(FILTER)
            result.append(pattern.format(i + start_offset, hexa, printable))

        return "".join(result)
1192653
public static final byte[] fromHex(String hexDump)
    {
        List<Integer> list = new ArrayList<>();
        String[] lines = hexDump.split("\n");
        if (lines.length < 2)
        {
            throw new IllegalArgumentException("not a hex dump");
        }
        if (!lines[0].contains(Title))
        {
            throw new IllegalArgumentException("not a hex dump");
        }
        for (int ll=1;ll<lines.length;ll++)
        {
            String line = lines[ll];
            int i1 = line.indexOf(':');
            if (i1 == -1)
            {
                throw new IllegalArgumentException("not a hex dump");
            }
            int i2 = line.indexOf("  ", i1+2);
            if (i2 == -1)
            {
                throw new IllegalArgumentException("not a hex dump");
            }
            String[] fields = line.substring(i1+2, i2).split(" ");
            for (int ii=0;ii<fields.length;ii++)
            {
                list.add(Integer.parseInt(fields[ii], 16));
            }
        }
        byte[] bytes = new byte[list.size()];
        for (int ii=0;ii<bytes.length;ii++)
        {
            bytes[ii] = list.get(ii).byteValue();
        }
        return bytes;
    }
1373819
def write(self, data, debug_info=None):
        
        self.num_write_bytes += len(data)
        if self.debug:
            if not debug_info:
                debug_info = str(len(data))
            sys.stderr.write("%s: WRITE %s:\n%s\n" %(
                    self.__class__.__name__,
                    debug_info,
                    pyhsm.util.hexdump(data)
                    ))
        return self.ser.write(data)