aboutsummaryrefslogtreecommitdiffstats
path: root/vespajlib/src/main/java/com/yahoo/collections/MD5.java
blob: 6bd32b62b745369bdd12dcbfc25b49f2b1dbf78e (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// Copyright Vespa.ai. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.
package com.yahoo.collections;

import com.yahoo.text.Utf8;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Convenience class for hashing a String with MD5, and either returning
 * an int with the 4 LSBytes, or the whole 12-byte MD5 hash.
 * <p>
 * Note that instantiating this class can be expensive, so re-using instances
 * is a good idea.
 * <p>
 * This class is not thread safe.
 *
 * @author Einar M R Rosenvinge
 */
public class MD5 {

    public static final ThreadLocal<MessageDigest> md5 = new MD5Factory();

    private static class MD5Factory extends ThreadLocal<MessageDigest> {

        @Override
        protected MessageDigest initialValue() {
            return createMD5();
        }
    }

    private static MessageDigest createMD5() {
        try {
            return MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException(e);
        }
    }

    final private MessageDigest digester;

    public MD5() {
        try {
            digester = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            throw new AssertionError("MD5 algorithm not found.");
        }
    }

    public int hash(String s) {
        byte[] md5 = digester.digest(Utf8.toBytes(s));
        int hash = 0;
        assert (md5.length == 16);

        //produce an int by using only the 32 lsb:
        int byte1 = (((int) md5[12]) << 24) & 0xFF000000;
        int byte2 = (((int) md5[13]) << 16) & 0x00FF0000;
        int byte3 = (((int) md5[14]) << 8) & 0x0000FF00;
        int byte4 = (((int) md5[15])) & 0x000000FF;

        hash |= byte1;
        hash |= byte2;
        hash |= byte3;
        hash |= byte4;
        return hash;
    }

    public byte[] hashFull(String s) {
        return digester.digest(Utf8.toBytes(s));
    }

}