You are on page 1of 7

Sample Login Program in Java

Lab 1
Create a Simple Login Program

import java.util.Scanner; // I use scanner because it's command line.

public class Login {


public void run() {
Scanner scan = new Scanner (new File("the\\dir\\myFile.extension"));
Scanner keyboard = new Scanner (System.in);
String user = scan.nextLine();
String pass = scan.nextLine(); // looks at selected file in scan

String inpUser = keyboard.nextLine();


String inpPass = keyboard.nextLine(); // gets input from user

if (inpUser.equals(user) && inpPass.equals(pass)) {


System.out.print("your login message");
} else {
System.out.print("your error message");
}
}
}

How to Encrypt Password in Java?


Every software application requires a username and password in order to authenticate the valid user. A username can be
anything like an email-id or just a combination of characters. But while creating a password, one must be very careful. Because
anyone with valid credentials can enter into the system and access the information.

Need of Encrypting a Password


When a user sets his/her password, it stores in the database as a plain text. Storing the plain text as it is into the database is not
secure at all. Hackers may break the system and steal the passwords from the database.

To ensure the security of the user's password, it is encrypted using different encryption techniques. Using various encryption
techniques, the plain text password is stored in an encrypted form in the database. There are many methods that can be used to
encrypt the password. But the hashing is one of the most popular encryption techniques.

Java Secure Hashing Techniques


The encrypted hash value is generated using certain algorithms on the plain text password provided by the user. Java
programming supports several hashing techniques in order to encrypt a password.

MD5 Hashing Technique


The MD5 (Message Digest) is a very popular hashing algorithm. It is a cryptographic hash function that generates a 128-bits hash
value. This algorithm is defined under java.security package in Java programming.

PassEncTech1.java

1. import java.security.NoSuchAlgorithmException;  
2. import java.security.MessageDigest;  
3.   
4. public class PassEncTech1   
5. {  
6.     /* Driver Code */  
7.     public static void main(String[] args)   
8.     {  
9.         /* Plain-text password initialization. */  
10.         String password = "myPassword";  
11.         String encryptedpassword = null;  
12.         try   
13.         {  
14.             /* MessageDigest instance for MD5. */  
15.             MessageDigest m = MessageDigest.getInstance("MD5");  
16.               
17.             /* Add plain-text password bytes to digest using MD5 update() method. */  
18.             m.update(password.getBytes());  
19.               
20.             /* Convert the hash value into bytes */   
21.             byte[] bytes = m.digest();  
22.               
23.             /* The bytes array has bytes in decimal form. Converting it into hexadecimal format. */  
24.             StringBuilder s = new StringBuilder();  
25.             for(int i=0; i< bytes.length ;i++)  
26.             {  
27.                 s.append(Integer.toString((bytes[i] & 0xff) + 0x100, 16).substring(1));  
28.             }  
29.               
30.             /* Complete hashed password in hexadecimal format */  
31.             encryptedpassword = s.toString();  
32.         }   
33.         catch (NoSuchAlgorithmException e)   
34.         {  
35.             e.printStackTrace();  
36.         }  
37.           
38.         /* Display the unencrypted and encrypted passwords. */  
39.         System.out.println("Plain-text password: " + password);  
40.         System.out.println("Encrypted password using MD5: " + encryptedpassword);  
41.     }  
42. }  

Output:

Plain-text password: myPassword


Encrypted password using MD5: deb1536f480475f7d593219aa1afd74c

The above code shows the implementation of MessageDigest class in java.security package. The MD5 returns a byte array that
needs to be converted into a readable hexadecimal format.

The MD5 hashing technique is easy and fast to implement but it is also prone to brute force attacks or dictionary attacks.

SHA256
SHA is the Secure Hash Algorithm. It uses a cryptographic function that takes up the 32-bit plain-text password and converts it
into a fixed size 256-bit hash value. This hashing technique is implemented using the MessageDiagest class of java.security
package.

It is a one-way encryption technique. Once the passphrase is encrypted it cannot be decrypted back.

PassEncTech2.java

1. import java.math.BigInteger;  
2. import java.nio.charset.StandardCharsets;  
3. import java.security.MessageDigest;  
4. import java.security.NoSuchAlgorithmException;  
5.   
6. public class PassEncTech2   
7. {  
8.     public static byte[] getSHA(String input) throws NoSuchAlgorithmException  
9.     {  
10.         /* MessageDigest instance for hashing using SHA256 */  
11.         MessageDigest md = MessageDigest.getInstance("SHA-256");  
12.   
13.         /* digest() method called to calculate message digest of an input and return array of byte */  
14.         return md.digest(input.getBytes(StandardCharsets.UTF_8));  
15.     }  
16.       
17.     public static String toHexString(byte[] hash)  
18.     {  
19.         /* Convert byte array of hash into digest */  
20.         BigInteger number = new BigInteger(1, hash);  
21.   
22.         /* Convert the digest into hex value */  
23.         StringBuilder hexString = new StringBuilder(number.toString(16));  
24.   
25.         /* Pad with leading zeros */  
26.         while (hexString.length() < 32)  
27.         {  
28.             hexString.insert(0, '0');  
29.         }  
30.   
31.         return hexString.toString();  
32.     }  
33.   
34.     /* Driver code */  
35.     public static void main(String args[])  
36.     {  
37.         try  
38.         {  
39.             String string1 = "myPassword";  
40.             System.out.println("\n" + string1 + " : " + toHexString(getSHA(string1)));  
41.   
42.             String string2 = "hashtrial";  
43.             System.out.println("\n" + string2 + " : " + toHexString(getSHA(string2)));  
44.         }  
45.         catch (NoSuchAlgorithmException e)   
46.         {  
47.             System.out.println("Exception thrown for incorrect algorithm: " + e);  
48.         }  
49.     }  
50. }  

