在Java中创建Base64编码的SHA-256哈希

May*_*ary 3 java oracle11g

我们需要读取文件内容并将其转换为SHA256,然后将其转换为Base64.

任何指针或示例代码都足够了,因为我是这种加密机制的新手.

提前致谢.

Flo*_*yle 5

您可以使用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)


lbn*_*dev 5

使用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