×

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

Java program to find frequency of characters in a string

In this article, you will understand the how to find the frequency of characters in strings by using Java programming language. Along with this, you will understand the hashing concept...

3 minutes read.

Java copy file

There are for the most part 3 methods for duplicating documents utilizing java language. They are as given underneath: Utilizing File StreamUtilizing FileChannel ClassUtilizing Files class. 1. Using File Stream: Here we are...

5 minutes read.

Java vs Go

Java: Java is an object oriented programming language. It is also known as multi threaded language. It was designed by James gosling in the year 1995. We can also say that...

4 minutes read.

Best Java IDE

Applications for desktop, workplace, smartphone, and the internet can be created using Java, one of the most popular programming languages. Java will undoubtedly be a popular programming language for so...

5 minutes read.

Java Math toDegrees() Method

The toDegrees() method of Java Math class converts a radian angle to an approximately equivalent angle measured in degrees. Syntax: public static double toDegrees(double angrad) Parameters: The parameter ‘angrad ‘represents an angle measured in...

2 minutes read.

How to Round Double Float up to Two Decimal Places in Java

It indicates 15 digits just after the decimal place in Java whenever a double data type is used in front of a variable. For example, when representing rupees and other...

4 minutes read.

How to Print array in Java?

A Java array is a data structure that allows us to hold components of the same data type. An array's items are kept in a single memory region. As a...

6 minutes read.

Java vs JavaScript

Java Vs JavaScript Java and JavaScript, both play an important role in the field of Computer Technology. Most people think JavaScript is a part of Java. But it is not entirely...

4 minutes read.

Java Boolean booleanValue() method

The booleanValue() method of Java Boolean class returns a Boolean value for the specified Boolean argument. Syntax public Boolean booleanValue() Parameters NA Return Value This method returns the primitive value of specified Boolean object. Example 1 public class...

2 minutes read.

String Palindrome Program in Java

String Palindrome Program in Java The palindrome is a string, phrase, word, number, or other sequences of characters that can be read in both directions i.e. forward (left to right) and...

11 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Java callable example

What is callable in Java? Callable is an interface that is present in Java. There are two methods for constructing threads: one is to inherit the Thread class, while the other...

3 minutes read.

Display Unique Rows in a Binary Matrix in Java

To solve this problem, we must first locate and display the distinct rows of a supplied binary matrix afterward. We will go through how to show distinct rows inside a...

12 minutes read.

Perfect Number in Java

The concept of a perfect number in Java will be defined in this chapter, along with creating Program code that determine whether a specific number is perfect or not. Additionally,...

4 minutes read.

Find Unique Elements in Array Java

An array in Java is a grouping of objects that share the same type of data. We are free to enter identical or repeating elements into an array. Therefore, we...

6 minutes read.

Creating a Jar file in Java

The JDK's jar (Java Archive) tool offers the ability to produce jar files that can be executed. If you double-click a jar file that is executable, it will call the...

2 minutes read.

Java Integer sum() method

The sum() method of Java Integer class add the two specified integers values. It returns the same result as given by + operator. Syntax public static int sum (int a, int b)  Parameters The...

1 minute read.

Java Integer divideUnsigned() method

The divideUnsigned() method of Integer class returns the unsigned quotient by dividing the first argument by the second argument. Syntax public static int divideUnsigned (int dividend , int divisor) Parameters The parameter ‘dividend’ represents...

1 minute read.

Java Integer toHexString() method

The toHexString() method of Java Integer class returns a string representing the specified int argument as an unsigned integer in base 16. Syntax public static String toHexString (int  i)  Parameters The parameter ‘i’ represents...

1 minute read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.