Commit | Line | Data |
---|---|---|
f433d153 NR |
1 | package be.nikiroo.utils; |
2 | ||
3 | import java.io.UnsupportedEncodingException; | |
4 | import java.security.MessageDigest; | |
5 | import java.security.NoSuchAlgorithmException; | |
6 | ||
7 | /** | |
8 | * Small class to easily hash some values in a few different ways. | |
9 | * <p> | |
10 | * Does <b>not</b> handle the salt itself, you have to add it yourself. | |
11 | * | |
12 | * @author niki | |
13 | */ | |
14 | public class HashUtils { | |
15 | /** | |
16 | * Hash the given value. | |
17 | * | |
18 | * @param value | |
19 | * the value to hash | |
20 | * | |
21 | * @return the hash that can be used to confirm a value | |
22 | * | |
23 | * @throws RuntimeException | |
24 | * if UTF-8 support is not available (!) or SHA-512 support is | |
25 | * not available | |
26 | * @throws NullPointerException | |
27 | * if email or pass is NULL | |
28 | */ | |
29 | static public String sha512(String value) { | |
30 | return hash("SHA-512", value); | |
31 | } | |
32 | ||
33 | /** | |
34 | * Hash the given value. | |
35 | * | |
36 | * @param value | |
37 | * the value to hash | |
38 | * | |
39 | * @return the hash that can be used to confirm the a value | |
40 | * | |
41 | * @throws RuntimeException | |
42 | * if UTF-8 support is not available (!) or MD5 support is not | |
43 | * available | |
44 | * @throws NullPointerException | |
45 | * if email or pass is NULL | |
46 | */ | |
47 | static public String md5(String value) { | |
48 | return hash("MD5", value); | |
49 | } | |
50 | ||
51 | /** | |
52 | * Hash the given value. | |
53 | * | |
54 | * @param algo | |
55 | * the hash algorithm to use ("MD5" and "SHA-512" are supported) | |
56 | * @param value | |
57 | * the value to hash | |
58 | * | |
59 | * @return the hash that can be used to confirm a value | |
60 | * | |
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 | |
66 | */ | |
67 | static private String hash(String algo, String value) { | |
68 | try { | |
69 | MessageDigest md = MessageDigest.getInstance(algo); | |
70 | md.update(value.getBytes("UTF-8")); | |
71 | byte byteData[] = md.digest(); | |
72 | ||
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); | |
79 | } | |
80 | ||
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); | |
87 | } | |
88 | } | |
89 | } |