Showing posts with label java. Show all posts
Showing posts with label java. Show all posts

Saturday, 9 June 2018

Java Simplified Encryption By JASYPT

Standard
Introduction to Jasypt


Jasypt is a java library which allows the developer to add basic encryption capabilities to his/her projects with minimum effort, and without the need of having deep knowledge on how cryptography works.

Take a simple case where we have application with customer's personal data to store in database in encrypted format 

In other case we have properties file with database credential store in encrypted form.
Jasypt library helps to  do  encryption and decryption scenarios in a very simple manner. 

Lets start with simple encryption and decryption using  BasicTextEncryptor class from the Jasypt library:

BasicTextEncryptor basicTextEncryptor = new BasicTextEncryptor();
String criticalData = "secret-data";
basicTextEncryptor.setPasswordCharArray("anythingforchararray".toCharArray())
String encryptedData= basicTextEncryptor.encrypt(criticalData);

To Decrypt
String plaintext = basicTextEncryptor.decrypt(encryptedData );

Simple isnt it !

We can use specialize class  StrongTextEncryptor   to achieve stronger encryption
StrongTextEncryptor strongEncryptor = new StrongTextEncryptor();
strongEncryptor.setPassword(myEncryptionPassword);
String myEncryptedText = strongEncryptor.encrypt(myText);
String myEncryptedText = strongEncryptor.encrypt(myText);
String plainText = strongEncryptor.decrypt(myEncryptedText)
Still Simple !!


we can even define encryption algorithm using Password based encryption classes  provided by jasypt. As the name suggest it requires a password to be supplied.

StandardPBEStringEncryptor encryptor = new StandardPBEStringEncryptor();
encryptor.setPassword("somepasswrd");             // set password
encryptor.setAlgorithm("PBEWithMD5AndTripleDES");    // optionally set the algorithm
// perform encyrption
String encryptedText = encryptor.encrypt(myText);
//perform decryption
String plainText = encryptor.decrypt(encryptedText);  // myText.equals(plainText)

Jasypt with SpringBoot


With spring-boot you can add maven dependency

<dependency>
    <groupId>com.github.ulisesbocchio</groupId>
    <artifactId>jasypt-spring-boot</artifactId>
    <version>2.0.0</version>
</dependency>

Add @EnableEncryptableProperties Annotations to your application
Add @PropertySource annotation to define properties files with encrypted properties
Inside properties file wrap encrypted value inside ENC()

@SpringBootApplication
@EnableEncryptableProperties
@PropertySource(name="EncryptedProperties", value = "classpath:encrypted.properties")
public class Application {
.....
}

Inside encrypted.properties
secret.key=ENC(hashed-encryptedtext); // 

 Now when you do environment.getProperty("secret.property") or use @Value("${secret.property}") what you get is the decrypted version of secret.property.

@Configuration
public class DBConfig {

@Value("${secret.property}")
String decryptedText;

......
}

Define a custom encryptor

@Bean(name = "customEcnryptor")
public StringEncryptor customEncryptorBean() {

    PooledPBEStringEncryptor encryptor = new PooledPBEStringEncryptor();
    SimpleStringPBEConfig config = new SimpleStringPBEConfig();
    config.setPassword("password");
    config.setAlgorithm("PBEWithMD5AndDES");
    config.setKeyObtentionIterations("1000");
    config.setPoolSize("1");
    config.setProviderName("SunJCE");
    config.setSaltGeneratorClassName("org.jasypt.salt.RandomSaltGenerator");
    config.setStringOutputType("base64");
    encryptor.setConfig(config);
    return encryptor;
}

Add  in application.properties file 
jasypt.encryptor.bean=customEcnryptor
to tell spring to use customEncryptor for jasypt encryption


That's all about Jasypt introduction. You can read more about jasypt features from  Jasypt home page


Saturday, 13 August 2016

Read text file using java

Standard
I have following requirements
1) Read text file
2) Skip start 3 line
3) Read data start with number and skip all empty and not required data





/**
 * 
 * @author Vaquar.khan@gmail.com
 *
 */
public class MutualFundNav {

    private String schemeCode;
    private String isinDivPayoutISINGrowth;
    private String isinDivReinvestment;
    private String schemeName;
    private String netAssetValue;
    private String repurchasePrice;
    private String salePrice;
    private String date;

    public String getSchemeCode() {
        return schemeCode;
    }

    public void setSchemeCode(String schemeCode) {
        this.schemeCode = schemeCode;
    }

    public String getIsinDivPayoutISINGrowth() {
        return isinDivPayoutISINGrowth;
    }

    public void setIsinDivPayoutISINGrowth(String isinDivPayoutISINGrowth) {
        this.isinDivPayoutISINGrowth = isinDivPayoutISINGrowth;
    }

    public String getIsinDivReinvestment() {
        return isinDivReinvestment;
    }

    public void setIsinDivReinvestment(String isinDivReinvestment) {
        this.isinDivReinvestment = isinDivReinvestment;
    }

    public String getSchemeName() {
        return schemeName;
    }

    public void setSchemeName(String schemeName) {
        this.schemeName = schemeName;
    }

    public String getNetAssetValue() {
        return netAssetValue;
    }

    public void setNetAssetValue(String netAssetValue) {
        this.netAssetValue = netAssetValue;
    }

    public String getRepurchasePrice() {
        return repurchasePrice;
    }

