Password Encryption Using SHA1 (MD5) – JAVA

Here’s is a program where the password stored in the code is encoded by SHA1, It accepts the input from user computes the SHA1 digest and check if it is the same as the set Password. I have set the Password to – password


import java.io.Console;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class SHA1Pwd {

public static void main(String[] args) {

char[] passwordChar = null;
Console console = System.console();
MessageDigest md = null;
String encodedSetPwdInHexString = “5:BA:A6:1E:4C:9B:93:F3:F0:68:22:50:B6:CF:83:31:B7:EE:68:FD:8″;

//digest value of the string – password. change it to your required password digest.

try {

md = MessageDigest.getInstance(“SHA1″); // can be replaced with MD5
// SHA1 has fewer collisions in comparison with MD5.

} catch (NoSuchAlgorithmException e1) {
e1.printStackTrace();
}

try {
passwordChar = console.readPassword(“Enter Password : “);
} catch (NullPointerException e) {
System.out.println(“You Might Be Running The Program From An IDE , Try In Terminal”);
System.exit(1);
}

String passwordString = new String(passwordChar);
byte[] passwordByte = passwordString.getBytes();

md.update(passwordByte, 0, passwordByte.length);
byte[] encodedPassword = md.digest();                                           // compute the digest
String encodedPasswordInString = toHexString(encodedPassword);
System.out.println(“\nThe SHA1 digest of the password you entered in hex \n”
+ encodedPasswordInString);

// copy and paste this output to encodedSetPwdInHexString variable so your required password is set.

System.out.println(“\nThe SHA1 digest of the Correct Password in hex \n ”
+ encodedSetPwdInHexString);

if (encodedPasswordInString.equals(encodedSetPwdInHexString))                // compare both
{
System.out.println(“Correct Password”);
System.exit(3);
}
System.out.println(“Worng password”);
System.exit(2);

}

// method converts Byte Array To a HEX-String

public static String toHexString(byte[] buf) {
char[] hexChar = { ’0′, ’1′, ’2′, ’3′, ’4′, ’5′, ’6′, ’7′, ’8′, ’9′,
‘A’, ‘B’, ‘C’, ‘D’, ‘E’, ‘F’ };

StringBuffer strBuf = new StringBuffer(buf.length * 2);
for (int i = 0; i < buf.length; i++) {
strBuf.append(hexChar[(buf[i] & 0xf0) >>> 4]); // fill left with
// zero bits
strBuf.append(‘:’);
strBuf.append(hexChar[buf[i] & 0x0f]);
}
return strBuf.toString();
}

}

Tags: , , ,

5 comments

  1. Check out the post on JavaBlogging that shows a simplier way of calculating SHA-1.

  2. Hi,

    Can we use the same for MD-6 ?

    Thx

  3. Hi..
    I am beginner of Java. I want to test about sha1 checksum to reduce file size and encrypt it. I will be so happy if I got some references.
    Thanks

Leave a comment