Java 远程url文件sha256加密
java
public static String getSHA256(String filePath) throws Exception {
InputStream fis = null;
URL url = new URL(filePath);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[1024];
int responseCode = connection.getResponseCode();
if (responseCode == HttpURLConnection.HTTP_OK) {
fis = connection.getInputStream();
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
digest.update(buffer, 0, bytesRead);
}
fis.close();
} else {
throw new IOException("HTTP request failed with response code: " + responseCode);
}
byte[] sha256Bytes = digest.digest();
StringBuilder sb = new StringBuilder();
for (byte b : sha256Bytes) {
sb.append(String.format("%02x", b));
}
String sha256 = sb.toString();
return sha256;
}