    public void setRepurchasePrice(String repurchasePrice) {
        this.repurchasePrice = repurchasePrice;
    }

    public String getSalePrice() {
        return salePrice;
    }

    public void setSalePrice(String salePrice) {
        this.salePrice = salePrice;
    }

    public String getDate() {
        return date;
    }

    public void setDate(String date) {
        this.date = date;
    }

    @Override
    public String toString() {
        return "MutualFundNav [schemeCode=" + schemeCode + ", isinDivPayoutISINGrowth=" + isinDivPayoutISINGrowth
                + ", isinDivReinvestment=" + isinDivReinvestment + ", schemeName=" + schemeName + ", netAssetValue="
                + netAssetValue + ", repurchasePrice=" + repurchasePrice + ", salePrice=" + salePrice + ", date=" + date
                + "]";
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((date == null) ? 0 : date.hashCode());
        result = prime * result + ((isinDivPayoutISINGrowth == null) ? 0 : isinDivPayoutISINGrowth.hashCode());
        result = prime * result + ((isinDivReinvestment == null) ? 0 : isinDivReinvestment.hashCode());
        result = prime * result + ((netAssetValue == null) ? 0 : netAssetValue.hashCode());
        result = prime * result + ((repurchasePrice == null) ? 0 : repurchasePrice.hashCode());
        result = prime * result + ((salePrice == null) ? 0 : salePrice.hashCode());
        result = prime * result + ((schemeCode == null) ? 0 : schemeCode.hashCode());
        result = prime * result + ((schemeName == null) ? 0 : schemeName.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        MutualFundNav other = (MutualFundNav) obj;
        if (date == null) {
            if (other.date != null)
                return false;
        } else if (!date.equals(other.date))
            return false;
        if (isinDivPayoutISINGrowth == null) {
            if (other.isinDivPayoutISINGrowth != null)
                return false;
        } else if (!isinDivPayoutISINGrowth.equals(other.isinDivPayoutISINGrowth))
            return false;
        if (isinDivReinvestment == null) {
            if (other.isinDivReinvestment != null)
                return false;
        } else if (!isinDivReinvestment.equals(other.isinDivReinvestment))
            return false;
        if (netAssetValue == null) {
            if (other.netAssetValue != null)
                return false;
        } else if (!netAssetValue.equals(other.netAssetValue))
            return false;
        if (repurchasePrice == null) {
            if (other.repurchasePrice != null)
                return false;
        } else if (!repurchasePrice.equals(other.repurchasePrice))
            return false;
        if (salePrice == null) {
            if (other.salePrice != null)
                return false;
        } else if (!salePrice.equals(other.salePrice))
            return false;
        if (schemeCode == null) {
            if (other.schemeCode != null)
                return false;
        } else if (!schemeCode.equals(other.schemeCode))
            return false;
        if (schemeName == null) {
            if (other.schemeName != null)
                return false;
        } else if (!schemeName.equals(other.schemeName))
            return false;
        return true;
    }

}
import java.io.*;
import java.util.ArrayList;
import java.util.List;

/**'
 * @author Vaquar.khan@gmail.com
 * 
 * This example code shows you how to read file in Java I am using MF file and
 * skip start 3 line 
 * http://portal.amfiindia.com/spages/NAV0.txt
 * 
 * Here you can see different type of data in file
 * i am reading only data i needed and setting into pojo
 */

public class ReadMutualFundNavTextFile {
    public static void main(String[] args) {
        String fileName = "C:\\temp\\MF File\\NAV0.txt";
        readFile(fileName);
    }

    private static void readFile(String fileName) {

        List<String> dataList = new ArrayList<String>();
        //
        System.out.println("Reading File from Java code");
        // Name of the file

        try {

            // Create object of FileReader
            FileReader inputFile = new FileReader(fileName);

            // Instantiate the BufferedReader Class
            BufferedReader bufferReader = new BufferedReader(inputFile);

            // Variable to hold the one line data
            String line;
            int curLineNr = 1;
            int skipLines = 3;
            // Read file line by line and print on the console
            while ((line = bufferReader.readLine()) != null) {
                if (curLineNr++ <= skipLines) {
                    continue;
                } else {
                    dataList.add(line);
                    System.out.println(line);
                }
            }
            //
            splitFileData1(dataList);
            // Close the buffer reader
            bufferReader.close();
        } catch (Exception e) {
            System.out.println("Error while reading file line by line:" + e.getMessage());
            e.printStackTrace();
        }

    }

    private static MutualFundNav splitFileData1(final List<String> dataList) {
        MutualFundNav mutualFundNav = new MutualFundNav();

        for (String str : dataList) {

            if (!str.isEmpty() && Character.isDigit(str.charAt(0))) {
                String split[] = str.split(";");
                mutualFundNav.setSchemeCode(split[0]);
                mutualFundNav.setIsinDivPayoutISINGrowth(split[1]);
                mutualFundNav.setIsinDivReinvestment(split[2]);
                mutualFundNav.setSchemeName(split[3]);
                mutualFundNav.setNetAssetValue(split[4]);
                mutualFundNav.setRepurchasePrice(split[5]);
                mutualFundNav.setSalePrice(split[6]);
                mutualFundNav.setDate(split[7]);
                //
                System.out.println("mutualFundNav=" + mutualFundNav);

                //

                //
                for (String s : split)
                    System.out.println(s);
            }
        }

        // return dto object
        return mutualFundNav;
    }

}