Monday, February 7, 2011

Iterator,Set and Encryption Example

import java.security.Provider;
import java.security.Security;
import java.security.MessageDigest;
import java.util.Iterator;
import java.util.Set;


public class cipher1 {
    public static void main(String args[]) throws Exception
    {
        // Get the Provider List
        Provider p[]=Security.getProviders();
        // First record of Providers
        // Get the Keyset
        Set v_set=p[0].keySet();
       
        // Get the Iterator to operate upon
        Iterator itr=v_set.iterator();
       
        // Key and Value String Variables
        String v_key;
        String v_value;
        while(itr.hasNext())
        {
            v_key=(String)itr.next();
            v_value=p[0].getProperty(v_key);
            System.out.println("Key is "+v_key);
            System.out.println("Property Value is "+v_value);       
        }
        // Use the key value as input
        // Example :
        // Key of type Key is MessageDigest.SHA-512
        // Name would be DSA (contents after the dot(.)
        System.out.println("SHA-1 Encrypted Code "+encrypt("Ajith","SHA-1"));
        System.out.println("MD5 Encrypted Code "+encrypt("Ajith","MD5"));
        System.out.println("MD5 Encrypted Code "+encrypt("Ajith","MD5"));
        System.out.println("MD2 Encrypted Code "+encrypt("Ajith","MD2"));
        System.out.println("SHA-256 Encrypted Code "+encrypt("Ajith","SHA-256"));
        System.out.println("SHA-512 Encrypted Code "+encrypt("Ajith","SHA-512"));
       
    }

    // This function takes String to be encrypted and encryption alogrithm name
    // and returns the encrypted byte Array
   
    public static byte[] encrypt(String v_str,String v_alg_name) throws Exception
    {
        java.security.MessageDigest d=null;
        d=java.security.MessageDigest.getInstance(v_alg_name);
        d.reset();
        System.out.println("Bytes are "+v_str.getBytes());
        d.update(v_str.getBytes());
        return d.digest();
    }
}

No comments:

Post a Comment

Please add value. Sharing is caring