One Way Password Encryption Using Java

Wonder how your passwords are generally stored by the web applications? One thing for sure, they are not stored as plain text, if the developers out there care about your password security. In this little Java Tutorial, I would like to demonstrate how to generate an encrypted password that can be stored in the database and is safe. I will show how the change in encryption algorithm and encoding affects the generation of the encrypted password. There are varieties of encrypting algorithms, I am using SHA and MD5.

/**
 * @Author Kushal Paudyal
 * http://www.sanjaal.com/java
 * Last Modified On 2009-04-28
 */
package com.kushal.utils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import sun.misc.BASE64Encoder;

public final class MyPasswordEncrypt {
	public static synchronized String encrypt(String plaintext,
			String algorithm, String encoding) throws Exception {
		MessageDigest msgDigest = null;
		String hashValue = null;
		try {
			msgDigest = MessageDigest.getInstance(algorithm);
			msgDigest.update(plaintext.getBytes(encoding));
			byte rawByte[] = msgDigest.digest();
			hashValue = (new BASE64Encoder()).encode(rawByte);

		} catch (NoSuchAlgorithmException e) {
			System.out.println("No Such Algorithm Exists");
		} catch (UnsupportedEncodingException e) {
			System.out.println("The Encoding Is Not Supported");
		}
		return hashValue;
	}

	public static void main(String args[]) throws Exception {
		String plainPassword = "SecretPassword";

		System.out.println("PlainText\tAlgo\tEncoding\tEncrypted Password");
		System.out.println(plainPassword + "\tSHA\tUTF-8\t"
				+ encrypt("MySecretPassword", "SHA", "UTF-8"));
		System.out.println(plainPassword + "\tSHA-1\tUTF-16\t"
				+ encrypt("MySecretPassword", "SHA-1", "UTF-16"));
		System.out.println(plainPassword + "\tMD5\tUTF-8\t"
				+ encrypt("MySecretPassword", "MD5", "UTF-8"));
		System.out.println(plainPassword + "\tMD5\tUTF-16\t"
				+ encrypt("MySecretPassword", "MD5", "UTF-16"));

	}
}

—————————————————-
Here is the output of this program. Note the different
Encrypted Passwords for the same Plain Text Password
—————————————————

PlainText	        Algo	   Encoding	Encrypted Password
SecretPassword	SHA	   UTF-8	lScpxhyrfgHktfW6e5WDDSB190s=
SecretPassword	SHA-1  UTF-16	NfsACTQRTvkEV5kzrDY55vQR1ec=
SecretPassword	MD5	   UTF-8	cxWgEuytEFmjY0+L4TR4Rg==
SecretPassword	MD5	   UTF-16	JulkQ6YpxzLMlpIgU28xmg==

————————————————–

If you are interested in understanding what is SHA /MD5 and UTF Encoding, read below:

SHA
The SHA hash functions are a set of cryptographic hash functions designed by the National Security Agency (NSA) and published by the NIST as a U.S. Federal Information Processing Standard. SHA stands for Secure Hash Algorithm. The three SHA algorithms are structured differently and are distinguished as SHA-0, SHA-1, and SHA-2. The SHA-2 family uses an identical algorithm with a variable digest size which is distinguished as SHA-224, SHA-256, SHA-384, and SHA-512.

SHA-1 is the best established of the existing SHA hash functions, and is employed in several widely used security applications and protocols. In 2005, security flaws were identified in SHA-1, namely that a possible mathematical weakness might exist, indicating that a stronger hash function would be desirable. Although no attacks have yet been reported on the SHA-2 variants, they are algorithmically similar to SHA-1 and so efforts are underway to develop improved alternatives. A new hash standard, SHA-3, is currently under development the function will be selected via an open competition running between 2008 and 2012. [From Wikipedia. See License Terms]

MD5
In cryptography, MD5 (Message-Digest algorithm 5) is a widely used cryptographic hash function with a 128-bit hash value. As an Internet standard (RFC 1321), MD5 has been employed in a wide variety of security applications, and is also commonly used to check the integrity of files. However, it has been shown that MD5 is not collision resistant; as such, MD5 is not suitable for applications like SSL certificates or digital signatures that rely on this property. An MD5 hash is typically expressed as a 32 digit hexadecimal number.

MD5 was designed by Ron Rivest in 1991 to replace an earlier hash function, MD4. In 1996, a flaw was found with the design of MD5. While it was not a clearly fatal weakness, cryptographers began recommending the use of other algorithms, such as SHA-1 (which has since been found vulnerable). In 2004, more serious flaws were discovered, making further use of the algorithm for security purposes questionable. In 2007 a group of researchers including Arjen Lenstra described how to create a pair of files that share the same MD5 checksum. In an attack on MD5 published in December 2008, a group of researchers used this technique to fake SSL certificate validity. [From Wikipedia. See License Terms]

UTF
UTF Stands for Unicode Transformation Format. It is one of the method of character encoding for unicode.

Originally posted 2009-04-28 15:08:03.

Share

Tutorial – Encryption And Decryption Using DESede (Triple DES) In Java

We learned how to do a DES Encryption /Decryption in Java in the previous tutorial. In this tutorial, we will extend our knowledge of DES Encryption to DESede also known as Triple DES.

Triple DES is the common name for the Triple Data Encryption Algorithm (TDEA) block cipher.It is so named because it applies the Data Encryption Standard (DES) cipher algorithm three times to each data block. Triple DES provides a relatively simple method of increasing the key size of DES to protect against brute force attacks, without requiring a completely new block cipher algorithm.

The standards define three keying options:

  • Keying option 1: All three keys are independent.
  • Keying option 2: K1 and K2 are independent, and K3 = K1.
  • Keying option 3: All three keys are identical, i.e. K1 = K2 = K3.

Keying option 1 is the strongest, with 3 x 56 = 168 independent key bits.

Keying option 2 provides less security, with 2 x 56 = 112 key bits. This option is stronger than simply DES encrypting twice, e.g. with K1 and K2, because it protects against meet-in-the-middle attacks.

Keying option 3 is no better than DES, with only 56 key bits. This option provides backward compatibility with DES, because the first and second DES operations simply cancel out. It is no longer recommended by the National Institute of Standards and Technology (NIST) and not supported by ISO/IEC 18033-3.

In general Triple DES with three independent keys (keying option 1) has a key length of 168 bits (three 56-bit DES keys), but due to the meet-in-the-middle attack the effective security it provides is only 112 bits. Keying option 2, reduces the key size to 112 bits. However, this option is susceptible to certain chosen-plaintext or known-plaintext attacks and thus it is designated by NIST to have only 80 bits of security. (Information Source: Wikipedia).

The following diagram simplifies the working detail of Triple DES Algorithm.

Working of Triple DES Algorithm

Working of Triple DES Algorithm

In the following tutorial, we have used Keying Option 3, where all the keys are identical.

package com.kushal.utils;

import java.security.spec.KeySpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class DESedeEncryption {

	private static final String UNICODE_FORMAT = "UTF8";
	public static final String DESEDE_ENCRYPTION_SCHEME = "DESede";
	private KeySpec myKeySpec;
	private SecretKeyFactory mySecretKeyFactory;
	private Cipher cipher;
	byte[] keyAsBytes;
	private String myEncryptionKey;
	private String myEncryptionScheme;
	SecretKey key;

	public DESedeEncryption() throws Exception
	{
		myEncryptionKey = "ThisIsSecretEncryptionKey";
		myEncryptionScheme = DESEDE_ENCRYPTION_SCHEME;
		keyAsBytes = myEncryptionKey.getBytes(UNICODE_FORMAT);
		myKeySpec = new DESedeKeySpec(keyAsBytes);
		mySecretKeyFactory = SecretKeyFactory.getInstance(myEncryptionScheme);
		cipher = Cipher.getInstance(myEncryptionScheme);
		key = mySecretKeyFactory.generateSecret(myKeySpec);
	}

	/**
	 * Method To Encrypt The String
	 */
	public String encrypt(String unencryptedString) {
		String encryptedString = null;
		try {
			cipher.init(Cipher.ENCRYPT_MODE, key);
			byte[] plainText = unencryptedString.getBytes(UNICODE_FORMAT);
			byte[] encryptedText = cipher.doFinal(plainText);
			BASE64Encoder base64encoder = new BASE64Encoder();
			encryptedString = base64encoder.encode(encryptedText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return encryptedString;
	}
	/**
	 * Method To Decrypt An Ecrypted String
	 */
	public String decrypt(String encryptedString) {
		String decryptedText=null;
		try {
			cipher.init(Cipher.DECRYPT_MODE, key);
			BASE64Decoder base64decoder = new BASE64Decoder();
			byte[] encryptedText = base64decoder.decodeBuffer(encryptedString);
			byte[] plainText = cipher.doFinal(encryptedText);
			decryptedText= bytes2String(plainText);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return decryptedText;
	}
	/**
	 * Returns String From An Array Of Bytes
	 */
	private static String bytes2String(byte[] bytes) {
		StringBuffer stringBuffer = new StringBuffer();
		for (int i = 0; i < bytes.length; i++) {
			stringBuffer.append((char) bytes[i]);
		}
		return stringBuffer.toString();
	}

	/**
	 * Testing The DESede Encryption And Decryption Technique
	 */
	public static void main(String args []) throws Exception
	{
		DESedeEncryption myEncryptor= new DESedeEncryption();

		String stringToEncrypt="Sanjaal.com";
		String encrypted=myEncryptor.encrypt(stringToEncrypt);
		String decrypted=myEncryptor.decrypt(encrypted);

		System.out.println("String To Encrypt: "+stringToEncrypt);
		System.out.println("Encrypted Value :" + encrypted);
		System.out.println("Decrypted Value :"+decrypted);

	}

}

========================

Here is the sample output:

String To Encrypt: Sanjaal.com
Encrypted Value :aArhqI25Y1SkYrdv9gxYDQ==
Decrypted Value :Sanjaal.com

Blog Widget by LinkWithin

Originally posted 2009-06-19 13:55:29.

Share