FileDocCategorySizeDatePackage
DigestDecryptor.javaAPI DocExample2523Sun Mar 28 19:07:36 BST 1999None

DigestDecryptor

public class DigestDecryptor extends Object

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


    if (args.length != 3) {
      System.err.println("Usage: java DigestDecryptor infile outfile password");
      return;
    }

    String infile = args[0];
    String outfile = args[1];
    String password = args[2];

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

      FileInputStream fin = new FileInputStream(infile);
      FileOutputStream fout = new FileOutputStream(outfile);

      // get the digest
      FileInputStream digestIn = new FileInputStream(infile + ".digest");
      DataInputStream dataIn = new DataInputStream(digestIn);
      // SHA digests are always 20 bytes long 
      byte[] oldDigest = new byte[20];
      dataIn.readFully(oldDigest);
      dataIn.close();

      // 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.DECRYPT_MODE, desKey);
      CipherOutputStream cout = new CipherOutputStream(fout, des);

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

      byte[] input = new byte[64];
      while (true) {
        int bytesRead = din.read(input);
        if (bytesRead == -1) break;
        cout.write(input, 0, bytesRead);
      }
      
      byte[] newDigest = sha.digest();
      if (!MessageDigest.isEqual(newDigest, oldDigest)) {
        System.out.println("Input file appears to be corrupt!");
      }

      din.close();
      cout.flush();
      cout.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);
    }