我写了下面这个程序来在Java中计算字符串的SHA-256哈希值:
public class ToHash {
public static void main(String[] args) {
byte[] data = "test".getBytes("UTF8");
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data);
System.out.println(new BASE64Encoder().encode(hash));
}
}
好的,那很好。在下一步中,我想以一种接受文件并计算其哈希值的方式来开发它。 我的解决方案是将整个文件读入字符串数组中,然后在该字符串数组上调用 digest()
方法。 但是有两个问题:
我不知道如何将整个文件读入数组? 目前我认为必须逐行读取文件并将新行附加到数组中!
上述方法对于大文件需要大量内存!
这是我目前用来读取文件的程序:
public class ToHash {
public static void main(String[] args) throws NoSuchAlgorithmException, UnsupportedEncodingException, FileNotFoundException, IOException {
// TODO code application logic here
// The name of the file to open.
String fileName = "C:\\Users\\ghasemi\\Desktop\\1.png";
BufferedReader br = null;
try {
String sCurrentLine;
br = new BufferedReader(new FileReader(fileName));
while ((sCurrentLine = br.readLine()) != null) {
byte[] data = sCurrentLine.getBytes("UTF8");
System.out.println(new BASE64Encoder().encode(data));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
}
似乎没有一种方法可以让 BufferedReader
对象通过一次调用读取整个文件。
digest.update()
方法中,我们将读取的数据附加到先前数据的末尾,因此对于大文件,我们需要大量的内存(RAM)。 - Ebrahim Ghasemidata
是一个打字错误。 - user207421