在Java中,如何将字节数组转换为十六进制数字字符串,同时保持前导零?

时间:2008-12-01 20:24:43

标签: java md5 hex

我正在使用一些示例java代码来制作md5哈希。一部分将结果从字节转换为十六进制数字的字符串:

byte messageDigest[] = algorithm.digest();     
StringBuffer hexString = new StringBuffer();
for (int i=0;i<messageDigest.length;i++) {
    hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
    }

但是,由于toHexString显然会从前导零中掉落,所以它并不常用。那么,从字节数组到保持前导零的十六进制字符串的最简单方法是什么?

28 个答案:

答案 0 :(得分:125)

查看Apache Commons Codec Hex.encodeHex。返回类型为char[],可以轻松转换为String。所以:

import org.apache.commons.codec.binary;

Hex.encodeHexString(messageDigest);

答案 1 :(得分:109)

您可以使用下面的那个。我用前导零字节和初始负字节测试了这个

public static String toHex(byte[] bytes) {
    BigInteger bi = new BigInteger(1, bytes);
    return String.format("%0" + (bytes.length << 1) + "X", bi);
}

如果您需要小写十六进制数字,请使用格式为String的"x"

答案 2 :(得分:97)

一种简单的方法是检查Integer.toHexString()输出的位数,并在需要时为每个字节添加前导零。像这样:

public static String toHexString(byte[] bytes) {
    StringBuilder hexString = new StringBuilder();

    for (int i = 0; i < bytes.length; i++) {
        String hex = Integer.toHexString(0xFF & bytes[i]);
        if (hex.length() == 1) {
            hexString.append('0');
        }
        hexString.append(hex);
    }

    return hexString.toString();
}

答案 3 :(得分:38)

使用DatatypeConverter.printHexBinary()。您可以在http://docs.oracle.com/javase/6/docs/api/javax/xml/bind/DatatypeConverter.html

中阅读其文档

例如:

byte bytes[] = {(byte)0, (byte)0, (byte)134, (byte)0, (byte)61};
System.out.println(javax.xml.bind.DatatypeConverter.printHexBinary(bytes));

将导致:

000086003D

答案 4 :(得分:32)

我喜欢Steve的提交,但他可以在没有几个变量的情况下完成并在此过程中保存了几行。

public static String toHexString(byte[] bytes) {
    char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for ( int j = 0; j < bytes.length; j++ ) {
        v = bytes[j] & 0xFF;
        hexChars[j*2] = hexArray[v/16];
        hexChars[j*2 + 1] = hexArray[v%16];
    }
    return new String(hexChars);
}

我喜欢这个是很容易看到它正在做什么(而不是依赖于一些神奇的BigInteger黑盒转换),你也可以免于担心像前导零和东西这样的角落情况。此例程采用每个4位半字节并将其转换为十六进制字符。它使用表查找,所以它可能很快。如果用逐位移位和AND替换v / 16和v%16可能会更快,但我现在懒得测试它。

答案 5 :(得分:21)

我发现Integer.toHexString有点慢。如果要转换许多字节,可能需要考虑构建包含“00”...“FF”的字符串数组,并使用整数作为索引。即。

hexString.append(hexArray[0xFF & messageDigest[i]]);

这样更快并确保正确的长度。只需要字符串数组:

String[] hexArray = {
"00","01","02","03","04","05","06","07","08","09","0A","0B","0C","0D","0E","0F",
"10","11","12","13","14","15","16","17","18","19","1A","1B","1C","1D","1E","1F",
"20","21","22","23","24","25","26","27","28","29","2A","2B","2C","2D","2E","2F",
"30","31","32","33","34","35","36","37","38","39","3A","3B","3C","3D","3E","3F",
"40","41","42","43","44","45","46","47","48","49","4A","4B","4C","4D","4E","4F",
"50","51","52","53","54","55","56","57","58","59","5A","5B","5C","5D","5E","5F",
"60","61","62","63","64","65","66","67","68","69","6A","6B","6C","6D","6E","6F",
"70","71","72","73","74","75","76","77","78","79","7A","7B","7C","7D","7E","7F",
"80","81","82","83","84","85","86","87","88","89","8A","8B","8C","8D","8E","8F",
"90","91","92","93","94","95","96","97","98","99","9A","9B","9C","9D","9E","9F",
"A0","A1","A2","A3","A4","A5","A6","A7","A8","A9","AA","AB","AC","AD","AE","AF",
"B0","B1","B2","B3","B4","B5","B6","B7","B8","B9","BA","BB","BC","BD","BE","BF",
"C0","C1","C2","C3","C4","C5","C6","C7","C8","C9","CA","CB","CC","CD","CE","CF",
"D0","D1","D2","D3","D4","D5","D6","D7","D8","D9","DA","DB","DC","DD","DE","DF",
"E0","E1","E2","E3","E4","E5","E6","E7","E8","E9","EA","EB","EC","ED","EE","EF",
"F0","F1","F2","F3","F4","F5","F6","F7","F8","F9","FA","FB","FC","FD","FE","FF"};

