skip to main | skip to sidebar

Java Programs and Examples with Output

Pages

  • Home
 
  • RSS
  • Twitter
Showing posts with label MD5 Hashing Example. Show all posts
Showing posts with label MD5 Hashing 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

Secure Your Passwords Java MD5 Hashing and Salting

Posted by Admin at 2:08 PM – 0 comments
 

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...
Older Posts
Subscribe to: Posts ( Atom )

List of Java Programs

  • Java Program to check Greater between the Two Number
  • Java Program to find that given number is Palindrome or not
  • Java Program to Demonstrate the Use of Pre and Post Operator
  • Java Program to Reverse the Given Number
  • Java Program to Print Number in the Given Data Type
  • Program to Demonstrate Skipping using Continue
  • Program to find whether entered character is a vowel or Consonant
  • Java Program to Calculate the Sum of Digits of Given Number
  • How to swap two numbers using only two variables
  • Checking the Given Number is Armstrong or Not
  • Average an Array of Values
  • Display ASCII Code Instead of Character
  • Comparison of Two Variable using If
  • Printing Table In java using While Loop
  • Generate Random Number Using Math.Random Function
  • To Find roots of Quadratic Equation
  • Performing Arithmetic Opration on Two Variable
  • Concatenation of Two String in Java
  • Command Line Argument in JAVA
  • Java Hello World Program
  • Calculate Circle Perimeter | Java Program
  • Calculate the Area of Circle | Java Program
  • To Find Whether Given Year is a Leap Year or not
  • Popular
  • Recent
  • Archives

Total Pageviews

Sparkline

Followers

