Encrypt decrypt algorithms examples

Click here to download eclipse supported ZIP file



This is AsymmetricEncryptionWithRSA.java file having the source code to execute business logic.



 

    
package com.cv.java.enc;

import java.security.InvalidKeyException;
import java.security.KeyPair;
import java.security.KeyPairGenerator;
import java.security.NoSuchAlgorithmException;
import java.util.Base64;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;


/**
 @author Chandra Vardhan
 */

public class AsymmetricEncryptionWithRSA {

  private static KeyPair keyPair;

  private static KeyPair initKeyPair() {
    try {
      keyPair = KeyPairGenerator.getInstance("RSA").generateKeyPair();
    catch (NoSuchAlgorithmException e) {
      System.err.println("Algorithm not supported! " + e.getMessage() "!");
    }

    return keyPair;
  }

  public static void main(String[] args) {
    initKeyPair();
    try {
      final Cipher cipher = Cipher.getInstance("RSA");
      final String plaintext = "javacirecep";

      // ENCRYPT using the PUBLIC key
      cipher.init(Cipher.ENCRYPT_MODE, keyPair.getPublic());
      byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes());
      String chipertext = new String(Base64.getEncoder().encode(encryptedBytes));
      System.out.println("encrypted (chipertext) = " + chipertext);

      // DECRYPT using the PRIVATE key
      cipher.init(Cipher.DECRYPT_MODE, keyPair.getPrivate());
      byte[] ciphertextBytes = Base64.getDecoder().decode(chipertext.getBytes());
      byte[] decryptedBytes = cipher.doFinal(ciphertextBytes);
      String decryptedString = new String(decryptedBytes);
      System.out.println("decrypted (plaintext) = " + decryptedString);
    catch (NoSuchAlgorithmException e) {
      System.err.println("Algorithm not supported! " + e.getMessage() "!");
    catch (NoSuchPaddingException | InvalidKeyException e) {
      System.err.println("Cipher cannot be created!");
      e.printStackTrace();
    catch (BadPaddingException | IllegalBlockSizeException e) {
      System.err.println("An error occurred during the encryption!");
      e.printStackTrace();
    }
  }
}


This is PBEWithSHA1AlgorithmExample.java file having the source code to execute business logic.



 

    
package com.cv.java.enc;

import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;


/**
 @author Chandra Vardhan
 */
public class PBEWithSHA1AlgorithmExample {

  public static void main(String[] args) {
    // generate key pair
    try {
      String algorithm = "PBEWithSHA1AndDESede";
      String password = "pleaseChangeit!";

      int count = 20;// hash iteration count
      SecureRandom random = new SecureRandom();
      byte[] salt = new byte[8];
      random.nextBytes(salt);

      // Create PBE parameter set
      PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, count);
      PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
      SecretKeyFactory keyFac = SecretKeyFactory.getInstance(algorithm);
      SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

      Cipher pbeCipher = Cipher.getInstance(algorithm);

      // Initialize PBE Cipher with key and parameters
      pbeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, pbeParamSpec);

      // Encrypt the encoded Private Key with the PBE key
      byte[] ciphertext = pbeCipher.doFinal("I will be encrypted".getBytes());
      String output = new String(ciphertext);
      System.out.println("Encrypted Text : : " + output);
      Cipher pbeCipher2 = Cipher.getInstance(algorithm);

      pbeCipher2.init(Cipher.DECRYPT_MODE, pbeKey, pbeParamSpec);
      byte[] plain = pbeCipher2.doFinal(output.getBytes());
      String plainOP = new String(plain);
      System.out.println("Decrypted Text : : " + plainOP);
    catch (Exception e) {
      e.printStackTrace();
    }
  }

}


This is RSAEncryptionDescription.java file having the source code to execute business logic.



 

    
package com.cv.java.enc;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.math.BigInteger;
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.spec.InvalidKeySpecException;
import java.security.spec.RSAPrivateKeySpec;
import java.security.spec.RSAPublicKeySpec;
import javax.crypto.Cipher;

/**
 
 @author Chandra Vardhan
 */
public class RSAEncryptionDescription {

  private static final String PUBLIC_KEY_FILE = "Public.key";
  private static final String PRIVATE_KEY_FILE = "Private.key";

  public static void main(String[] argsthrows IOException {

    try {
      System.out.println("-------GENRATE PUBLIC and PRIVATE KEY-------------");
      KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA");
      keyPairGenerator.initialize(2048)// 1024 used for normal
                        // securities
      KeyPair keyPair = keyPairGenerator.generateKeyPair();
      PublicKey publicKey = keyPair.getPublic();
      PrivateKey privateKey = keyPair.getPrivate();
      System.out.println("Public Key - " + publicKey);
      System.out.println("Private Key - " + privateKey);

      // Pullingout parameters which makes up Key
      System.out.println("\n------- PULLING OUT PARAMETERS WHICH MAKES KEYPAIR----------\n");
      KeyFactory keyFactory = KeyFactory.getInstance("RSA");
      RSAPublicKeySpec rsaPubKeySpec = keyFactory.getKeySpec(publicKey, RSAPublicKeySpec.class);
      RSAPrivateKeySpec rsaPrivKeySpec = keyFactory.getKeySpec(privateKey, RSAPrivateKeySpec.class);

      // Share public key with other so they can encrypt data and decrypt
      // thoses using private key(Don't share with Other)
      System.out.println("\n--------SAVING PUBLIC KEY AND PRIVATE KEY TO FILES-------\n");
      RSAEncryptionDescription rsaObj = new RSAEncryptionDescription();
      rsaObj.saveKeys(PUBLIC_KEY_FILE, rsaPubKeySpec.getModulus(), rsaPubKeySpec.getPublicExponent());
      rsaObj.saveKeys(PRIVATE_KEY_FILE, rsaPrivKeySpec.getModulus(), rsaPrivKeySpec.getPrivateExponent());

      // Encrypt Data using Public Key
      byte[] encryptedData = rsaObj.encryptData("RSA Encryption Decryption example Information !");

      // Descypt Data using Private Key
      rsaObj.decryptData(encryptedData);

    catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    catch (InvalidKeySpecException e) {
      e.printStackTrace();
    }

  }

  /**
   * Save Files
   
   @param fileName
   @param mod
   @param exp
   @throws IOException
   */
  private void saveKeys(String fileName, BigInteger mod, BigInteger expthrows IOException {
    FileOutputStream fos = null;
    ObjectOutputStream oos = null;

    try {
      System.out.println("Generating " + fileName + "...");
      fos = new FileOutputStream(fileName);
      oos = new ObjectOutputStream(new BufferedOutputStream(fos));

      oos.writeObject(mod);
      oos.writeObject(exp);

      System.out.println(fileName + " generated successfully");
    catch (Exception e) {
      e.printStackTrace();
    finally {
      if (oos != null) {
        oos.close();

        if (fos != null) {
          fos.close();
        }
      }
    }
  }

  /**
   * Encrypt Data
   
   @param data
   @throws IOException
   */
  private byte[] encryptData(String datathrows IOException {
    System.out.println("\n----------------ENCRYPTION STARTED------------");

    System.out.println("Data Before Encryption :" + data);
    byte[] dataToEncrypt = data.getBytes();
    byte[] encryptedData = null;
    try {
      PublicKey pubKey = readPublicKeyFromFile(PUBLIC_KEY_FILE);
      Cipher cipher = Cipher.getInstance("RSA");
      cipher.init(Cipher.ENCRYPT_MODE, pubKey);
      encryptedData = cipher.doFinal(dataToEncrypt);
      System.out.println("Encryted Data: " +new String(encryptedData));

    catch (Exception e) {
      e.printStackTrace();
    }

    System.out.println("----------------ENCRYPTION COMPLETED------------");
    return encryptedData;
  }

  /**
   * Encrypt Data
   
   @param data
   @throws IOException
   */
  private void decryptData(byte[] datathrows IOException {
    System.out.println("\n----------------DECRYPTION STARTED------------");
    byte[] descryptedData = null;

    try {
      PrivateKey privateKey = readPrivateKeyFromFile(PRIVATE_KEY_FILE);
      Cipher cipher = Cipher.getInstance("RSA");
      cipher.init(Cipher.DECRYPT_MODE, privateKey);
      descryptedData = cipher.doFinal(data);
      System.out.println("Decrypted Data: " new String(descryptedData));

    catch (Exception e) {
      e.printStackTrace();
    }

    System.out.println("----------------DECRYPTION COMPLETED------------");
  }

  /**
   * read Public Key From File
   
   @param fileName
   @return PublicKey
   @throws IOException
   */
  public PublicKey readPublicKeyFromFile(String fileNamethrows IOException {
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    try {
      fis = new FileInputStream(new File(fileName));
      ois = new ObjectInputStream(fis);

      BigInteger modulus = (BigIntegerois.readObject();
      BigInteger exponent = (BigIntegerois.readObject();

      // Get Public Key
      RSAPublicKeySpec rsaPublicKeySpec = new RSAPublicKeySpec(modulus, exponent);
      KeyFactory fact = KeyFactory.getInstance("RSA");
      PublicKey publicKey = fact.generatePublic(rsaPublicKeySpec);

      return publicKey;

    catch (Exception e) {
      e.printStackTrace();
    finally {
      if (ois != null) {
        ois.close();
        if (fis != null) {
          fis.close();
        }
      }
    }
    return null;
  }

  /**
   * read Public Key From File
   
   @param fileName
   @return
   @throws IOException
   */
  public PrivateKey readPrivateKeyFromFile(String fileNamethrows IOException {
    FileInputStream fis = null;
    ObjectInputStream ois = null;
    try {
      fis = new FileInputStream(new File(fileName));
      ois = new ObjectInputStream(fis);

      BigInteger modulus = (BigIntegerois.readObject();
      BigInteger exponent = (BigIntegerois.readObject();

      // Get Private Key
      RSAPrivateKeySpec rsaPrivateKeySpec = new RSAPrivateKeySpec(modulus, exponent);
      KeyFactory fact = KeyFactory.getInstance("RSA");
      PrivateKey privateKey = fact.generatePrivate(rsaPrivateKeySpec);

      return privateKey;

    catch (Exception e) {
      e.printStackTrace();
    finally {
      if (ois != null) {
        ois.close();
        if (fis != null) {
          fis.close();
        }
      }
    }
    return null;
  }
}


This is pom.xml file having the entries of dependency jars and information to build the application .



	
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"> <modelVersion>4.0.0</modelVersion> <groupId>com.cv.java.enc</groupId> <artifactId>EncryptDecryptAlgorithms</artifactId> <version>1.0</version> <dependencies> <dependency> <groupId>com.sun.jersey</groupId> <artifactId>jersey-bundle</artifactId> <version>1.11</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <dependency> <groupId>org.bouncycastle</groupId> <artifactId>bcprov-jdk16</artifactId> <version>1.46</version> </dependency> </dependencies> <build> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>3.1</version> <configuration> <source>1.8</source> <target>1.8</target> </configuration> </plugin> </plugins> </pluginManagement> <finalName>EncryptDecryptAlgorithms</finalName> </build> </project>


This is log4j.properties file having the entries for logging the information into the console/file.




#By default enabling Console appender
# Root logger option
log4j.rootLogger=INFO, stdout

# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-5p [%c]:%L -->> %m%n

# Redirect log messages to a log file
#log4j.appender.file=org.apache.log4j.RollingFileAppender
#log4j.appender.file.File=C:\servlet-application.log
#log4j.appender.file.MaxFileSize=5MB
#log4j.appender.file.MaxBackupIndex=10
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


No comments:

Post a Comment