答案 6 :(得分:13)

我一直在寻找同样的东西......这里有一些好主意,但我运行了几个微基准测试。我发现以下是最快的(从Ayman以上修改过来,速度提高约2倍,比Steve高出约50%):

public static String hash(String text, String algorithm)
        throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
    return new BigInteger(1, hash).toString(16);
}

编辑:哎呀 - 错过了这与kgiannakakis的基本相同,因此可能会删除前导0.但是,将其修改为以下内容,它仍然是最快的:

public static String hash(String text, String algorithm)
        throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes());
    BigInteger bi = new BigInteger(1, hash);
    String result = bi.toString(16);
    if (result.length() % 2 != 0) {
        return "0" + result;
    }
    return result;
}

答案 7 :(得分:11)

static String toHex(byte[] digest) {
    StringBuilder sb = new StringBuilder();
    for (byte b : digest) {
        sb.append(String.format("%1$02X", b));
    }

    return sb.toString();
}

答案 8 :(得分:6)

String result = String.format("%0" + messageDigest.length + "s", hexString.toString())

鉴于您已经拥有的东西,这是最短的解决方案。如果您可以将字节数组转换为数字值,String.format可以同时将其转换为十六进制字符串。

答案 9 :(得分:5)

我会使用这样的东西来固定长度,比如哈希:

md5sum = String.format("%032x", new BigInteger(1, md.digest()));

掩码中的0执行填充...

答案 10 :(得分:5)

这个解决方案是一个较旧的学校,应该具有记忆效率。

public static String toHexString(byte bytes[]) {
    if (bytes == null) {
        return null;
    }

    StringBuffer sb = new StringBuffer();
    for (int iter = 0; iter < bytes.length; iter++) {
        byte high = (byte) ( (bytes[iter] & 0xf0) >> 4);
        byte low =  (byte)   (bytes[iter] & 0x0f);
        sb.append(nibble2char(high));
        sb.append(nibble2char(low));
    }

    return sb.toString();
}

private static char nibble2char(byte b) {
    byte nibble = (byte) (b & 0x0f);
    if (nibble < 10) {
        return (char) ('0' + nibble);
    }
    return (char) ('a' + nibble - 10);
}

答案 11 :(得分:5)

另一个选择

public static String toHexString(byte[]bytes) {
    StringBuilder sb = new StringBuilder(bytes.length*2);
    for(byte b: bytes)
      sb.append(Integer.toHexString(b+0x800).substring(1));
    return sb.toString();
}

答案 12 :(得分:5)

Guava也很简单:

BaseEncoding.base16().encode( bytes );

当Apache Commons不可用时,这是一个不错的选择。它还有一些很好的输出控件,如:

byte[] bytes = new byte[] { 0xa, 0xb, 0xc, 0xd, 0xe, 0xf };
BaseEncoding.base16().lowerCase().withSeparator( ":", 2 ).encode( bytes );
// "0a:0b:0c:0d:0e:0f"

答案 13 :(得分:4)

static String toHex(byte[] digest) {
    String digits = "0123456789abcdef";
    StringBuilder sb = new StringBuilder(digest.length * 2);
    for (byte b : digest) {
        int bi = b & 0xff;
        sb.append(digits.charAt(bi >> 4));
        sb.append(digits.charAt(bi & 0xf));
    }
    return sb.toString();
}

答案 14 :(得分:4)

为了保持前导零,这里有一个保罗建议的小变化(例如md5哈希):

public static String MD5hash(String text) throws NoSuchAlgorithmException {
    byte[] hash = MessageDigest.getInstance("MD5").digest(text.getBytes());
    return String.format("%032x",new BigInteger(1, hash));
}
哎呀,这看起来比艾曼提出的要差,对不起

答案 15 :(得分:3)

看起来concat和追加功能可能非常慢。以下对我来说要快得多(比我上一篇文章)。在构建输出时更改为char数组是加速输出的关键因素。我没有比较Brandon DuRette建议的Hex.encodeHex。

public static String toHexString(byte[] bytes) {
    char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char[] hexChars = new char[10000000];
    int c = 0;
    int v;
    for ( j = 0; j < bytes.length; j++ ) {
        v = bytes[j] & 0xFF;
        hexChars[c] = hexArray[v/16];
        c++;
        hexChars[c] = hexArray[v%16];
        c++;
    }
    return new String(hexChars, 0, c); }

答案 16 :(得分:2)

这是我用于MD5哈希的:

public static String getMD5(String filename)
        throws NoSuchAlgorithmException, IOException {
    MessageDigest messageDigest = 
        java.security.MessageDigest.getInstance("MD5");

    InputStream in = new FileInputStream(filename);

    byte [] buffer = new byte[8192];
    int len = in.read(buffer, 0, buffer.length);

    while (len > 0) {
        messageDigest.update(buffer, 0, len);
        len = in.read(buffer, 0, buffer.length);
    }
    in.close();

    return new BigInteger(1, messageDigest.digest()).toString(16);
}
编辑:我已经测试过了,我已经注意到了这一点也会减少尾随的零。但这只能在开始时发生,因此您可以与预期的长度进行比较并相应地填充。

答案 17 :(得分:2)

如果没有外部库,你可以减少写作:

String hex = (new HexBinaryAdapter()).marshal(md5.digest(YOUR_STRING.getBytes()))

答案 18 :(得分:2)

此解决方案不需要位移或掩码,查找表或外部库,并且只需要尽可能短:

byte[] digest = new byte[16];       

Formatter fmt = new Formatter();    
for (byte b : digest) { 
  fmt.format("%02X", b);    
}

fmt.toString()

答案 19 :(得分:1)

byte messageDigest[] = algorithm.digest();
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < messageDigest.length; i++) {
    String hexByte = Integer.toHexString(0xFF & messageDigest[i]);
    int numDigits = 2 - hexByte.length();
    while (numDigits-- > 0) {
        hexString.append('0');
    }
    hexString.append(hexByte);
}

答案 20 :(得分:0)

恕我直言,上面所有提供片段以删除前导零的解决方案都是错误的。

byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
    hexString.append(Integer.toHexString(0xFF & messageDigest[i]));
}    

根据这个片段,8位取自a中的字节数组 迭代,转换为整数(因为Integer.toHexString函数需要 int as argument)然后将该整数转换为相应的哈希值 值。因此,例如,如果你有二进制的00000001 00000001,根据 代码,hexString变量将0x11作为十六进制值 正确的值应为0x0101。因此,在计算MD5时,我们可能会得到哈希值 长度<32字节(因为缺少零)可能不满足 MD5哈希所做的加密唯一属性。

该问题的解决方案是用以下代码替换上面的代码片段 以下代码段:

byte messageDigest[] = algorithm.digest();
for (int i = 0; i < messageDigest.length; i++) {
    int temp=0xFF & messageDigest[i];
    String s=Integer.toHexString(temp);
    if(temp<=0x0F){
        s="0"+s;
    }
    hexString.append(s);
}

答案 21 :(得分:0)

这将为一个字节提供两个字符长字符串。

public String toString(byte b){
    final char[] Hex = new String("0123456789ABCDEF").toCharArray();
    return  "0x"+ Hex[(b & 0xF0) >> 4]+ Hex[(b & 0x0F)];
}

答案 22 :(得分:0)

你怎么能再从ascii转换回字节数组?

我按照以下代码转换为Jemenake给出的ascii。

public static String toHexString(byte[] bytes) {
    char[] hexArray = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
    char[] hexChars = new char[bytes.length * 2];
    int v;
    for ( int j = 0; j < bytes.length; j++ ) {
        v = bytes[j] & 0xFF;
        hexChars[j*2] = hexArray[v/16];
        hexChars[j*2 + 1] = hexArray[v%16];
    }
    return new String(hexChars);
}

答案 23 :(得分:0)

我的变种

    StringBuilder builder = new StringBuilder();
    for (byte b : bytes)
    {
        builder.append(Character.forDigit(b/16, 16));
        builder.append(Character.forDigit(b % 16, 16));
    }
    System.out.println(builder.toString());

它对我有用。

答案 24 :(得分:0)

这是一个错误的解决方案吗? (android java)

    // Create MD5 Hash
    MessageDigest digest = java.security.MessageDigest.getInstance("MD5");
    digest.update(s.getBytes());
    byte[] md5sum = digest.digest();
    BigInteger bigInt = new BigInteger(1, md5sum);
    String stringMD5 = bigInt.toString(16);
    // Fill to 32 chars
    stringMD5 = String.format("%32s", stringMD5).replace(' ', '0');
    return stringMD5;

所以基本上它用0替换空格。

答案 25 :(得分:0)

我很惊讶没有人提出以下解决方案:

StringWriter sw = new StringWriter();
com.sun.corba.se.impl.orbutil.HexOutputStream hex = new com.sun.corba.se.impl.orbutil.HexOutputStream(sw);
hex.write(byteArray);
System.out.println(sw.toString());

答案 26 :(得分:0)

或者您可以这样做:

byte[] digest = algorithm.digest();
StringBuilder byteContet = new StringBuilder();
for(byte b: digest){
 byteContent = String.format("%02x",b);
 byteContent.append(byteContent);
}

它简短,简单,基本上只是一种格式更改。

答案 27 :(得分:-1)

这也是等效的,但使用Apache util HexBin更简洁,其中代码缩减为

HexBin.encode(messageDigest).toLowerCase();