Popular Posts of This Week

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Comparison of Two Variable using If | JAVA Program
    Here is a Java Program to show Comparison Operation on the two variable using If Control Structure class IfComparison { public static vo...
  • Use a StreamTokenizer object to parse a string separated by commas
     Use a StreamTokenizer object to parse a string entered from the keyboard containing a series of data items separated by commas and output ...
  • Code to Remove Certain Characters from a Java Input
    Sometimes we can't rename a file automatically when the Filename has "/" inside them because of Windows limitations. This c...
  • Sorting a List in ascending order
    This code snippet sorts a list of objects based on the value of a field of those objects import java.util.ArrayList; import java.util...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
Powered by Blogger.

Archives

  • ▼  2014 ( 4 )
    • ▼  August ( 4 )
      • Java program to create a Binary Heap and Perform v...
      • Create an Adjacency matrix Graph and perform Add a...
      • To Sort an Interger Array using Shell Sort
      • Sort an Integer array with Bucket Sort
  • ►  2013 ( 6 )
    • ►  August ( 1 )
    • ►  April ( 5 )
  • ►  2012 ( 673 )
    • ►  November ( 9 )
    • ►  October ( 223 )
    • ►  September ( 272 )
    • ►  August ( 2 )
    • ►  June ( 1 )
    • ►  February ( 67 )
    • ►  January ( 99 )
 

Our Blogs

  • Linux Tutorial
  • C Programming Tutorial

Labels

  • Agile Methodology ( 1 )
  • Algorithm ( 3 )
  • AntiSamy ( 1 )
  • Arithmetic Operation ( 1 )
  • Array Example ( 9 )
  • ArrayList Examples ( 11 )
  • Average an Array of Values ( 1 )
  • Barcode Example ( 1 )
  • Basic Java Programs ( 34 )
  • Bing API Example ( 2 )
  • BitSet Example ( 1 )
  • Boolean Example ( 1 )
  • Bouncy Castle API ( 1 )
  • Break Statement ( 2 )
  • BufferedReader Example ( 2 )
  • Calendar Example ( 1 )
  • Chart Generation Example ( 1 )
  • Command Line Argument ( 1 )
  • Comparator Example ( 1 )
  • Concatenation of String ( 1 )
  • Continue Statement ( 1 )
  • Control Structure ( 1 )
  • Copy File Example ( 1 )
  • CRC Example ( 1 )
  • CSV Example ( 6 )
  • Data Structure ( 5 )
  • Date Example ( 2 )
  • Directory Example ( 1 )
  • Do - While Loop Example ( 1 )
  • Domino Database ( 1 )
  • Email Example ( 8 )
  • Encryption Example ( 3 )
  • Excel Example ( 15 )
  • Factorial Example ( 1 )
  • File Upload Example ( 1 )
  • Find Roots of Quadratic Equation ( 1 )
  • FTP Example ( 2 )
  • Graph Examples ( 1 )
  • Greater between Two Numbers ( 1 )
  • GSON Library ( 1 )
  • HashMap Example ( 1 )
  • HashSet Example ( 1 )
  • Hello World Program ( 1 )
  • If Condition ( 2 )
  • Inner Class Example ( 1 )
  • iText Example ( 3 )
  • JAR File ( 1 )
  • JAVA Applet ( 1 )
  • Java Applications ( 1 )
  • Java AWT Example ( 9 )
  • Java Certification ( 1 )
  • Java Class Examples ( 15 )
  • Java Collection Example ( 1 )
  • Java Command Example ( 4 )
  • Java Constructor Examples ( 1 )
  • Java Currency Example ( 1 )
  • Java Database Example ( 3 )
  • Java Date and Time Example ( 3 )
  • Java DateFormat Example ( 3 )
  • Java Examples ( 2 )
  • Java Exception Example ( 5 )
  • Java File Example ( 22 )
  • Java GUI Example ( 1 )
  • Java Image Examle ( 3 )
  • Java Inheritance Example ( 3 )
  • Java Input Output Example ( 1 )
  • Java IO Example ( 3 )
  • Java Jar Example ( 1 )
  • Java JSON Example ( 3 )
  • Java Mail Examples ( 4 )
  • Java Map Example ( 5 )
  • Java MapReduce Example ( 2 )
  • Java MultiThreading Example ( 7 )
  • Java Network Example ( 9 )
  • Java Package ( 1 )
  • Java Programs ( 1 )
  • Java RMI ( 1 )
  • Java Robot Class Examples ( 2 )
  • Java Runtime Example ( 1 )
  • Java Swing Example ( 9 )
  • Java Util Example ( 1 )
  • Java Vector Example ( 4 )
  • Java Voice Example ( 1 )
  • Java Webservice Example ( 1 )
  • Java XML Example ( 3 )
  • Java Zip Class Examples ( 2 )
  • JDBC ( 9 )
  • JDK Version Comparison ( 1 )
  • JFrame Example ( 3 )
  • JOptionPane Dialog Example ( 1 )
  • JPanel Example ( 1 )
  • JSP Example ( 2 )
  • JSTL Example ( 1 )
  • jUnit Example ( 2 )
  • LinkedList Example ( 2 )
  • List Example ( 1 )
  • Long Variable ( 1 )
  • Lottery Nubmer ( 1 )
  • MD5 Hashing Example ( 3 )
  • Memory Management Example ( 1 )
  • Method Override ( 1 )
  • MIDI Sound ( 8 )
  • Module Operator Example ( 2 )
  • Multiplication Table ( 1 )
  • Observer Interface Example ( 1 )
  • Operator Example ( 5 )
  • Pagination ( 1 )
  • Palindrome Number ( 1 )
  • Pass By Reference Example ( 1 )
  • Pass By Value Example ( 1 )
  • PDF File Example ( 3 )
  • PDF Generation Example ( 4 )
  • Pre and Post Operator ( 2 )
  • Prime Number ( 3 )
  • Progress Bar Example ( 1 )
  • Property List Example ( 2 )
  • Random Function ( 7 )
  • Recursion Example ( 2 )
  • Regex Example ( 2 )
  • Remote Host Example ( 2 )
  • Robot Class ( 4 )
  • Searching Example ( 3 )
  • Slideshow ( 1 )
  • Sorting Example ( 7 )
  • SpringLayout Example ( 1 )
  • Stack Example ( 4 )
  • Static Variable ( 1 )
  • StreamTokenizer Example ( 2 )
  • String Example ( 19 )
  • Struts2 Example ( 1 )
  • Sum of Digits ( 1 )
  • Swap Two Numbers ( 1 )
  • Switch Case ( 3 )
  • Tapestry Components ( 1 )
  • Thumbnail Example ( 2 )
  • TimerTask Example ( 2 )
  • To Calculate Volume ( 1 )
  • To Check Armstrong Number ( 1 )
  • Tree Example ( 1 )
  • TreeMap Example ( 1 )
  • TreeSet Example ( 1 )
  • Two Dimensional Array Example ( 1 )
  • UUID ( 1 )
  • Validation Example ( 2 )
  • Variable Casting ( 1 )
  • While Loop ( 1 )
  • XML Parsing ( 7 )
  • XSS Attacks ( 1 )
  • Zip File ( 15 )

Popular Posts

  • Java program to create a Binary Heap and Perform various operation
    A binary heap (min-heap) is a complete binary tree with elements from a partially ordered set, such that the element at every node is less ...
  • Creating Dynamic Macro Enabled Excel by Java
    We can create a dynamic macro enabled excel by java: We need to create a excel sheet template with macro on server. we can copy the...
  • Implementation of a basic generic tree, with labels of type T - Data Structure
    // This implements a basic generic tree, with labels of type T, // pointer to the parent node, and a singly linked list of children nodes...
  • To Sort an Interger Array using Shell Sort
    To Sort an Interger Array using Shell Sort class ShellSort { public static int[] shellSort(int[] array) { int N = array.length; ...
  • Create an Adjacency matrix Graph and perform Add and Remove operation
    import java.util.ArrayList; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Queue; import...
  • Sort an Integer array with Bucket Sort
    Here is a java program to Sort an Integer array with Bucket Sort class BucketSort { public int[] bucketSort(int[] array) { /...
  • Merge-Sort Algorithm implementation in JAVA
    Merge-Sort Function void MergeSort(int low, int high) // a[low : high] is a global array to be sorted. // Small(P) is true if there...
  • Stack implemented as array - Data Structure
    // Stack implemented as array public class ArrayStack<T> { private T[] stack; private int numElements = 0; // points to s...
  • Printing Table In java using While Loop
    Here is a Java Program to Print the Table public class Table { public static void main(String[] args) { int no = Integer.p...
  • Java Class to Calculate the Volume of Box
    Here is a Java Class to Calculate the Volume of Box. class Box { double width; double height; double depth; // This is the con...
 
 
© 2011 Java Programs and Examples with Output | Designs by Web2feel & Fab Themes

Bloggerized by DheTemplate.com - Main Blogger