Security Algorithms (JAVA)


Encryption: It is the process of transforming human readable plaintext to unreadable cipher text.

RSA Encryption\Decryption

package asymmetric;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.security.Key;
import java.security.KeyFactory;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Security;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;
import javax.crypto.Cipher;

public class RSAText
{
                public byte[] encrypt(byte[] input,Key pubKey) throws Exception
                {
                                Cipher cipher = Cipher.getInstance("RSA");
                                cipher.init(Cipher.ENCRYPT_MODE, pubKey);
                                return cipher.doFinal(input);
                }

                public byte[] decrypt(byte[] input,Key privKey) throws Exception
                {
                                Cipher cipher = Cipher.getInstance("RSA");
                                cipher.init(Cipher.DECRYPT_MODE, privKey);
                                return cipher.doFinal(input);     
                }

                public void saveKeyPair(String path) throws NoSuchAlgorithmException, IOException
                {
                                new File(path).mkdirs();
                                KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA");
                                kpg.initialize(512);
                                KeyPair keyPair = kpg.generateKeyPair();
                                PrivateKey privateKey = keyPair.getPrivate();
                                PublicKey publicKey = keyPair.getPublic();
                                // Store Public Key.
                                X509EncodedKeySpec x509EncodedKeySpec = new X509EncodedKeySpec(         publicKey.getEncoded());
                                FileOutputStream fos = new FileOutputStream(path + "/public.key");
                                fos.write(x509EncodedKeySpec.getEncoded());
                                fos.close();
                                // Store Private Key.
                                PKCS8EncodedKeySpec pkcs8EncodedKeySpec = new PKCS8EncodedKeySpec(privateKey.getEncoded());
                                fos = new FileOutputStream(path + "/private.key");
                                fos.write(pkcs8EncodedKeySpec.getEncoded());
                                fos.close();
                }

                public KeyPair LoadKeyPair(String path) throws Exception
                {
                                // Read Public Key.
                                File filePublicKey = new File(path + "/public.key");
                                FileInputStream fis = new FileInputStream(path + "/public.key");
                                byte[] encodedPublicKey = new byte[(int) filePublicKey.length()];
                                fis.read(encodedPublicKey);
                                fis.close();
                                // Read Private Key.
                                File filePrivateKey = new File(path + "/private.key");
                                fis = new FileInputStream(path + "/private.key");
                                byte[] encodedPrivateKey = new byte[(int) filePrivateKey.length()];
                                fis.read(encodedPrivateKey);
                                fis.close();
                                // Generate KeyPair.
                                KeyFactory keyFactory = KeyFactory.getInstance("RSA");
                                X509EncodedKeySpec publicKeySpec = new X509EncodedKeySpec(encodedPublicKey);
                                PublicKey publicKey = keyFactory.generatePublic(publicKeySpec);
                                PKCS8EncodedKeySpec privateKeySpec = new PKCS8EncodedKeySpec(encodedPrivateKey);
                                PrivateKey privateKey = keyFactory.generatePrivate(privateKeySpec);
                                return new KeyPair(publicKey, privateKey);
                }
               
                public static void main(String[] args) throws Exception
                {
                                Security.addProvider(Security.getProvider("SunRsaSign"));
                                RSAText obj = new RSAText();
                                obj.saveKeyPair("e:\\RSA");
                                KeyPair keyPair = obj.LoadKeyPair("e:\\RSA");
                                PrivateKey privKey = keyPair.getPrivate();
                                PublicKey pubKey = keyPair.getPublic();
                                BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
                                System.out.println("Enter text to encrypted: ");
                                String original = br.readLine();
                                byte[] encrypted = obj.encrypt(original.getBytes(),pubKey);
                                System.out.println("Encrypted text: " + new String(encrypted));
                                byte[] decrypted = obj.decrypt(encrypted,privKey);
                                System.out.println("Decrypted text: " + new String(decrypted));
                }
}


Decryption : It is the process of transforming unreadable cipher text to human readable plaintext.

DES Encryption\Decryption

package symmetric;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Arrays;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class DES
{
                public byte[] encrypt(byte[] message,String symmetricKey) throws Exception
                {
                                byte[] keyBytes = Arrays.copyOf(symmetricKey.getBytes(),24);
                                for (int j=0,k=16; j < 8; k++,j++)
                                                keyBytes[k] = keyBytes[j];
                                SecretKey key = new SecretKeySpec(keyBytes,"DESede");
                                IvParameterSpec iv = new IvParameterSpec(new byte[8]);
                                Cipher cipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
                                cipher.init(Cipher.ENCRYPT_MODE,key,iv);
                                return cipher.doFinal(message);
                }

                public String decrypt(byte[] message,String symmetricKey) throws Exception
                {
                                byte[] keyBytes = Arrays.copyOf(symmetricKey.getBytes(),24);
                                for (int j=0,k=16; j<8; j++,k++)
                                                keyBytes[k] = keyBytes[j];
                                SecretKey key = new SecretKeySpec(keyBytes,"DESede");
                                IvParameterSpec iv = new IvParameterSpec(new byte[8]);
                                Cipher decipher = Cipher.getInstance("DESede/CBC/PKCS5Padding");
                                decipher.init(Cipher.DECRYPT_MODE,key,iv);
                                return new String(decipher.doFinal(message));
                }

                public static void main(String[] args) throws Exception
                {
                                DES des = new DES();
                                BufferedReader br =new BufferedReader(new InputStreamReader(System.in));
                                System.out.println("Enter the text to be encryted: ");
                                String original = br.readLine();
                                System.out.println("Enter key: ");
                                String key = br.readLine();
                                byte[] encrypted = des.encrypt(original.getBytes(),key);
                                System.out.println("Encrypted text: " + new String(encrypted));
                                String decrypted  = des.decrypt(encrypted,key);
                                System.out.println("Decrypted text: " + new String(decrypted));
                }
}


Hashing : It is one way process for conversion of any variable length text to a fixed length hash.

MD5 Hashing

The MD5 Message-Digest Algorithm is cryptographic hash function that produces a 128-bit (16-byte) hash value.

 package hashing;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5
{
                public static MD5 instance;

                static
                {
                                if(instance==null)
                                                instance = new MD5();
                }

                private MD5() {}
               
    public String encrypt(String input) throws NoSuchAlgorithmException
    {
        byte[] data = input.getBytes();
        String hex="";
        char[] hexChars = {'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
        MessageDigest md = MessageDigest.getInstance("MD5");
        md.update(data,0,data.length);
        byte[] b = md.digest();
        int msb;
        int lsb=0;
        for(int i=0;i<b.length;i++)
        {
            msb=((int)b[i]&0X000000FF)/16;
            lsb=((int)b[i]&0X000000FF)%16;
            hex = hex + hexChars[msb] + hexChars[lsb];
        }
        return hex;
    }
   
    public static void main(String args[]) throws Exception
    {
        MD5 obj = MD5.instance;
        System.out.println(obj.encrypt("cms"));
    }
}

Comments

Popular posts from this blog

Index MySQL datadase table in Solr

Hibernate Sharding Example

Shallow Copy