FileDocCategorySizeDatePackage
DigestEncryptor.javaAPI DocExample2148Sun Mar 28 19:07:36 BST 1999None

DigestEncryptor

public class DigestEncryptor extends Object

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


    if (args.length != 2) {
      System.err.println("Usage: java DigestEncryptor 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(filename);
      FileOutputStream fout = new FileOutputStream(filename +".des");
      FileOutputStream digest = new FileOutputStream(filename + ".des.digest");

      // create the 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);
      CipherInputStream cin = new CipherInputStream(fin, des);

      // use SHA digest algorithm
      MessageDigest sha = MessageDigest.getInstance("SHA");
      DigestInputStream din = new DigestInputStream(cin, sha);

      byte[] input = new byte[64];
      while (true) {
        int bytesRead = din.read(input);
        if (bytesRead == -1) break;
        fout.write(input, 0, bytesRead);
      }
      
      digest.write(sha.digest());
      digest.close();
      din.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 (IOException e) {
      System.err.println(e);
    }