您可以使用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))));
}
Run Code Online (Sandbox Code Playgroud)
使用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());
}
Run Code Online (Sandbox Code Playgroud)
BTW:SHA256不是加密,而是哈希.散列不需要密钥,加密也是如此.加密可以反转(使用密钥),哈希不能.更多关于维基百科:https://en.wikipedia.org/wiki/Hash_function
| 归档时间: |
|
| 查看次数: |
7528 次 |
| 最近记录: |