Password Hashing In Java

In this post you will learn how to do hashing of password in Java. This is hashing for any String value. For security reasons it is very important to hash password before storing in the database.

If you want to watch video on this then here you go - https://youtu.be/qSTZVlo2lr0

Here is source code to achieve hashing of password in Java.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.example.hashing;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class PasswordHashing {

 public static void main(String[] args) {
  System.out.println(doHashing("12345678"));
 }

 public static String doHashing (String password) {
  try {
   MessageDigest messageDigest = MessageDigest.getInstance("MD5");
   
   messageDigest.update(password.getBytes());
   
   byte[] resultByteArray = messageDigest.digest();
   
   StringBuilder sb = new StringBuilder();
   
   for (byte b : resultByteArray) {
    sb.append(String.format("%02x", b));
   }
   
   return sb.toString();
   
  } catch (NoSuchAlgorithmException e) {
   e.printStackTrace();
  }
  
  return "";
 }
 
}

0 Comments