Friday 18 November 2016

How to Encrypt and Decrypt file using java code


import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class EncriptDecrypt {
    
    private static final String ALGORITHM = "AES";
    private static final String TRANSFORMATION = "AES";
    
    public static void main(String args[]) throws Exception{
        
       EncriptDecrypt.decrypt(new File("c:\\encryptFile\\encr.xls"), new File("c:\\decryptFile\\decr.xls"));  
       EncriptDecrypt.encrypt(new File("c:\\test.xls"), new File("c:\\decryptFile\\encr.xls"));  
    }
    
       public static void encrypt(File inputFile, File outputFile)
            throws Exception {
        doCrypto(Cipher.ENCRYPT_MODE, inputFile, outputFile);
    }

    public static void decrypt(File inputFile, File outputFile)
            throws Exception {
        doCrypto(Cipher.DECRYPT_MODE, inputFile, outputFile);
    }
    
    private static void doCrypto(int cipherMode, File inputFile,
            File outputFile) throws Exception {
        try {
            byte[] keyLength = new byte[16];
            Key secretKey = new SecretKeySpec(keyLength, ALGORITHM);
            Cipher cipher = Cipher.getInstance(TRANSFORMATION);
            cipher.init(cipherMode, secretKey);
            FileInputStream inputStream = new FileInputStream(inputFile);
            byte[] inputBytes = new byte[(int) inputFile.length()];
            inputStream.read(inputBytes);
            byte[] outputBytes = cipher.doFinal(inputBytes);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            outputStream.write(outputBytes);
            inputStream.close();
            outputStream.close();

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



No comments:

Post a Comment