HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Optimizing Java SHA-512 String-to-Hash Generator

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
shajavahashgeneratoroptimizingstring512

Problem

In an attempt to learn Java and SHA-2 I created a very simple String-to-SHA512 generator. Here is the code:

package main;
import java.util.Scanner;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA512_String_Hash {
    public static void main(String args[]) throws NoSuchAlgorithmException {
        Scanner inputScanner = new Scanner(System.in);
        System.out.print("Text Input: ");
        String input = inputScanner.next();

        MessageDigest objSHA = MessageDigest.getInstance("SHA-512");
        byte[] bytSHA = objSHA.digest(input.getBytes());
        BigInteger intNumber = new BigInteger(1, bytSHA);
        String strHashCode = intNumber.toString(16);

        while (strHashCode.length() < 128) {
            strHashCode = "0" + strHashCode;
        }
        System.out.println("SHA-512: \n" + strHashCode);
    }
}


Since I am new to SHA-512 in Java, I do not know the optimal (for performance and more importantly security) way to create a SHA-512 hash generator.

TLDR— How could the performance and security of this code be improved?

Solution

-
You should extract the hex encoding into its own method.

See How to convert a byte array to a hex string in Java? for various implementations.

-
input.getBytes() uses the locale dependent legacy encoding. So you won't get reproducible results on different systems. Specify an encoding explicitly, I recommend utf-8.

Context

StackExchange Code Review Q#136630, answer score: 4

Revisions (0)

No revisions yet.