skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

▼
 
  • RSS
  • Twitter
Showing posts with label Encryption Example. Show all posts
Showing posts with label Encryption Example. Show all posts
Sunday, October 14, 2012

Password Encryption Decryption using PBE With MD5 And DES algorithm in java

Posted by Raju Gupta at 4:00 PM – 1 comments
 

In Some applications, at User registration time, we need to Encrypt the password field and then store into the database.

After that if same user logs in, retrieve the encrypted password from Database , decrypt it and then compare it with user entered password.

If both password's are equal, then only the User will be allowed to login the application.

This java code snippet can be used to Encrypt and decrypt the passwords with PBEWithMD5AndDES algorithm in java   

import javax.crypto.*;
import javax.crypto.spec.*;
import java.security.spec.*;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.io.*;

public class Helper {

 public static Cipher dcipher,ecipher;
 
 //Responsible for setting, initializing this object's encrypter and decrypter Chipher instances    
 Helper(String passPhrase) {
          // 8-bytes Salt
          byte[] salt = {
             (byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,
             (byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03
          };

          // Iteration count
          int iterationCount = 19;

          try
             {  
  //Generate a temporary key. In practice, you would save this key
            //Encrypting with DES Using a Pass Phrase
              KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
             SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);

             ecipher = Cipher.getInstance(key.getAlgorithm());
             dcipher = Cipher.getInstance(key.getAlgorithm());

              // Prepare the parameters to the cipthers
              AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);

             ecipher.init(Cipher.ENCRYPT_MODE, key, paramSpec);
             dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);

             } catch (InvalidAlgorithmParameterException e) {
               System.out.println("EXCEPTION: InvalidAlgorithmParameterException");
              } catch (InvalidKeySpecException e) {
              System.out.println("EXCEPTION: InvalidKeySpecException");
             } catch (NoSuchPaddingException e) {
              System.out.println("EXCEPTION: NoSuchPaddingException");
              } catch (NoSuchAlgorithmException e) {
              System.out.println("EXCEPTION: NoSuchAlgorithmException");
             } catch (InvalidKeyException e) {
               System.out.println("EXCEPTION: InvalidKeyException");
             }
    }

     //Encrpt Password    
     @SuppressWarnings("unused")
 protected String encrypt(String str) 
     {
            try {
             // Encode the string into bytes using utf-8
              byte[] utf8 = str.getBytes("UTF8");
              // Encrypt
             byte[] enc = ecipher.doFinal(utf8);
              // Encode bytes to base64 to get a string
             return new sun.misc.BASE64Encoder().encode(enc);

          } catch (BadPaddingException e) {
        } catch (IllegalBlockSizeException e) {
          } catch (UnsupportedEncodingException e) {
               }
          return null;
     }    

     // Decrpt password   
     //To decrypt the encryted password
     protected String decrypt(String str) 
     {
      Cipher dcipher = null;
  try
  {
       byte[] salt = {(byte)0xA9, (byte)0x9B, (byte)0xC8, (byte)0x32,(byte)0x56, (byte)0x34, (byte)0xE3, (byte)0x03};
   int iterationCount = 19;
   try 
   {   String passPhrase="";
        KeySpec keySpec = new PBEKeySpec(passPhrase.toCharArray(), salt, iterationCount);
       SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);          
       dcipher = Cipher.getInstance(key.getAlgorithm());
        // Prepare the parameters to the cipthers
        AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
    dcipher.init(Cipher.DECRYPT_MODE, key, paramSpec);
           } 
   catch (InvalidAlgorithmParameterException e)
           {       System.out.println("EXCEPTION: InvalidAlgorithmParameterException");
    }
   catch (InvalidKeySpecException e)
   {       System.out.println("EXCEPTION: InvalidKeySpecException");
   }
   catch (NoSuchPaddingException e)
   {       System.out.println("EXCEPTION: NoSuchPaddingException");
   } 
   catch (NoSuchAlgorithmException e)
   {       System.out.println("EXCEPTION: NoSuchAlgorithmException");
   } 
   catch (InvalidKeyException e)
   {       System.out.println("EXCEPTION: InvalidKeyException");
   }
           // Decode base64 to get bytes
   byte[] dec = new sun.misc.BASE64Decoder().decodeBuffer(str);
   // Decrypt
   byte[] utf8 = dcipher.doFinal(dec);
   // Decode using utf-8
   return new String(utf8, "UTF8");
  }
  catch (BadPaddingException e) {
  } catch (IllegalBlockSizeException e) {
  } catch (UnsupportedEncodingException e) {
  } catch (IOException e){
  }
  return null;
 }
    
 /**
  * @param args
  */
 public static void main(String[] args) {
  try {
      
      // Create encrypter/decrypter class
   System.out.println("Inside Helper");
      Helper encrypter = new Helper("");

      // Pass the word to be Encrypted to Encrypt()
      System.out.println( "encrypt the String: SimplePassword");
      String encrypted = encrypter.encrypt("SimplePassword");
      System.out.println( "encrypted String:"+ encrypted);
      
      // Pass the encrypted word to be Decrypted to Decrypt()
      String decrypted = encrypter.decrypt(encrypted);
      System.out.println( "decrypted String:"+ decrypted);
  } catch (Exception e) {
  }
 }  
}
/* ************** OUTPUT **********************
encrypt the String: SimplePassword
encrypted String:7X57aBz+EzblJoIon5HkCg==
decrypted String:SimplePassword
*************************************************/


