简体   繁体   English

生成整数列表的MD5哈希

[英]Generate MD5 hash for a list of integers

I have a list of Integer 我有一个整数列表

List<Integer> listInt;

I want to generate a MD5 hash for the listInt how should I approach the problem, I know that I have to use 我想为listInt生成MD5哈希,我应该如何处理该问题,我知道我必须使用

MessageDigest.getInstance("MD5").digest(byte[])

How do I convert the listInt to bytes. 如何将listInt转换为字节。

You need to convert each integer value to 4 bytes, forming an array of bytes that is 4*listInt.size() bytes long. 您需要将每个整数值转换为4个字节,从而形成一个字节数组,该数4*listInt.size()个字节。

One way to do this is to make use of NIO's ByteBuffer class: 一种方法是利用NIO的ByteBuffer类:

ByteBuffer buf = ByteBuffer.allocate(4*listInt.size());
buf.order(ByteOrder.BIG_ENDIAN);
for (int i = 0; i < listInt.size(); ++i)
    buf.putInt(listInt.get(i));
byte[] barr = buf.array();

Note that there are two common ways of converting an array of integers to an array of bytes. 请注意,有两种将整数数组转换为字节数组的常用方法。 The difference, however, is simply the choice of Endianness . 但是,区别只是Endianness的选择。 Some people choose to calculate the Big Endian byte representation of integers; 有人选择计算整数的Big Endian字节表示形式。 others choose to calculate the little Endian representation of integers. 其他人选择计算整数的小字节序表示。 It doesn't matter which method you pick as long as you calculate the byte representation of each integer consistently. 只要选择一致地计算每个整数的字节表示形式,选择哪种方法都没有关系。

First create a method that converts an int to a byte array: 首先创建一个将int转换为字节数组的方法:

  public static final byte[] intToByteArray(int value) 
  { 
    return new byte[]  { (byte)(value >>> 24), (byte)(value >> 16 & 0xff), (byte)(value >> 8 & 0xff), (byte)(value & 0xff) };
  }

Then use a ByteArrayOutputStream. 然后使用ByteArrayOutputStream。

ByteArrayOutputStream baos = new ByteArrayOutputStream();

for (int i = 0; i < listInt.size(); i++)
{
  baos.write(intToByteArray(listInt[i]), 0, 4);
}

You will then get your full byte array to perform the md5 hash on by: 然后,您将通过以下方式获取完整字节数组以执行md5哈希:

byte[] fullByteArray = baos.toByteArray();
byte data[] = new byte[listInt.size()*4];
for (int i = 0; i < listInt.size(); i++) {
  data[i*4]   = new Integer(listInt.get(i) >> 24).byteValue();
  data[i*4+1] = new Integer(listInt.get(i) >> 16).byteValue();
  data[i*4+2] = new Integer(listInt.get(i) >> 8).byteValue();
  data[i*4+3] = listInt.get(i).byteValue();
}

Sample code running: http://ideone.com/YJZVj 运行示例代码: http : //ideone.com/YJZVj

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM