SHA-512 hash - Java Security

Java examples for Security:SHA

Description

SHA-512 hash

Demo Code


//package com.java2s;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static void main(String[] argv) throws Exception {
        String password = "java2s.com";
        String salt = "java2s.com";
        System.out.println(hash(password, salt));
    }/*from   w w w. ja  va 2  s  .c  om*/

    private static int PBKDF2_ROUNDS = 1000;

    public static String hash(String password, String salt)
            throws NoSuchAlgorithmException {
        String hashedPassword = "";
        byte[] buffer = (password + salt).getBytes();
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update(buffer);
        byte[] digest = md.digest();
        for (int i = 0; i < digest.length; i++) {
            hashedPassword += Integer
                    .toString((digest[i] & 0xff) + 0x100, 16).substring(1)
                    .toUpperCase();
        }

        for (int round = 0; round < PBKDF2_ROUNDS; round++) {
            hashedPassword = pbkdf2(hashedPassword);
        }

        return hashedPassword;
    }

    public static String pbkdf2(String password)
            throws NoSuchAlgorithmException {
        String hashedPassword = "";
        byte[] buffer = password.getBytes();
        MessageDigest md = MessageDigest.getInstance("SHA-512");
        md.update(buffer);
        byte[] digest = md.digest();
        for (int i = 0; i < digest.length; i++) {
            hashedPassword += Integer
                    .toString((digest[i] & 0xff) + 0x100, 16).substring(1)
                    .toUpperCase();
        }
        return hashedPassword;
    }
}

Related Tutorials