[ Read More ]
Read more...

Generate MD5 Hash value for any input given using Java

Posted by Raju Gupta at 6:00 AM – 0 comments
 

The MD5 Message-Digest Algorithm is a widely used cryptographic hash function that produces a 128-bit (16-byte) hash value. MD5 has been employed in a wide variety of security applications, and is also commonly used to check data integrity

A cryptographic hash function is a hash function, that is, an algorithm that takes an arbitrary block of data and returns a fixed-size bit string, the hash value, such that an change to the data will change the hash value. The data to be encoded is often called the message, and the hash value is sometimes called the message digest or simply digest.

java.security.MessageDigest provides applications the functionality of a message digest algorithm, such as MD5 or SHA.

import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class JavaMD5Hash {
 
    public static void main(String[] args) {
 
            String password = "MyPassword123";
 
            System.out.println("MD5 in hex: " + md5(password));
 
             
            System.out.println("MD5 in hex: " + md5(null));
            //= d41d8cd98f00b204e9800998ecf8427e
             
             
            System.out.println("MD5 in hex: "
                + md5("The quick brown fox jumps over the lazy dog"));
            //= 9e107d9d372bb6826bd81d3542a419d6
    }
     
     
    public static String md5(String input) {
         
        String md5 = null;
         
        if(null == input) return null;
         
        try {
             
        //Create MessageDigest object for MD5
        MessageDigest digest = MessageDigest.getInstance("MD5");
         
        //Update input string in message digest
        digest.update(input.getBytes(), 0, input.length());
 
        //Converts message digest value in base 16 (hex)
        md5 = new BigInteger(1, digest.digest()).toString(16);
 
        } catch (NoSuchAlgorithmException e) {
 
            e.printStackTrace();
        }
        return md5;
    }
}


[ Read More ]
Read more...
Friday, September 14, 2012

Encrypt a text using java | Java Example

Posted by Admin at 12:46 PM – 0 comments
 

Encryption of text using java



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 Encryption{
 
    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 Encryption() 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 Encryption And Decryption Technique
     */
    public static void main(String args []) throws Exception
    {
        Encryptionmy Encryptor= new Encryption();
 
        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);
 
    }
 
}





[ Read More ]
Read more...
Older Posts
Subscribe to: Posts ( Atom )
  • Popular
  • Recent
  • Archives
Powered by Blogger.
 
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger