Skip to content

Commit ff89981

Browse files
committed
Add utility class for cryptographic hashes
1 parent 29d891f commit ff89981

File tree

1 file changed

+233
-0
lines changed

1 file changed

+233
-0
lines changed
Lines changed: 233 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,233 @@
1+
/*
2+
* #%L
3+
* SciJava Common shared library for SciJava software.
4+
* %%
5+
* Copyright (C) 2009 - 2014 Board of Regents of the University of
6+
* Wisconsin-Madison, Broad Institute of MIT and Harvard, and Max Planck
7+
* Institute of Molecular Cell Biology and Genetics.
8+
* %%
9+
* Redistribution and use in source and binary forms, with or without
10+
* modification, are permitted provided that the following conditions are met:
11+
*
12+
* 1. Redistributions of source code must retain the above copyright notice,
13+
* this list of conditions and the following disclaimer.
14+
* 2. Redistributions in binary form must reproduce the above copyright notice,
15+
* this list of conditions and the following disclaimer in the documentation
16+
* and/or other materials provided with the distribution.
17+
*
18+
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
19+
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
20+
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
21+
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR CONTRIBUTORS BE
22+
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
23+
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
24+
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
25+
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
26+
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
27+
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28+
* POSSIBILITY OF SUCH DAMAGE.
29+
* #L%
30+
*/
31+
32+
package org.scijava.util;
33+
34+
import java.io.UnsupportedEncodingException;
35+
import java.security.MessageDigest;
36+
import java.security.NoSuchAlgorithmException;
37+
38+
import javax.xml.bind.DatatypeConverter;
39+
40+
/**
41+
* Utility class for computing cryptographic hashes.
42+
*
43+
* @author Curtis Rueden
44+
* @author Johannes Schindelin
45+
*/
46+
public final class DigestUtils {
47+
48+
private final static char[] hex = { '0', '1', '2', '3', '4', '5', '6', '7',
49+
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
50+
51+
private DigestUtils() {
52+
// NB: Prevent instantiation of utility class.
53+
}
54+
55+
/**
56+
* Converts the given byte array to a string. UTF-8 encoding is used if
57+
* available, with the platform's default encoding as a fallback.
58+
*/
59+
public static String string(final byte[] bytes) {
60+
try {
61+
return new String(bytes, "UTF-8");
62+
}
63+
catch (final UnsupportedEncodingException exc) {
64+
return new String(bytes);
65+
}
66+
}
67+
68+
/**
69+
* Converts the given string to a byte array. UTF-8 encoding is used if
70+
* available, with the platform's default encoding as a fallback.
71+
*/
72+
public static byte[] bytes(final String s) {
73+
try {
74+
return s.getBytes("UTF-8");
75+
}
76+
catch (final UnsupportedEncodingException exc) {
77+
return s.getBytes();
78+
}
79+
}
80+
81+
/** Converts the given integer into a byte array. */
82+
public static byte[] bytes(final int i) {
83+
return new byte[] {
84+
(byte) (0xff & (i >>> 24)),
85+
(byte) (0xff & (i >>> 16)),
86+
(byte) (0xff & (i >>> 8)),
87+
(byte) (0xff & i),
88+
};
89+
}
90+
91+
/** Converts the given byte array to a hexidecimal string. */
92+
public static String hex(final byte[] bytes) {
93+
final char[] buffer = new char[bytes.length * 2];
94+
for (int i = 0; i < bytes.length; i++) {
95+
buffer[i * 2] = hex[(bytes[i] & 0xf0) >> 4];
96+
buffer[i * 2 + 1] = hex[bytes[i] & 0xf];
97+
}
98+
return new String(buffer);
99+
}
100+
101+
/** Converts the given byte array to a base64 string. */
102+
public static String base64(final byte[] bytes) {
103+
return DatatypeConverter.printBase64Binary(bytes);
104+
}
105+
106+
/**
107+
* Gets the Java hash code of the given string, as a byte array.
108+
*
109+
* @see String#hashCode()
110+
*/
111+
public static byte[] hash(final String s) {
112+
return bytes(s.hashCode());
113+
}
114+
115+
/**
116+
* Gets the hash code of the given byte array, as a byte array.
117+
*
118+
* @see String#hashCode()
119+
* @see #string(byte[])
120+
*/
121+
public static byte[] hash(final byte[] bytes) {
122+
// NB: We cannot use the hash code of the byte array directly,
123+
// because it is not deterministic. Primitive byte arrays use the
124+
// default Object implementation of hashCode(), which differs for
125+
// every object instance. We need a consistent hash code, so we
126+
// convert to String first, which fulfills this requirement.
127+
return hash(string(bytes));
128+
}
129+
130+
/** Gets the given byte array's SHA-1 checksum, or null if unavailable. */
131+
public static byte[] sha1(final byte[] bytes) {
132+
return digest("SHA-1", bytes);
133+
}
134+
135+
/** Gets the given byte array's MD5 checksum, or null if unavailable. */
136+
public static byte[] md5(final byte[] bytes) {
137+
return digest("MD5", bytes);
138+
}
139+
140+
/**
141+
* Gets the given byte array's hash value according to the specified
142+
* algorithm.
143+
*
144+
* @param algorithm The algorithm to use when generating the hash value.
145+
* @param bytes The byte array for which to compute the hash value.
146+
* @return The computed hash value, or null if the digest algorithm is not
147+
* available.
148+
* @see MessageDigest
149+
*/
150+
public static byte[] digest(final String algorithm, final byte[] bytes) {
151+
try {
152+
final MessageDigest digest = MessageDigest.getInstance(algorithm);
153+
digest.update(bytes);
154+
return digest.digest();
155+
}
156+
catch (final NoSuchAlgorithmException exc) {
157+
return null;
158+
}
159+
}
160+
161+
/**
162+
* Gets the given string's best available hash. Tries SHA-1 first, then MD5,
163+
* then Java hash code.
164+
*
165+
* @see #bytes(String)
166+
* @see #sha1(byte[])
167+
* @see #md5(byte[])
168+
* @see #hash(String)
169+
*/
170+
public static byte[] best(final String s) {
171+
final byte[] bytes = bytes(s);
172+
byte[] best = sha1(bytes);
173+
if (best == null) best = md5(bytes);
174+
if (best == null) best = hash(s);
175+
return best;
176+
}
177+
178+
/**
179+
* Gets the given byte array's best available hash. Tries SHA-1 first, then
180+
* MD5, then Java hash code.
181+
*
182+
* @see #sha1(byte[])
183+
* @see #md5(byte[])
184+
* @see #hash(byte[])
185+
*/
186+
public static byte[] best(final byte[] bytes) {
187+
byte[] best = sha1(bytes);
188+
if (best == null) best = md5(bytes);
189+
if (best == null) best = hash(bytes);
190+
return best;
191+
}
192+
193+
/**
194+
* Gets the hex string of the given string's best available hash.
195+
*
196+
* @see #best(String)
197+
* @see #hex(byte[])
198+
*/
199+
public static String bestHex(final String text) {
200+
return hex(best(text));
201+
}
202+
203+
/**
204+
* Gets the hex string of the given byte array's best available hash.
205+
*
206+
* @see #best(byte[])
207+
* @see #hex(byte[])
208+
*/
209+
public static String bestHex(final byte[] bytes) {
210+
return hex(best(bytes));
211+
}
212+
213+
/**
214+
* Gets the base64 string of the given string's best available hash.
215+
*
216+
* @see #best(String)
217+
* @see #base64(byte[])
218+
*/
219+
public static String bestBase64(final String text) {
220+
return base64(best(text));
221+
}
222+
223+
/**
224+
* Gets the base64 string of the given byte array's best available hash.
225+
*
226+
* @see #best(byte[])
227+
* @see #base64(byte[])
228+
*/
229+
public static String bestBase64(final byte[] bytes) {
230+
return base64(best(bytes));
231+
}
232+
233+
}

0 commit comments

Comments
 (0)