【发布时间】:2017-07-18 02:57:04
【问题描述】:
我们需要读取文件内容并将其转换为SHA256,然后再转换为Base64。
任何指针或示例代码都足够了,因为我是这个加密机制的新手。
提前致谢。
【问题讨论】:
-
转换为 SHA256:stackoverflow.com/questions/5531455/… 转换为 Base64:stackoverflow.com/questions/19743851/…
我们需要读取文件内容并将其转换为SHA256,然后再转换为Base64。
任何指针或示例代码都足够了,因为我是这个加密机制的新手。
提前致谢。
【问题讨论】:
您可以使用MessageDigest 转换为SHA256,并使用Base64 将其转换为Base64:
public static String encode(final String clearText) throws NoSuchAlgorithmException {
return new String(
Base64.getEncoder().encode(MessageDigest.getInstance("SHA-256").digest(clearText.getBytes(StandardCharsets.UTF_8))));
}
【讨论】:
使用 Java 8:
public static String fileSha256ToBase64(File file) throws NoSuchAlgorithmException, IOException {
byte[] data = Files.readAllBytes(file.toPath());
MessageDigest digester = MessageDigest.getInstance("SHA-256");
digester.update(data);
return Base64.getEncoder().encodeToString(digester.digest());
}
顺便说一句:SHA256 不是加密,它是散列。散列不需要密钥,加密需要。加密可以反转(使用密钥),散列不能。更多关于维基百科:https://en.wikipedia.org/wiki/Hash_function
【讨论】: