PageRenderTime 81ms CodeModel.GetById 40ms app.highlight 6ms RepoModel.GetById 34ms app.codeStats 0ms

/src/mpv5/utils/text/MD5HashGenerator.java

http://mp-rechnungs-und-kundenverwaltung.googlecode.com/
Java | 76 lines | 44 code | 17 blank | 15 comment | 4 complexity | bfbd57eec46b1a530554fd9fce018090 MD5 | raw file
 1package mpv5.utils.text;
 2
 3//~--- JDK imports ------------------------------------------------------------
 4
 5import java.security.*;
 6
 7/**
 8 *
 9 * @author pertinax
10 */
11public class MD5HashGenerator {
12    private static final char[]     hexChars = {
13        '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'
14    };
15    static private MD5HashGenerator md5      = null;
16    private MessageDigest           md       = null;
17
18    /**
19     * Constructor is private so you must use the getInstance method
20     */
21    private MD5HashGenerator() throws NoSuchAlgorithmException {
22        md = MessageDigest.getInstance("MD5");
23    }
24
25    /**
26     * This returns the singleton instance
27     * @return
28     * @throws NoSuchAlgorithmException
29     */
30    public static MD5HashGenerator getInstance() throws NoSuchAlgorithmException {
31        if (md5 == null) {
32            md5 = new MD5HashGenerator();
33        }
34
35        return (md5);
36    }
37
38    public String hashData(char[] password) {
39        byte[] byteArray = new byte[password.length];
40
41        for (int i = 0; i < password.length; i++) {
42            byteArray[i] = (byte) password[i];
43        }
44
45        return hashData(byteArray);
46    }
47
48    public String hashData(byte[] dataToHash) {
49        return hexStringFromBytes((calculateHash(dataToHash)));
50    }
51
52    private byte[] calculateHash(byte[] dataToHash) {
53        md.update(dataToHash, 0, dataToHash.length);
54
55        return (md.digest());
56    }
57
58    public String hexStringFromBytes(byte[] b) {
59        String hex = "";
60        int    msb;
61        int    lsb = 0;
62        int    i;
63
64        // MSB maps to idx 0
65        for (i = 0; i < b.length; i++) {
66            msb = ((int) b[i] & 0x000000FF) / 16;
67            lsb = ((int) b[i] & 0x000000FF) % 16;
68            hex = hex + hexChars[msb] + hexChars[lsb];
69        }
70
71        return (hex);
72    }
73}
74
75
76//~ Formatted by Jindent --- http://www.jindent.com