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
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
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
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
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.