1
24 package net.sf.jasperreports.engine.util;
25
26 import java.io.UnsupportedEncodingException;
27 import java.security.MessageDigest;
28 import java.security.NoSuchAlgorithmException;
29 import java.util.UUID;
30
31 import net.sf.jasperreports.engine.JRRuntimeException;
32
33
36 public final class DigestUtils
37 {
38 public static final String EXCEPTION_MESSAGE_KEY_MD5_NOT_AVAILABLE = "util.digest.md5.not.available";
39
40 private static final DigestUtils INSTANCE = new DigestUtils();
41
42 public static DigestUtils instance()
43 {
44 return INSTANCE;
45 }
46
47 private DigestUtils()
48 {
49 }
50
51 public MD5Digest md5(String text)
52 {
53 try
54 {
55 MessageDigest digest = MessageDigest.getInstance("MD5");
56 byte[] digestBytes = digest.digest(text.getBytes("UTF-8"));
57 long low = (long) (digestBytes[0] &0xFF) << 56
58 | (long) (digestBytes[1] &0xFF) << 48
59 | (long) (digestBytes[2] &0xFF) << 40
60 | (long) (digestBytes[3] &0xFF) << 32
61 | (long) (digestBytes[4] &0xFF) << 24
62 | (long) (digestBytes[5] &0xFF) << 16
63 | (long) (digestBytes[6] &0xFF) << 8
64 | (long) (digestBytes[7] &0xFF) << 0;
65 long high = (long) (digestBytes[8] &0xFF) << 56
66 | (long) (digestBytes[9] &0xFF) << 48
67 | (long) (digestBytes[10] &0xFF) << 40
68 | (long) (digestBytes[11] &0xFF) << 32
69 | (long) (digestBytes[12] &0xFF) << 24
70 | (long) (digestBytes[13] &0xFF) << 16
71 | (long) (digestBytes[14] &0xFF) << 8
72 | (long) (digestBytes[15] &0xFF) << 0;
73 return new MD5Digest(low, high);
74 }
75 catch (NoSuchAlgorithmException e)
76 {
77 throw
78 new JRRuntimeException(
79 EXCEPTION_MESSAGE_KEY_MD5_NOT_AVAILABLE,
80 (Object[])null,
81 e);
82 }
83 catch (UnsupportedEncodingException e)
84 {
85
86 throw new JRRuntimeException(e);
87 }
88 }
89
90 public UUID deriveUUID(UUID base, String text)
91 {
92 MD5Digest textMD5 = md5(text);
93 long md5Low = textMD5.getLow();
94 long md5High = textMD5.getHigh();
95 return deriveUUID(base, md5Low, md5High);
96 }
97
98 public UUID deriveUUID(UUID base, long maskLow, long maskHigh)
99 {
100 long baseMostSig = base.getMostSignificantBits();
101 long baseLeastSig = base.getLeastSignificantBits();
102
103 return new UUID(
104 baseMostSig ^ (maskLow & 0xffffffffffff0fffl),
105 baseLeastSig ^ (maskHigh & 0x3fffffffffffffffl)
106 );
107 }
108
109 }
110