|
7 | 7 | *******************************************************************************/ |
8 | 8 | package org.eclipse.rdf4j.query.algebra.evaluation.function.hash; |
9 | 9 |
|
10 | | -import java.math.BigInteger; |
11 | 10 | import java.security.MessageDigest; |
12 | 11 | import java.security.NoSuchAlgorithmException; |
13 | 12 |
|
|
23 | 22 | * @author jeen |
24 | 23 | */ |
25 | 24 | public abstract class HashFunction implements Function { |
26 | | - |
| 25 | +private final String HEX = "0123456789abcdef"; |
| 26 | + |
| 27 | + /** |
| 28 | + * Calculate hash value, represented as hexadecimal string. |
| 29 | + * |
| 30 | + * @param text text |
| 31 | + * @param algorithm name of the hash algorithm |
| 32 | + * @return hexadecimal string |
| 33 | + * @throws NoSuchAlgorithmException |
| 34 | + */ |
27 | 35 | protected String hash(String text, String algorithm) |
28 | 36 | throws NoSuchAlgorithmException |
29 | 37 | { |
30 | 38 | byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes()); |
31 | | - BigInteger bi = new BigInteger(1, hash); |
32 | | - String result = bi.toString(16); |
33 | | - if (result.length() % 2 != 0) { |
34 | | - return "0" + result; |
| 39 | + |
| 40 | + // convert to hexadecimal representation, with leading zeros |
| 41 | + char[] hex = new char[hash.length * 2]; |
| 42 | + for (int i = 0, j = 0; i < hex.length; ) { |
| 43 | + hex[i++] = HEX.charAt((hash[j] & 0xF0) >>> 4); |
| 44 | + hex[i++] = HEX.charAt(hash[j++] & 0x0F); |
35 | 45 | } |
36 | | - return result; |
| 46 | + return new String(hex); |
37 | 47 | } |
38 | 48 |
|
| 49 | + @Override |
39 | 50 | public abstract Literal evaluate(ValueFactory valueFactory, Value... args) |
40 | 51 | throws ValueExprEvaluationException; |
41 | | - |
42 | 52 | } |
0 commit comments