|
1 | | -/******************************************************************************* |
| 1 | +/** ***************************************************************************** |
2 | 2 | * Copyright (c) 2015 Eclipse RDF4J contributors, Aduna, and others. |
3 | 3 | * All rights reserved. This program and the accompanying materials |
4 | 4 | * are made available under the terms of the Eclipse Distribution License v1.0 |
5 | 5 | * which accompanies this distribution, and is available at |
6 | 6 | * http://www.eclipse.org/org/documents/edl-v10.php. |
7 | | - *******************************************************************************/ |
| 7 | + ****************************************************************************** */ |
8 | 8 | package org.eclipse.rdf4j.query.algebra.evaluation.function.hash; |
9 | 9 |
|
| 10 | +import java.math.BigInteger; |
10 | 11 | import java.security.MessageDigest; |
11 | 12 | import java.security.NoSuchAlgorithmException; |
12 | 13 |
|
|
18 | 19 |
|
19 | 20 | /** |
20 | 21 | * Abstract hash function |
21 | | - * |
| 22 | + * |
22 | 23 | * @author jeen |
23 | 24 | */ |
24 | 25 | public abstract class HashFunction implements Function { |
25 | | -private final String HEX = "0123456789abcdef"; |
26 | | - |
| 26 | + |
27 | 27 | /** |
28 | 28 | * Calculate hash value, represented as hexadecimal string. |
29 | | - * |
| 29 | + * |
30 | 30 | * @param text text |
31 | 31 | * @param algorithm name of the hash algorithm |
32 | | - * @return hexadecimal string |
33 | | - * @throws NoSuchAlgorithmException |
| 32 | + * @return hexadecimal string (padded with leading zeros if needed) |
| 33 | + * @throws NoSuchAlgorithmException |
34 | 34 | */ |
35 | 35 | protected String hash(String text, String algorithm) |
36 | | - throws NoSuchAlgorithmException |
37 | | - { |
| 36 | + throws NoSuchAlgorithmException { |
38 | 37 | byte[] hash = MessageDigest.getInstance(algorithm).digest(text.getBytes()); |
| 38 | + BigInteger bi = new BigInteger(1, hash); |
39 | 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); |
45 | | - } |
46 | | - return new String(hex); |
| 40 | + return String.format("%0" + hash.length * 2 + "x", bi); |
47 | 41 | } |
48 | 42 |
|
49 | 43 | @Override |
50 | 44 | public abstract Literal evaluate(ValueFactory valueFactory, Value... args) |
51 | | - throws ValueExprEvaluationException; |
| 45 | + throws ValueExprEvaluationException; |
52 | 46 | } |
0 commit comments