Professional Documents
Culture Documents
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
// Need to write the salt to the (encrypted) file. The // salt is needed when reconstructing the key for decryption.
outFile.write(salt);
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); }
} }