java如何使用SHA256算法对文件进行编码
时间: 2023-04-08 18:05:18 浏览: 94
Java可以使用MessageDigest类中的SHA-256算法对文件进行编码。具体实现可以参考以下代码:
```java
import java.io.*;
import java.security.*;
public class SHA256Example {
public static void main(String[] args) throws Exception {
String filename = "example.txt";
FileInputStream fis = new FileInputStream(filename);
MessageDigest md = MessageDigest.getInstance("SHA-256");
byte[] buffer = new byte[1024];
int numRead = 0;
do {
numRead = fis.read(buffer);
if (numRead > 0) {
md.update(buffer, 0, numRead);
}
} while (numRead != -1);
fis.close();
byte[] digest = md.digest();
System.out.println("SHA-256 hash of " + filename + ": " + bytesToHex(digest));
}
private static final char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for (int i = 0; i < bytes.length; i++) {
int v = bytes[i] & 0xFF;
hexChars[i * 2] = HEX_ARRAY[v >>> 4];
hexChars[i * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars);
}
}
```
其中,filename为要编码的文件名,可以根据实际情况进行修改。运行程序后,会输出文件的SHA-256哈希值。
阅读全文