×

How to encrypt password in Java

Every software program needs a username and password to identify a legitimate user. A username can be any number of things, including an email address or a string of characters. But extreme caution must be exercised when creating a password. Because a user's password is stored in the database as plain text when they set it, anyone with appropriate credentials can access the system and read the information. It is not at all secure to store plain text in the database in its current state. The database may be breached by hackers, who then take the passwords. The user's password is encrypted using a variety of encryption algorithms to protect its security. The plain text password is saved in an encrypted form in the database using various encryption methods.

We use the hashing method to store the data in the database securely.

Java Hashing techniques

Specific algorithms produce the encrypted hash value on the user-provided plain text password. A password can be encrypted using various hashing methods supported by Java programming.

MD5 Hashing Procedure

The hashing method known as MD5 (Message Digest) is particularly well-liked. It is a cryptographic hash function that produces a hash value of 128 bits. A message of any length can be entered into the cryptographic hash function algorithm MD5, which converts it into a message with a fixed length of 16 bytes. In Java programming, this approach is described in Java. Security package.

Program for encrypting password using MD5 procedure

EncryptedMD5.java

import java.security.NoSuchAlgorithmException; 
import java.security.MessageDigest; 
public class EncryptedMD5 
{ 
/* Driver Code */ 
public static void main(String[] args) 
{ 
String pd = "Rohith@113"; 
String ed = null; 
try 
{ 
MessageDigest m1 = MessageDigest.getInstance("MD5"); 
/* Use the MD5 update() function to add plain-text password bytes to the digest. */ 
m1.update(pd.getBytes()); 
/*The hash value should be converted to bytes.*/ 
byte[] bt = m1.digest(); 
/*Decimal bytes are contained in the bytes array. Changing the format to hexadecimal. */
StringBuilder str = new StringBuilder(); 
for(int i=0; i< bt.length ;i++) 
{ 
str.append(Integer.toString((bt[i] & 0xff) + 0x100, 16).substring(1)); 
} 
ed = str.toString(); 
} 
catch (NoSuchAlgorithmException e) 
{ 
e.printStackTrace(); 
} 
/* Displaying the unencrypted and encrypted passwords. */ 
System.out.println (" Original password: " + pd); 
System.out.println("Encrypted password using MD5: " + ed); 
} 
}

Output

How to encrypt password in Java

Explanation

The MessageDigest class is implemented in Java. Security package, as shown in the code above. The byte array that the MD5 returns must be transformed into a readable hexadecimal format.

Although the MD5 hashing method is simple and quick to use, it is also vulnerable to dictionary or brute force attacks.

SHA256

The Secure Hash Algorithm is SHA. The 32-bit plain-text password is transformed into a fixed size 256-bit hash value using a cryptographic algorithm. The Java. Security package's MessageDiagest class is used to create this hashing method. It employs one-way encryption. The passphrase cannot be decrypted once it has been encrypted. The National Security Agency developed SHA-2 in 2001 as a replacement for SHA-1. The SHA-256 algorithm is one variant of SHA-2. The patented cryptographic hash algorithm SHA-256 produces a 256-bit value.

Program for encrypting password using SHA256 procedure

SHA256.java

