mustafa cantürk blog

SHA512 hashing on Java

Hello! For my school project, I had been tought of crypting passwords of users. Due to the fact that, SHA1 algorithm has security problems (link) , I have decided using a SHA2. SHA2 has 3 variants: SHA256, SHA384 and SHA512. While I was searching how to implement SHA2 on Java,  I have found this link.

For SHA512 that code works:

 
import java.security.*;
 
public class cryptotest {
    public static void main(String[] args) throws NoSuchAlgorithmException {
        MessageDigest md;
        String message = "password";
        try {
            md= MessageDigest.getInstance("SHA-512");
 
            md.update(message.getBytes());
            byte[] mb = md.digest();
            String out = "";
            for (int i = 0; i < mb.length; i++) {
                byte temp = mb[i];
                String s = Integer.toHexString(new Byte(temp));
                while (s.length() < 2) {
                    s = "0" + s;
                }
                s = s.substring(s.length() - 2);
                out += s;
            }
            System.out.println(out.length());
            System.out.println("CRYPTO: " + out);
 
        } catch (NoSuchAlgorithmException e) {
            System.out.println("ERROR: " + e.getMessage());
        }
    }
}

If you want to hash password with SHA256, you can change the line:

md= MessageDigest.getInstance("SHA-512");

to

md= MessageDigest.getInstance("SHA-256");

For others:

md= MessageDigest.getInstance("MD5");
md= MessageDigest.getInstance("SHA");
md= MessageDigest.getInstance("SHA-1");
md= MessageDigest.getInstance("SHA-384");
VN:F [1.9.11_1134]
Rating: 4.6/5 (9 votes cast)
SHA512 hashing on Java, 4.6 out of 5 based on 9 ratings
Category: Java, Programming
  • Pereira says:

    I changed the method and now i can used in my application
    Thanks!

    VA:F [1.9.11_1134]
    Rating: 5.0/5 (1 vote cast)
    VA:F [1.9.11_1134]
    Rating: -1 (from 3 votes)
    June 8, 2010 at 9:01 pm
  • JEROME says:

    This sample is very helpful !!

    Thank you for submitting IT

    VA:F [1.9.11_1134]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.11_1134]
    Rating: +1 (from 1 vote)
    April 6, 2011 at 6:09 pm
  • tamás says:

    Very helpful, thanks.

    VA:F [1.9.11_1134]
    Rating: 0.0/5 (0 votes cast)
    VA:F [1.9.11_1134]
    Rating: +1 (from 1 vote)
    May 3, 2013 at 8:41 pm

Your email address will not be published. Required fields are marked *

*


*

Comment Spam Protection by WP-SpamFree

web development