如何在 Java 中使用 SHA-512 对密码进行哈希处理?密码、如何在、SHA、Java

2023-09-06 22:33:57 作者:诗酒趁年华

我一直在研究 Java 字符串加密技术,不幸的是我没有找到任何好的教程,如何在 Java 中使用 SHA-512 对字符串进行哈希处理;我阅读了一些关于 MD5 和 Base64 的博客,但它们并没有我想的那么安全(实际上,Base64 不是一种加密技术),所以我更喜欢 SHA-512.

I've been investigating a bit about Java String encryption techniques and unfortunately I haven't find any good tutorial how to hash String with SHA-512 in Java; I read a few blogs about MD5 and Base64, but they are not as secure as I'd like to (actually, Base64 is not an encryption technique), so I prefer SHA-512.

推荐答案

你可以将它用于 SHA-512

you can use this for SHA-512

import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public String get_SHA_512_SecurePassword(String passwordToHash, String salt){
    String generatedPassword = null;
    try {
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update(salt.getBytes(StandardCharsets.UTF_8));
        byte[] bytes = md.digest(passwordToHash.getBytes(StandardCharsets.UTF_8));
        StringBuilder sb = new StringBuilder();
        for(int i=0; i< bytes.length ;i++){
            sb.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));
        }
        generatedPassword = sb.toString();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    return generatedPassword;
}