Output:

myPassword : 76549b827ec46e705fd03831813fa52172338f0dfcbd711ed44b81a96dac51c6

hashtrial : d3e3224a59d69e9a000f1ce6782cb6a8be1eb3155610ff41bffbcbc95adc5d7

The above code uses the instance of MessageDigest class to generate a hash for SHA256. The SHA256 returns a byte array that
needs to be converted into a readable hexadecimal format. And lastly, the encrypted hash value is displayed.
SHA512 MD5 Hashing Technique
SHA512 uses a cryptographic function that takes up the 64-bit plain-text password and converts it into a fixed size 512-bit hash
value. This hashing technique is also implemented using the MessageDiagest class of java.security package.

PassEncTech2.java

1. import java.math.BigInteger;  
2. import java.nio.charset.StandardCharsets;  
3. import java.security.MessageDigest;  
4. import java.security.NoSuchAlgorithmException;  
5.   
6. public class PassEncTech2   
7. {  
8.     public static byte[] getSHA(String input) throws NoSuchAlgorithmException  
9.     {  
10.         /* MessageDigest instance for hashing using SHA512*/  
11.         MessageDigest md = MessageDigest.getInstance("SHA-512");  
12.   
13.         /* digest() method called to calculate message digest of an input and return array of byte */  
14.         return md.digest(input.getBytes(StandardCharsets.UTF_8));  
15.     }  
16.       
17.     public static String toHexString(byte[] hash)  
18.     {  
19.         /* Convert byte array of hash into digest */  
20.         BigInteger number = new BigInteger(1, hash);  
21.   
22.         /* Convert the digest into hex value */  
23.         StringBuilder hexString = new StringBuilder(number.toString(16));  
24.   
25.         /* Pad with leading zeros */  
26.         while (hexString.length() < 32)  
27.         {  
28.             hexString.insert(0, '0');  
29.         }  
30.   
31.         return hexString.toString();  
32.     }  
33.   
34.     /* Driver code */  
35.     public static void main(String args[])  
36.     {  
37.         try  
38.         {  
39.             String string1 = "myPassword";  
40.             System.out.println("\n" + string1 + " : " + toHexString(getSHA(string1)));  
41.   
42.             String string2 = "hashtrial";  
43.             System.out.println("\n" + string2 + " : " + toHexString(getSHA(string2)));  
44.         }  
45.         catch (NoSuchAlgorithmException e)   
46.         {  
47.             System.out.println("Exception thrown for incorrect algorithm: " + e);  
48.         }  
49.     }  
50. }  

Output:
myPassword :
450ad03db9395dfccb5e03066fd7f16cfba2b61e23d516373714471459052ec90a9a4bf3a151e600ea8aaed36e
3b8c21a3d38ab1705839749d130da4380f1448

hashtrial :
9520ea1a8d60d23334e6d59acebd587de6fec1e53db5836f467096c540ae60f7c85e9fbc90856dee9d6563609b
8786b03b47892af0bad44bdcab2206f22df5cb

The above code uses the instance of MessageDigest class to generate a hash for SHA512. The SHA512 returns a byte array that
needs to be converted into a readable hexadecimal format. And lastly, the encrypted hash value is displayed.

Password-Based Encryption using Salt and Base64:


The password-based encryption technique uses plain text passwords and salt values to generate a hash value. And the hash
value is then encoded as a Base64 string. Salt value contains random data generated using an instance of Random class from
java.util package.

The following program demonstrates password encryption using salt and base64.

PassEncTech4.java

