FileDocCategorySizeDatePackage
PasswordEncryptor.javaAPI DocExample2372Sun Mar 28 19:07:48 BST 1999None

PasswordEncryptor

public class PasswordEncryptor extends Object

Fields Summary
Constructors Summary
Methods Summary
public static voidmain(java.lang.String[] args)


    if (args.length != 2) {
      System.err.println("Usage: java FileEncryptor filename password");
      return;
    }

    String filename = args[0];
    String password = args[1];

    if (password.length() < 8 ) {
      System.err.println("Password must be at least eight characters long");
    }
    
    try {

      FileInputStream fin = new FileInputStream(args[0]);
      FileOutputStream fout = new FileOutputStream(args[0] + ".pbe");

      // create a key
      PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray());
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
      SecretKey pbeKey = keyFactory.generateSecret(pbeKeySpec);

      // use Password Based Encryption
      byte[] salt = { (byte) 0x9C, (byte) 0x8A, (byte) 0xFF, (byte) 0xEF, 
       (byte) 0x76, (byte) 0x23, (byte) 0x29, (byte) 0x02, };
      PBEParameterSpec paramspec = new PBEParameterSpec(salt, 20);
      Cipher pbe = Cipher.getInstance("PBEWithMD5AndDES");
      pbe.init(Cipher.ENCRYPT_MODE, pbeKey, paramspec);
      
      byte[] input = new byte[64];
      while (true) {
        int bytesRead = fin.read(input);
        if (bytesRead == -1) break;
        byte[] output = pbe.update(input, 0, bytesRead);
        if (output != null) fout.write(output);
      }
      
      byte[] output = pbe.doFinal();
      if (output != null) fout.write(output);
      fin.close();
      fout.flush();
      fout.close();

    }
    catch (InvalidKeySpecException e) {
      System.err.println(e);
    }
    catch (InvalidKeyException e) {
      System.err.println(e);
    }
    catch (InvalidAlgorithmParameterException e) {
      System.err.println(e);
    }
    catch (NoSuchAlgorithmException e) {
      System.err.println(e);
      e.printStackTrace();
    }
    catch (NoSuchPaddingException e) {
      System.err.println(e);
    }
    catch (BadPaddingException e) {
      System.err.println(e);
    }
    catch (IllegalBlockSizeException e) {
      System.err.println(e);
    }
    catch (IOException e) {
      System.err.println(e);
    }