Skip to content

Commit

Permalink
Merge pull request #42601 from anuruddhal/master
Browse files Browse the repository at this point in the history
Fix SHA256 hash byte to string conversion
  • Loading branch information
anuruddhal authored Apr 26, 2024
2 parents 8b1ac03 + b38e669 commit 939d0cb
Showing 1 changed file with 30 additions and 6 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -40,12 +40,12 @@

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.math.BigInteger;
import java.net.URI;
import java.nio.charset.Charset;
import java.nio.file.FileSystem;
Expand All @@ -54,6 +54,7 @@
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
Expand Down Expand Up @@ -468,13 +469,36 @@ private static void extractBala(Path balaFilePath, Path balaFileDestPath, String
}

public static String checkHash(String filePath, String algorithm) throws CentralClientException {
MessageDigest md;
try {
byte[] data = Files.readAllBytes(Paths.get(filePath));
byte[] hash = MessageDigest.getInstance(algorithm).digest(data);
return new BigInteger(1, hash).toString(16);
} catch (IOException | NoSuchAlgorithmException e) {
throw new CentralClientException("Unable to calculate the hash value of the file: " + filePath);
md = MessageDigest.getInstance(algorithm);
} catch (NoSuchAlgorithmException e) {
throw new CentralClientException("Unable to calculate the hash value of the file " + filePath + ": "
+ e.getMessage());
}

try (InputStream is = new FileInputStream(filePath);
DigestInputStream dis = new DigestInputStream(is, md)) {
while (dis.read() != -1) {
}
md = dis.getMessageDigest();
return bytesToHex(md.digest());
} catch (RuntimeException | IOException e) {
throw new CentralClientException("Unable to calculate the hash value of the file " + filePath + ": "
+ e.getMessage());
}
}

private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (byte b : hash) {
String hex = Integer.toHexString(0xff & b);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}

static String getBearerToken(String accessToken) {
Expand Down

0 comments on commit 939d0cb

Please sign in to comment.