Tuesday, October 29

Cryptography - Encryption/Decryption with Java

Introduction: Cryptography is the study and practice of hiding information. There are two basic techniques for encrypting information: symmetric encryption (also called secret key encryption) and asymmetric encryption (also called public key encryption.)


Symmetric Encryption
Symmetric encryption is the oldest and best-known technique. A secret key, which can be a number, a word, or just a string of random letters, is applied to the text of a message to change the content in a particular way. In this type of message encryption, both sender and receiver share the same key which is used to both encrypt and decrypt messages. Examples include AES (Advanced Encryption Standard) and Triple DES (Data Encryption Standard).

Advantages
Simple: This type of encryption is easy to carry out. The sender and receiver shares the same key.
Encrypt and decrypt your own files: If you use encryption for messages or files which you alone intend to access, there is no need to create different keys. Single-key encryption is best for this.
Fast: Symmetric key encryption is much faster than asymmetric key encryption.
Uses less computer resources: Single-key encryption does not require a lot of computer resources when compared to public key encryption.
Prevents widespread security compromise:  A different secret key is used for communication with every different party. If a key is compromised, only the messages between a particular pair of sender and receiver are affected. Communications with other people are still secure.
Disadvantages
 Need for secure channel for secret key exchange: Sharing the secret key in the beginning is a problem in symmetric key encryption.
Too many keys: A new shared key has to be generated for communication with every different party. This creates a problem with managing and ensuring the security of all these key.

Origin and authenticity of message cannot be guaranteed: Since both sender and receiver use the same key, messages cannot be verified to have come from a particular user. This may be a problem if there is a dispute.
Asymmetric Encryption
Any message (text, binary files, or documents) that are encrypted by using the public key can only be decrypted by applying the same algorithm, but by using the matching private key. Any message that is encrypted by using the private key can only be decrypted by using the matching public key. An example of asymmetric key encryption system is RSA.
Advantages
- Convenience: It solves the problem of distributing the key for encryption. Everyone publishes their public keys and private keys are kept secret.
- Provides for message authentication: Public key encryption allows the use of digital signatures which enables the recipient of a message to verify that the message is truly from a particular sender.
- Detection of tampering: The use of digital signatures in public key encryption allows the receiver to detect if the message was altered in transit. A digitally signed message cannot be modified without invalidating the signature.
- Provide for non-repudiation: Digitally signing a message is akin to physically signing a document. It is an acknowledgement of the message and thus, the sender cannot deny it.
Disadvantages
Public keys should/must be authenticated: No one can be absolutely sure that a public key belongs to the person it specifies and so everyone must verify that their public keys belong to them.
Slow: Public key encryption is slow compared to symmetric encryption. Not feasible for use in decrypting bulk messages.
Uses up more computer resources: It requires a lot more computer supplies compared to single-key encryption.
Widespread security compromise is possible: If an attacker determines a person's private key, his or her entire messages can be read.
 Loss of private key may be irreparable: The loss of a private key means that all received messages cannot be decrypted.

I’ll show how to encrypt and decrypt data using java. I used AES, Triple DES and RSA algorithm separately. I encrypted a simple text message and decrypted it back to its original form.
Symmetric Encryption/Decryption – AES Algorithm
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.Cipher;
import sun.misc.BASE64Encoder;
 
public class AES
{
public static void main(String args[])
{
  
    try
    {
              
    String clearText,cipherText,decipherText;
    clearText="This message is very confidential";
    byte[] clearTextByte=clearText.getBytes("UTF8");
   
    //Generate Key and pass an instance of AES
    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
   
    //initialize with key size 128 bits
    keyGen.init(128);
   
    //hold generated key in Secretkey
    SecretKey secretKey = keyGen.generateKey();
   
    // create an instance of Cipher and pass AES
    Cipher cipher = Cipher.getInstance("AES");
   
    //initialize cipher to encrypt mode and pass the key to encrypt
    cipher.init(Cipher.ENCRYPT_MODE,secretKey);
   
    byte[] cipherbyte = cipher.doFinal(clearTextByte);
  
   
    //encode data to get final encrypted data
    cipherText = new BASE64Encoder().encode(cipherbyte);
  
    //Decrypt the encrypted cipher
    cipher.init(Cipher.DECRYPT_MODE,secretKey,cipher.getParameters());
    byte[] decipherbyte = cipher.doFinal(cipherbyte);
    decipherText = new String(decipherbyte,"UTF8");
   
    //display
    System.out.println("Before encryption: " + clearText);
               System.out.println("After encryption: " + cipherText);
               System.out.println("After decryption: " + decipherText);
    } catch(Exception e)
    {
         
    }
}
}

Ps: It may give compilation error in eclipse environment. To resolve this issue- click window-preferences-compilers-error/warnings-deprecated and restricted API. Check Deprecated & Restricted API and select warning from dropdown box. Also, select warning from dropdown box for forbidden reference (Access rules).