1. import java.security.NoSuchAlgorithmException;  
2. import java.security.SecureRandom;  
3. import java.security.spec.InvalidKeySpecException;  
4. import java.util.Arrays;  
5. import java.util.Base64;  
6. import java.util.Random;  
7. import javax.crypto.SecretKeyFactory;  
8. import javax.crypto.spec.PBEKeySpec;  
9.    
10. public class PassEncTech4  
11. {  
12.     /* Driver Code */  
13.     public static void main(String[] args)  
14.     {  
15.         /* Plain text Password. */  
16.         String password = "myNewPass123";  
17.           
18.         /* generates the Salt value. It can be stored in a database. */  
19.         String saltvalue = PassBasedEnc.getSaltvalue(30);  
20.           
21.         /* generates an encrypted password. It can be stored in a database.*/  
22.         String encryptedpassword = PassBasedEnc.generateSecurePassword(password, saltvalue);  
23.           
24.         /* Print out plain text password, encrypted password and salt value. */  
25.         System.out.println("Plain text password = " + password);  
26.         System.out.println("Secure password = " + encryptedpassword);  
27.         System.out.println("Salt value = " + saltvalue);  
28.           
29.         /* verify the original password and encrypted password */  
30.         Boolean status = PassBasedEnc.verifyUserPassword(password,encryptedpassword,saltvalue);  
31.         if(status==true)  
32.             System.out.println("Password Matched!!");  
33.         else  
34.             System.out.println("Password Mismatched");  
35.     }  
36. }  
37.   
38. class PassBasedEnc   
39. {  
40.     /* Declaration of variables */   
41.     private static final Random random = new SecureRandom();  
42.     private static final String characters = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";  
43.     private static final int iterations = 10000;  
44.     private static final int keylength = 256;  
45.       
46.     /* Method to generate the salt value. */  
47.     public static String getSaltvalue(int length)   
48.     {  
49.         StringBuilder finalval = new StringBuilder(length);  
50.   
51.         for (int i = 0; i < length; i++)   
52.         {  
53.             finalval.append(characters.charAt(random.nextInt(characters.length())));  
54.         }  
55.   
56.         return new String(finalval);  
57.     }     
58.   
59.     /* Method to generate the hash value */  
60.     public static byte[] hash(char[] password, byte[] salt)   
61.     {  
62.         PBEKeySpec spec = new PBEKeySpec(password, salt, iterations, keylength);  
63.         Arrays.fill(password, Character.MIN_VALUE);  
64.         try   
65.         {  
66.             SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");  
67.             return skf.generateSecret(spec).getEncoded();  
68.         }   
69.         catch (NoSuchAlgorithmException | InvalidKeySpecException e)   
70.         {  
71.             throw new AssertionError("Error while hashing a password: " + e.getMessage(), e);  
72.         }   
73.         finally   
74.         {  
75.             spec.clearPassword();  
76.         }  
77.     }  
78.   
79.     /* Method to encrypt the password using the original password and salt value. */  
80.     public static String generateSecurePassword(String password, String salt)   
81.     {  
82.         String finalval = null;  
83.   
84.         byte[] securePassword = hash(password.toCharArray(), salt.getBytes());  
85.    
86.         finalval = Base64.getEncoder().encodeToString(securePassword);  
87.    
88.         return finalval;  
89.     }  
90.       
91.     /* Method to verify if both password matches or not */  
92.     public static boolean verifyUserPassword(String providedPassword,  
93.             String securedPassword, String salt)  
94.     {  
95.         boolean finalval = false;  
96.           
97.         /* Generate New secure password with the same salt */  
98.         String newSecurePassword = generateSecurePassword(providedPassword, salt);  
99.           
100.         /* Check if two passwords are equal */  
101.         finalval = newSecurePassword.equalsIgnoreCase(securedPassword);  
102.           
103.         return finalval;  
104.     }  
105. }  

Output:

Plain text password = myNewPass123


Secure password = sA0jNGQTrAfMUiqrB++bMKTU55ThdFCl16ZZTIXwD2M=
Salt value = n7d9MPQFXxDqzT6onmong3hQt8Nyko
Password Matched!!

In the above code, two classes are defined.

1. The class PassEncTech4 contains the driver code for the program. It generates a salt value and encrypted password
using the given plain-text password. And verifies them using the value returned by the verifyUserPassword()
2. In the class PassBasedEnc, 4 methods are defined. The first method is getSaltvalue() which generates the value
using Random class from util package. Then hash()is defined that has a return type of byte array.
The generateSecurePassword() uses plain-text password and salt value with the hash() method. And lastly, the two
passwords are matched using the verifyUserPassword() method.

Techniques for Cracking the Hash


A hash value is prone to different kinds of attacks by attackers. Some of them are mentioned below,

1. Brute force attack: In the brute force attack, the attacker submits multiple combinations of passphrases or passwords
in the hope that one of the combinations will match and he can enter into the system.
To avoid this kind of attack the passphrase should use a combination of alphabets, numbers and symbols. Another way
is to set a fixed number of invalid attempts and after that ask for human verification like a captcha.
2. Dictionary attack: Dictionary attack is an enhanced version of brute force attack. In this technique, the encrypted cipher
is tried to be decrypted using multiple possibilities, like the words in a dictionary.
3. Rainbow tables: The technique is about a rainbow table that is precomputed table for reversing the cryptographic hash
functions. The rainbow tables are used to discover the plain text passwords up to a certain length and a limited number
of characters. So it uses a side-loop table in order to reduce the storage usage and increase the speed of attack.

You might also like