Question

I need to calculate the SHA 256 for my password.

i already know that I can user the common codec from apache but this is not allowed in where i am working

I tried to make a simple function to return the sha 256 from a plain text, which is:

public static String getSHA1(String plainText) {
        MessageDigest md;
        try {
            md = MessageDigest.getInstance("SHA-256");

            md.update(plainText.getBytes());
            StringBuffer hexString = new StringBuffer();
            for (int i = 0; i < md.digest().length; i++) {
                hexString.append(Integer.toHexString(0xFF & md.digest()[i]));
            }
            return hexString.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

my problem is whatever the input is, the result is the same. i always got this result

e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855

I can calculate the sha 256 online using this website http://onlinemd5.com/

but i need to calculate it from my code.

your help is appreciated and lovely.

Was it helpful?

Solution

From the Javadoc for digest():

Completes the hash computation by performing final operations such as padding. The digest is reset after this call is made.

Call digest() once and put the results into a variable.

(By the way, had you searched for the digest, which is always a good idea whenever you get a fixed result, you would have seen that it's the SHA-256 digest for the empty string.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top