Output:

Before encryption: This message is very confidential
After encryption: BZVz03yW46PBGtyLlFcIhRo3OS6/Ov8K06nSttt25mMnx91u+j0/OMHcSOTQh/pK
After decryption: This message is very confidential

Symmetric Encryption/Decryption –Triple DES Algorithm
import javax.crypto.KeyGenerator; //Generate key
import javax.crypto.Cipher;       //encryption/decryption
import javax.crypto.SecretKey;    //store and use keys
import java.security.*;


public class DES {
              
               private static Cipher cipher=null;
              
                 public static void main(String[] args) throws Exception {
                             
                             
                              try {
                                            
                              //Define keygenerator and pass an instance of DESede
                              //DESede key size is 168, so initialize the generator with 168 bits.
                              //store the generated key in SecretKey
                   //Create a Cipher Instance
                                            
                              KeyGenerator keygen=KeyGenerator.getInstance("DESede");
                              keygen.init(168);
                              SecretKey secretkey=keygen.generateKey();
                              cipher=Cipher.getInstance("DESede");
                             
                              //define cleartext and store it as an array of bytes
                             
                              String clearText="This message is very confidential";
                              byte[] clearTextByte=clearText.getBytes("UTF8");
                             
                             
                              //ENCRYPTION
                              //initialize cipher and pass secretkey to use for encryption.
                              //dofinal() method encrypts on Byte Array of input String
                             
                              cipher.init(Cipher.ENCRYPT_MODE, secretkey);
                              byte[] ciphertbyte=cipher.doFinal(clearTextByte);
                              String cipherText=new String(ciphertbyte,"UTF8");
                             
                             
                              //DECRYPTION
                              //initialize the cipher text to decrypt mode and pass the secretkey to use for decryption
                              //Use dofinal() to decrypt on Byte Array of cipher.Finally convert cipherbyte to String
                             
                              cipher.init(Cipher.DECRYPT_MODE, secretkey);
                              byte[] decipherbyte=cipher.doFinal(ciphertbyte);
                              String decipherText=new String(decipherbyte,"UTF8");
                             
                              // Display message before encryption, after encryption and after decryption
                             
                              System.out.println("Before encryption: " + clearText);
                              System.out.println("After encryption: " + cipherText);
                              System.out.println("After decryption: " + decipherText);

               }catch(Exception ex)
               {
                              System.out.println(ex.getMessage());
               }
                             
               }

}
Output:
Before encryption: This message is very confidential
After encryption: C_t???s?b_]Q?A?\=n4?i???w??_@s?_?3c6?o
After decryption: This message is very confidential


Asymmetric Encryption/Decryption –RSA Algorithm
import javax.crypto.KeyGenerator; //Generate key
import javax.crypto.Cipher;       //encryption/decryption
import javax.crypto.SecretKey;    //store and use keys
import java.security.*;

public class RSA {
              
              
    public static void main(String[] args) throws Exception {
              
               //Generate key with RSA
        KeyPairGenerator keyGen = KeyPairGenerator.getInstance("RSA");
        keyGen.initialize(2048); //key size
        KeyPair kp = keyGen.genKeyPair(); // one pair of key

        PublicKey publicKey = kp.getPublic(); //public key
        PrivateKey privateKey = kp.getPrivate(); //private key

        String clearText="This message is very confidential"; //plain text message
                              byte[] clearTextByte=clearText.getBytes("UTF8");  //plain message in byte array
       
       
        Cipher cipher = Cipher.getInstance("RSA");  //instance of cipher
        cipher.init(Cipher.ENCRYPT_MODE, publicKey); //encrypt with public key
        byte[] cipherbyte = cipher.doFinal(clearTextByte); //encryption on byte array
        String cipherText=new String(cipherbyte,"UTF8");
       
       

        cipher.init(Cipher.DECRYPT_MODE, privateKey); //decrypt with private key
        byte[] decipherbyte = cipher.doFinal(cipherbyte); //decrypt on byte array
        String decipherText=new String(decipherbyte,"UTF8");
       
       
        System.out.println("Before encryption: " + clearText); //display plain message
                              System.out.println("After encryption: " + cipherText); // display cipher
                              System.out.println("After decryption: " + decipherText); //display decipher
    }
}
Output:
Before encryption: This message is very confidential
After encryption: __????6????_c(<&_zI?X_uy??_?1cv_?VA_z_{ã?I?__??x??d??X0??6?
\?C??vk-X?9?.xqp>~_?b??????_m?{___U_=HH?????`???_RM[??4=W?d??_?Wu??/?)oTe??N*C?g-?a?cFK?????k???I??`_??4q_-(Mh?(?? ?9?e?)???02A/?iB4_?)??\V???<28?T?_,~_?&???N__??p?C????hX?,?kp?
After decryption: This message is very confidential