// importing math package to use BigInterger to store 32-bit integers
import java. math.BigInteger; 
import java.nio.charset.StandardCharsets; 
// importing Message digest library from the security package 
//Message package is used to represent fixed numeric values
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
public class SHA256 
{ 
public static byte[] getSHA(String input) throws NoSuchAlgorithmException 
{ 
/* Use the SHA-256 update() function to add plain-text password bytes to the digest. */ 
MessageDigest m = MessageDigest.getInstance("SHA-256"); 
/* digest() method called to calculate message digest of input and return array of byte */ 
return m.digest(input.getBytes(StandardCharsets.UTF_8)); 
} 
public static String toHex(byte[] hash) 
{ 
/* Convert byte array of hash into digest */ 
BigInteger nr = new BigInteger(1, hash); 
/* Convert the digest into hex value */ 
StringBuilder hS = new StringBuilder(nr.toString(16)); 
while (hS.length() < 32) 
{ 
hS.insert(0, '0'); 
} 
return hS.toString(); 
} 
/* Main section where execution of the program is started*/ 
public static void main(String args[]) 
{ 
try 
{ 
String s1 = "rohith113"; 
System.out.println("\n" + s1 + " : " + toHex(getSHA(s1))); 
String s2 = "hashtrial"; 
System.out.println("\n" + s2 + " : " + toHex(getSHA(s2))); 
} 
catch (NoSuchAlgorithmException en) 
{ 
System.out.println("Exception is 
thrown if thee is incorrect algorithm: " + en); 
} 
} 
}

Output

How to encrypt password in Java

Explanation

The MessageDigest class instance is used in the code above to create a SHA256 hash. A byte array produced by the SHA256 algorithm must be transformed into a readable hexadecimal representation. Finally, the hash value is shown encrypted.

SHA512 MD5 Hashing Technique

The MessageDiagest class of the Java. The 64-bit plain-text password is transformed into a fixed-size 512-bit hash value using SHA512 using a cryptographic algorithm. A security package is also used to implement this hashing method.

Program for encrypting password using SHA512 MD5 procedure

SHA512.java

import java . math.BigInteger; 
import java.nio.charset.StandardCharsets; 
import java.security.MessageDigest; 
import java.security.NoSuchAlgorithmException; 
public class SHA512 
{
public static byte[] getSHA(String input) throws NoSuchAlgorithmException 
{ 
MessageDigest m = MessageDigest.getInstance ( "SHA-512" ) ; 
return m.digest (input.getBytes(StandardCharsets.UTF_8)); 
} 
public static String toHexaStr(byte[] h) 
{ 
BigInteger n = new BigInteger(1, h); 
StringBuilder ht = new StringBuilder(n.toString(16)); 
while (ht.length() < 32) 
{ 
ht.insert ( 0 , '0' ) ; 
} 
return ht.toString ( ); 
} 
public static void main ( String args [ ] ) 
{ 
try 
{ 
// Using s1 
String s1 = " Rohith@113 " ; 
System.out.println( " \n " + s1 + " : " + toHexaStr(getSHA(s1))); 
String s2 = " hashtrial " ; 
System. out.println ( " \n " + s2 + " : " + toHexaStr(getSHA(s2))); 
} 
catch (NoSuchAlgorithmException ex) 
{ 
System.out.println(" Exception is thrown due to wrong algorithm : " + ex ) ; 
} 
} 
} 

Output

How to encrypt password in Java

SALT AND BASE 64 Technique

The hash value is produced using plain text passwords and salt values using the password-based encryption method. And after that, a Base64 string is created from the hash value. The salt value comprises random data produced by a Random class instance from the java util package.

Program for encryption using SALT and BASE 64 technique

SaltEncryption.java

import java . util . *;
import java . security . NoSuchAlgorithmException ; 
import java . security . SecureRandom ; 
import java . security . spec .InvalidKeySpecException; 
import java . util . Arrays ; 
import java . util . Base64 ; 
import java . util . Random ; 
import javax . crypto . SecretKeyFactory ; 
import javax . crypto . spec . PBEKeySpec ; 
public class SaltEncrpytion 
{ 
public static void main ( String [ ] args ) 
{ 
// Random password 
String pass = "R!@#$%^&*"; 
// A salt value is generated which is stored in the database 
String salt_value = PassBasedEnc.getSaltvalue( 30 ) ; 
// Encrypted password is generated 
String encrypted_password = PassBasedEnc . generateSecurePassword ( pass, salt_value); 
System.out.println("Plain text password = " + pass); 
System.out.println("Secure password = " + encrypted_password); 
System.out.println("Salt value = " + salt_value); 
Boolean status = PassBasedEnc.verifyUserPassword(pass,encrypted_password,salt_value); 
if(status==true) 
System.out.println ( " Both the passwords are matched " ) ; 
else 
System.out.println ( " Both the passwords are not matched " ) ; 
} 
} 
class PassBasedEnc 
{ 
private static final Random r = new SecureRandom(); 
private static final String c = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; 
private static final int re = 10000; 
private static final int length_key = 256; 
public static String getSaltvalue(int length) 
{ 
StringBuilder final_value = new StringBuilder(length); 
for (int i = 0; i < length; i++) 
{ 
final_value.append(c.charAt(r.nextInt(c.length()))); 
} 
return new String(final_value); 
} 
public static byte[] hash(char[] pass, byte[] salt) 
{ 
PBEKeySpec sp = new PBEKeySpec(pass, salt, re, length_key); 
Arrays.fill(pass, Character.MIN_VALUE); 
try 
{ 
SecretKeyFactory srf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); 
return srf.generateSecret(sp).getEncoded(); 
} 
catch ( NoSuchAlgorithmException | InvalidKeySpecException e ) 
{ 
throw new AssertionError ( " Error raised at the time of hashing : " + e.getMessage() , e) ; 
} 
finally 
{ 
sp.clearPassword () ; 
} 
} 
public static String generateSecurePassword (String pass , String salt ) 
{ 
String final_value = null ; 
byte[] secure_password = hash ( pass . toCharArray() , salt . getBytes()) ; 
final_value = Base64 . getEncoder ( ) . encodeToString ( secure_password ) ; 
return final_value ; 
} 
public static boolean verifyUserPassword ( String provided_password , 
String secured_password , String salt ) 
{ 
boolean final_value = false ; 
String newSecurePassword = generateSecurePassword (provided_password , salt ) ; 
final_value = newSecurePassword . equalsIgnoreCase(secured_password) ; 
return final_value ; 
} 
}

