FileDocCategorySizeDatePackage
ECBEncryptor.javaAPI DocExample2092Sun Mar 28 19:07:40 BST 1999None

ECBEncryptor.java

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


public class ECBEncryptor {

  public static void main(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] + ".des");

      // create a key
      byte[] desKeyData = password.getBytes();
      DESKeySpec desKeySpec = new DESKeySpec(desKeyData);
      SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
      SecretKey desKey = keyFactory.generateSecret(desKeySpec);

      // use Data Encryption Standard
      Cipher des = Cipher.getInstance("DES/ECB/PKCS5Padding");
      des.init(Cipher.ENCRYPT_MODE, desKey);
            
      byte[] input = new byte[64];
      while (true) {
        int bytesRead = fin.read(input);
        if (bytesRead == -1) break;
        byte[] output = des.update(input, 0, bytesRead);
        if (output != null) fout.write(output);
      }
      
      byte[] output = des.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 (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);
    }

  }

}