Friday, July 25, 2014

Encryption in Java

Java provides cryptographic hash function to encrypt. Let's look a way to encrypt a text using SHA-1 algorithm. By just changing the encryption algorithm, we can generate different kind of hash.

//Any implementation of Java need to provide following algorithms
// MD5
// SHA-1
// SHA-256
String encryptionAlgorithm = "SHA-1";

try {   
 MessageDigest md = MessageDigest.getInstance(encryptionAlgorithm);
 
 String clearPassword = "password123";
 
 md.reset();
 md.update(clearPassword.getBytes("UTF-8"));

 byte[] digestedPassword = md.digest();
 String hexStr = "";
 for (int i = 0; i < digestedPassword.length; i++) {
  hexStr += Integer.toString

  ((digestedPassword[i] & 0xff) + 0x100, 16).substring(1);
 }
 
 //Print the encrypted password
 System.out.println(hexStr);
 
 // Many code snippets in web show the following way of generating
 // the hex
 // code. The right way is the above way and not the way below which
 // is
 // commented out. The following code generates hex code with
 // negative sign
 // for certain combination for example for "password123" . Still do
 // not know the mathematics behind it.
 // Will probe sometime in future, right now
 // has to fix the issue. :(
 //String encryptedPAssword = String.format("%x", new BigInteger(
 //  digestedPassword));
 //System.out.println(encryptedPAssword);

} catch (java.security.NoSuchAlgorithmException e) {
 System.out.println("Rats, " + encryptionAlgorithm + " doesn't exist");
}

Adding the salt

To add the salt, change the following code, after defining a salt string

String salt = "TATASalt";
....
md.update((clearPassword+salt).getBytes("UTF-8"));

No comments:

Post a Comment