1 package be
.nikiroo
.utils
;
3 import java
.io
.UnsupportedEncodingException
;
4 import java
.security
.MessageDigest
;
5 import java
.security
.NoSuchAlgorithmException
;
8 * Small class to easily hash some values in a few different ways.
10 * Does <b>not</b> handle the salt itself, you have to add it yourself.
14 public class HashUtils
{
16 * Hash the given value.
21 * @return the hash that can be used to confirm a value
23 * @throws RuntimeException
24 * if UTF-8 support is not available (!) or SHA-512 support is
26 * @throws NullPointerException
27 * if email or pass is NULL
29 static public String
sha512(String value
) {
30 return hash("SHA-512", value
);
34 * Hash the given value.
39 * @return the hash that can be used to confirm the a value
41 * @throws RuntimeException
42 * if UTF-8 support is not available (!) or MD5 support is not
44 * @throws NullPointerException
45 * if email or pass is NULL
47 static public String
md5(String value
) {
48 return hash("MD5", value
);
52 * Hash the given value.
55 * the hash algorithm to use ("MD5" and "SHA-512" are supported)
59 * @return the hash that can be used to confirm a value
61 * @throws RuntimeException
62 * if UTF-8 support is not available (!) or the algorithm
63 * support is not available
64 * @throws NullPointerException
65 * if email or pass is NULL
67 static private String
hash(String algo
, String value
) {
69 MessageDigest md
= MessageDigest
.getInstance(algo
);
70 md
.update(value
.getBytes("UTF-8"));
71 byte byteData
[] = md
.digest();
73 StringBuffer hexString
= new StringBuffer();
74 for (int i
= 0; i
< byteData
.length
; i
++) {
75 String hex
= Integer
.toHexString(0xff & byteData
[i
]);
76 if (hex
.length() % 2 == 1)
77 hexString
.append('0');
78 hexString
.append(hex
);
81 return hexString
.toString();
82 } catch (NoSuchAlgorithmException e
) {
83 throw new RuntimeException(algo
+ " hashing not available", e
);
84 } catch (UnsupportedEncodingException e
) {
85 throw new RuntimeException(
86 "UTF-8 encoding is required in a compatible JVM", e
);