Skip to content

Commit 00823bf

Browse files
committed
Convert bytes to hex string with leading zeros
Signed-off-by: Bart Hanssens <bart.hanssens@fedict.be>
1 parent 6df9a5f commit 00823bf

1 file changed

Lines changed: 18 additions & 8 deletions

File tree

  • core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash

core/queryalgebra/evaluation/src/main/java/org/eclipse/rdf4j/query/algebra/evaluation/function/hash/HashFunction.java

Lines changed: 18 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,6 @@
77
*******************************************************************************/
88
package org.eclipse.rdf4j.query.algebra.evaluation.function.hash;
99

10-
import java.math.BigInteger;
1110
import java.security.MessageDigest;
1211
import java.security.NoSuchAlgorithmException;
1312

@@ -23,20 +22,31 @@
2322
* @author jeen
2423
*/
2524
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+
*/
2735
protected String hash(String text, String algorithm)
2836
throws NoSuchAlgorithmException
2937
{
3038
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);
3545
}
36-
return result;
46+
return new String(hex);
3747
}
3848

49+
@Override
3950
public abstract Literal evaluate(ValueFactory valueFactory, Value... args)
4051
throws ValueExprEvaluationException;
41-
4252
}

0 commit comments

Comments
 (0)