Skip to main content

Encryption Decryption in java


In some use cases we require encryption and decryption of parameters. There are so many algorithm present for this implementation. Java Encryption Algorithms

When we are implementing the algorithm we need to consider our requirement and select the appropriate algorithm.

In one of my use case i had one requirement to send some parameters after encryption and decrypt it wherever i am using those parameters. I used AES algorithm.

You can use the same code in your application by creating a java file.

import java.io.IOException;
import java.nio.charset.Charset;
import java.security.GeneralSecurityException;

import java.util.regex.Pattern;

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

public class Encryption {
   private static String key = "xyzBKabcccraSing";
 
  public static void main(String[] args) {
    try {
      String encryptData="http://freshers.xyz.com/alert(request.get())";
      String ciphertext = encrypt(encryptData);
      System.out.println("encrypted value:" +ciphertext);
      System.out.println("decrypted value:" + (decrypt(ciphertext)));
      System.out.println("After validation : "+validateInput(decrypt(ciphertext)));
     } catch (Exception e) {
      e.printStackTrace();
    }
  }

/* Method to encrypt given string
 * input  : String
 * output : decryptrd string
 */

  public static String encrypt(String value)throws GeneralSecurityException {

    byte[] raw = key.getBytes(Charset.forName("UTF-8"));
    if (raw.length != 16) {
      throw new IllegalArgumentException("Invalid key size.");
    }
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeySpec,new IvParameterSpec(new byte[16]));
    byte[] byteCipherText = cipher.doFinal(value.getBytes(Charset.forName("UTF-8")));
    String strCipherText = new BASE64Encoder().encode(byteCipherText);
    return strCipherText;
  }


/* Method to Decrypt the given encrypted string
* input  : decrypted String
* output : encrypted string
*/


  public static String decrypt(String encrypted)throws GeneralSecurityException,IOException {

    byte[] raw = key.getBytes(Charset.forName("UTF-8"));
    if (raw.length != 16) {
      throw new IllegalArgumentException("Invalid key size.");
    }
    SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
    Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
    cipher.init(Cipher.DECRYPT_MODE, skeySpec,new IvParameterSpec(new byte[16]));
    byte[] decodedBytes=new BASE64Decoder().decodeBuffer(encrypted);
    byte[] original = cipher.doFinal(decodedBytes);
 
    return new String(original, Charset.forName("UTF-8"));
  }


// below code is used to validate or avoid the XSS attack in application

private static Pattern[] patterns = new Pattern[] {
            // Script fragments
            Pattern.compile("<script>(.*?)</script>",Pattern.CASE_INSENSITIVE),
            // src='...'
            Pattern.compile("src[\r\n]*=[\r\n]*\\\'(.*?)\\\'",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE |Pattern.DOTALL),
            Pattern.compile("src[\r\n]*=[\r\n]*\\\"(.*?)\\\"",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE |Pattern.DOTALL),
            // lonely script tags
            Pattern.compile("</script>", Pattern.CASE_INSENSITIVE),
            Pattern.compile("<script(.*?)>",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE |Pattern.DOTALL),
            // eval(...)
            Pattern.compile("eval\\((.*?)\\)",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE |Pattern.DOTALL),
            // expression(...)
            Pattern.compile("expression\\((.*?)\\)",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE |Pattern.DOTALL),
            // javascript:...
            Pattern.compile("javascript:", Pattern.CASE_INSENSITIVE),
            // vbscript:...
            Pattern.compile("vbscript:", Pattern.CASE_INSENSITIVE),
            // onload(...)=...
            Pattern.compile("onload(.*)",Pattern.CASE_INSENSITIVE | Pattern.MULTILINE |Pattern.DOTALL),
            //alert tag in js
            Pattern.compile("alert(.*)", Pattern.CASE_INSENSITIVE),
            Pattern.compile("<.*>", Pattern.CASE_INSENSITIVE)};

/* Method to validate input string for xss attack or
 * any malicious code
 */

public static String validateInput(String value) {
        if (value != null) {
           value = value.replaceAll("\0", "");
           for (Pattern scriptPattern : patterns) {
                value = scriptPattern.matcher(value).replaceAll("");
            }
        }
        return value;
    }
}


This code is tested and verified by checkmarx and fortify reports.


Comments

Popular posts from this blog

The file store "WLS_DIAGNOSTICS" could not be opened

WLS_DIAGNOSTIC ERROR weblogic.store.PersistentStoreException: [Store:280073]The file store "WLS_DIAGNOSTICS" could not be opened because it contained a file with the invalid version 1. A file of version 2 was expected. When you get this error while running your application on internal weblogic server delete the following file WLS_DIAGNOSTICS000000.DAT search the file in following path C:\jdev_work\system11.1.1.5.37.60.13\DefaultDomain this file is in DefaultDomain folder of your jdev. and delete the WLS_DIAGNOSTICS000000.DAT file . and run your applicatuon

Passivation and Activation in ADF (Application Module )

1. For performance reasons, ADF keeps a pool of application modules in memory. It tries to give each session the same application module as the session used during the last request; however, this might not be possible during peak load of your application. 2. In this case, ADF saves the application modules state in a database table so the application module can be used by another session. This is called passivation . 3. When the first session needs the application module again, its state is retrieved from the database process known as activation . 4. If you have made an error in your code and depend on some variable that is not persisted correctly when your application module state is stored, you will experience mysterious errors under high load.   Enable/Disable Application Module Pooling : Right-click on your application module, choose Configurations.By default, each application module has two configurations. Ensure that the one ending in …Local is selected and then c...

Overview Editor for bc4j.xcfg

This is used to customize the configuration settings for the application pool, connection pool, and transactions. Select the Application Module, then select a configuration from the Configurations list. You can specify a Default Configuration from the dropdown to use with selected application module. Edit the name of the configuration in Details. Its having 3 tabs 1.Database and Scalability 2. Properties 3. Custom Properties Database and Scalability Tab : In Database and Scalability you can mention the JDBC data source definition for each application module. You can choose to connect to a JDBC data source or to a JDBC URL.The default connection type is the default data source. A data source is a vendor-independent encapsulation of a database server connection on the application server. 1. Data sources ( JNDI name) offer advantages over a JDBC URL connection because the data source can be tuned, reconfigured, or remapped without changing the deployed application. 2. JDB...