You are on page 1of 3

Encryption of a file using java

package com;

import java.io.*; import java.security.*; import javax.crypto.*; import javax.crypto.spec.*; import java.util.*;

public class FileEncryptor { private static String filename; private static String password; private static FileInputStream inFile; private static FileOutputStream outFile; public static void main(String[] args) throws Exception { // File to encrypt. It does not have to be a text file! filename = "c:/poi-Order.xls"; // Password must be at least 8 characters (bytes) long String password = "super_secret"; inFile = new FileInputStream(filename); outFile = new FileOutputStream(filename + ".des");

PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES"); SecretKey passwordKey = keyFactory.generateSecret(keySpec);

byte[] salt = new byte[8]; Random rnd = new Random(); rnd.nextBytes(salt); int iterations = 100;

//Create the parameter spec for this salt and interation count

PBEParameterSpec parameterSpec = new PBEParameterSpec(salt, iterations);

// Create the cipher and initialize it for encryption.

Cipher cipher = Cipher.getInstance("PBEWithMD5AndDES"); cipher.init(Cipher.ENCRYPT_MODE, passwordKey, parameterSpec);

// Need to write the salt to the (encrypted) file. The // salt is needed when reconstructing the key for decryption.

outFile.write(salt);

// Read the file and encrypt its bytes.

byte[] input = new byte[128]; int bytesRead; while ((bytesRead = inFile.read(input)) != -1) { byte[] output = cipher.update(input, 0, bytesRead); if (output != null) outFile.write(output); }

byte[] output = cipher.doFinal(); if (output != null) outFile.write(output);

inFile.close(); outFile.flush(); outFile.close();

} }

You might also like