Output

How to encrypt password in Java

Explanation

The program's driver code is found in the class PassEncTech4. There are 4 methods defined in the PassBasedEnc class. The first function, getSaltvalue(), uses the Random class from the util package to generate the value. Then, the hash() function is defined, with the byte array as the return type. The generateSecurePassword() function employs the hash() method with a plain-text password and salt value. The verifyUserPassword() method is then used to compare the two passwords.


Related Topics

Read the XLSX file in Java

Excel files contain cells; reading an excel file in Java differs from reading a word file. JDK doesn't have a direct API that can read or write Word or Excel...

3 minutes read.

Copy data/content from one file to another in java

In this article, you will be acknowledged about how to copy data or content from one file to another file. Also, you will be acknowledged about the classes and methods...

3 minutes read.

How to create a linked list in Java

Introduction: The linked listing is one type of linear statistics shaped like an array. Not like arrays, linked listing factors aren't stored in a contiguous place. The elements have linked...

3 minutes read.

JDK | Java Development Kit

Java Development Kit (JDK) The Java Development Kit is a software development environment used to create Java applications. The JDK includes JRE (Java Runtime Environment), an interpreter (java), a compiler (javac),...

3 minutes read.

Java LinkedHashSet

LinkedHashSet in Java with Example Java LinkedHashSet extends HashSet and Implements the Set interface. It doesn’t contain only duplicate values like HashSet. It also permits the null elements. It maintains the order...

5 minutes read.

Java instance variable

An instance in object-oriented programming (OOP) is a particular implementation of any object. Each realized version of an item, which might vary in several ways, is an instance. Instantiation is...

3 minutes read.

Java String replaceFirst() method

This method replace the first substring with user specified String. Syntax: public String replaceFirst(String Regexp, String Replacement) Parameter: Regexp : Regular Expression Replacement : the String which would replace found expression Return: a string Java String replaceFirst()...

1 minute read.

Use Of Adapter class in Java

An adapter class in Java enables listener interfaces to be implemented by default. The Delegation Event Model is where the idea of listener interfaces first appeared. It is one of...

3 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

Print Matrix Diagonally in Java

The aim is to print the elements of a matrix of size n*n in some kind of a diagonal pattern. Input : mat[3][3] = {{1, 2, 3},                      {4, 5, 6},                      {7,...

3 minutes read.

Balanced Parentheses in Java

One of the frequent programming issues, commonly referred to as the Balanced brackets issue, is the problem with the balanced parenthesis. Interviewers frequently provide this task, in which we must...

5 minutes read.

Memory Areas in Java

Let’s have a look at how memory management in Java works. We will be going to discuss how the objects get destroyed, the working of a garbage collector, and things...

5 minutes read.

Various operations on the Queue using Stack in Java

The Java Collections Framework's core data structures are the Stack and Queue. They are used to store and retrieve identical data in a presentation sequence. These two linear data structures...

7 minutes read.

Java String compareTo() Method

compareTo() method is used to compare the two specified Strings based on the alphabetical order(lexicographical order) of their characters.It returns positive number ,negative number or 0 Syntax: public int compareTo(String anotherString) Parameters: anotherString: the...

2 minutes read.

Java Public Keyword

A Java access modifier is a public keyword. It can be applied to classes, constructors, methods, and variables. It is the type of access modifier that is least constrained. A...

4 minutes read.

Java Math ceil() Method

The ceil() method of Math class returns the smallest double value which is closest to negative infinity and is greater than or equal to the argument. Syntax: public static double ceil(double a) Parameters: The...

2 minutes read.

Method chaining in Java

Method chaining in Java is the act of calling a series of methods one after the other. The sole distinction between it and function Object () constructor chaining is the difference...

3 minutes read.

Java file Writer

File Writer: It is used to write all the data from text files. It inherits the properties from the Output Stream class. It is meant for writing characters. It is meant...

4 minutes read.

Java 8 Consumer Interface in Java

The Consumer Interface is used to implement the functional programming in Java. The Consumer Interface indicates a function that accepts a single input and outputs a result. These functions don’t...

2 minutes read.

Java Integer reverse() method

The reverse() method of Java Integer class returns the value obtained by reversing the order of the bits in the 2’s complement binary representation. Syntax public static int reverse (int i)  Parameters The parameter...

1 minute read.