Esempio n. 1
0
 /** Sends the user a list of the files contained in the same folder as the server. */
 private void listFiles() throws IOException {
   File folder = new File(".");
   File[] listOfFiles = folder.listFiles();
   for (File f : listOfFiles) {
     outToClient.writeBytes(f.getName() + '\n');
   }
 }
Esempio n. 2
0
 /**
  * The ActionListener implementation
  *
  * @param event the event.
  */
 public void actionPerformed(ActionEvent event) {
   String searchText = textField.getText().trim();
   if (searchText.equals("") && !saveAs.isSelected() && (fileLength > 10000000)) {
     textPane.setText("Blank search text is not allowed for large IdTables.");
   } else {
     File outputFile = null;
     if (saveAs.isSelected()) {
       outputFile = chooser.getSelectedFile();
       if (outputFile != null) {
         String name = outputFile.getName();
         int k = name.lastIndexOf(".");
         if (k != -1) name = name.substring(0, k);
         name += ".txt";
         File parent = outputFile.getAbsoluteFile().getParentFile();
         outputFile = new File(parent, name);
         chooser.setSelectedFile(outputFile);
       }
       if (chooser.showSaveDialog(this) != JFileChooser.APPROVE_OPTION) System.exit(0);
       outputFile = chooser.getSelectedFile();
     }
     textPane.setText("");
     Searcher searcher = new Searcher(searchText, event.getSource().equals(searchPHI), outputFile);
     searcher.start();
   }
 }
Esempio n. 3
0
 void getTable() {
   if (chooser == null) {
     File userdir = new File(System.getProperty("user.dir"));
     chooser = new JFileChooser(userdir);
   }
   if (chooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION) {
     file = chooser.getSelectedFile();
     fileLength = file.length();
     setTitle(windowTitle + ": " + file.getAbsolutePath());
     int size = Key.getEncryptionKeySize(this, true);
     key = Key.getEncryptionKey(this, true, size);
     if (key == null) key = defaultKey;
     initCipher();
   } else System.exit(0);
 }
Esempio n. 4
0
 /**
  * Reads the raw data from the input File, encrypts and saves its contents to the output File, and
  * then save the raw data of the SecretKey used to the SecretKey File.
  *
  * @param input the File to be read and encrypted
  * @param output the File the encrypted data will be saved to
  * @param keyFile the File the SecretKey data will be saved to
  * @throws InvalidKeyException if the given key is inappropriate for initializing this cipher, or
  *     if this cipher is being initialized for decryption and requires algorithm parameters that
  *     cannot be determined from the given key, or if the given key has a keysize that exceeds the
  *     maximum allowable keysize (as determined from the configured jurisdiction policy files).
  * @throws IOException if any of the files do not exist, are a directory rather than a regular
  *     file, or for some other reason cannot be opened for reading or if an I/O error occurs.
  * @throws IllegalBlockSizeException if the cipher is a block cipher, no padding has been
  *     requested (only in encryption mode), and the total input length of the data processed by
  *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
  *     process the input data provided.
  * @throws BadPaddingException if the cipher is in decryption mode, and (un)padding has been
  *     requested, but the decrypted data is not bounded by the appropriate padding bytes
  */
 public void encrypt(File input, File output, File keyFile)
     throws InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException {
   if (debug) {
     System.out.println("Initializing encryption...");
   }
   cipher.init(Cipher.ENCRYPT_MODE, key);
   FileInputStream fis = null;
   try {
     fis = new FileInputStream(input);
     data = new byte[(int) input.length()];
     if (debug) {
       System.out.println("Reading data...");
     }
     fis.read(data);
   } finally {
     if (fis != null) {
       fis.close();
     }
   }
   if (debug) {
     System.out.println("Encrypting data...");
   }
   data = cipher.doFinal(data);
   FileOutputStream fos = null;
   try {
     fos = new FileOutputStream(output);
     if (debug) {
       System.out.println("Saving data...");
     }
     fos.write(data);
   } finally {
     if (fos != null) {
       fos.close();
     }
   }
   if (debug) {
     System.out.println("Saving key...");
   }
   data = key.getEncoded();
   fos = null;
   try {
     fos = new FileOutputStream(keyFile);
     fos.write(data);
   } finally {
     if (fos != null) {
       fos.close();
     }
   }
   if (debug) {
     System.out.println("Encryption complete!");
   }
   data = null;
 }
  public boolean upload(
      String sourceFile, String destFile, String group, UserToken token, Key key, int keyNum) {

    if (destFile.charAt(0) != '/') {
      destFile = "/" + destFile;
    }

    try {
      FileInputStream fis = new FileInputStream(sourceFile);
      File encryptFile = new File(sourceFile + "_encrypt");
      encryptFile.createNewFile();
      FileOutputStream fos = new FileOutputStream(encryptFile);

      // Initial Vector must be 16 bytes
      byte[] initialVector = {
        0x0, 0x1, 0x2, 0x3, 0x4, 0x5, 0x6, 0x7, 0x8, 0x9, 0xa, 0xb, 0xc, 0xd, 0xe, 0xf
      };
      IvParameterSpec ivs = new IvParameterSpec(initialVector);
      byte[] buf = new byte[1024];
      Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
      cipher.init(Cipher.ENCRYPT_MODE, key, ivs);
      byte[] cipherBytes;

      // create a new local encrypted file
      do {
        buf = new byte[1024];
        int n = fis.read(buf);

        if (n > 0) {
          System.out.printf(".");
        } else if (n < 0) {
          System.out.println("Read error");
        }

        cipherBytes = cipher.doFinal(buf);
        fos.write(cipherBytes);
      } while (fis.available() > 0);
      System.out.println();

      // send encrypted file to server
      Envelope message = null, env = null;
      // Tell the server to return the member list
      message = new Envelope("UPLOADF");
      message.addObject(destFile);
      message.addObject(group);
      message.addObject(token);
      message.addObject(keyNum);
      message.addObject(initialVector);

      String concat =
          destFile
              + group
              + token.toString()
              + keyNum
              + "UPLOADF"
              + nonce; // concatinates all of the objects in envelope
      byte[] hasharray = concat.getBytes(); // turn the concat into a byte array
      Mac mac = Mac.getInstance("HmacSHA1");
      mac.init(HMACkey);
      mac.update(hasharray);
      String stringhash =
          new String(mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
      message.addObject(stringhash);
      message.addObject(nonce);
      nonce++;

      byte[] messageBytes = Envelope.toByteArray(message);

      // Encrypt envelope w/ AES
      cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.ENCRYPT_MODE, AESkey);
      cipherBytes = cipher.doFinal(messageBytes);

      output.writeObject(cipherBytes);

      byte[] responseCipherBytes =
          (byte[])
              input.readObject(); // if response isnt ready it should check whether it was forged

      // Decrypt response
      cipher = Cipher.getInstance("AES");
      cipher.init(Cipher.DECRYPT_MODE, AESkey);
      byte[] responseBytes = cipher.doFinal(responseCipherBytes);

      env = Envelope.getEnvelopefromBytes(responseBytes);
      if (env.getMessage().equals("READY")) {
        System.out.printf("Meta data upload successful\n");
      } else if ((Integer) env.getObjContents().get(1) == nonce) {
        String hash = (String) env.getObjContents().get(0);
        concat = env.getMessage() + nonce; // reconstructs the hash
        hasharray = concat.getBytes();
        mac = Mac.getInstance("HmacSHA1");
        File HASHfile = new File("FHASHKey.bin");
        fis = new FileInputStream(HASHfile);
        ObjectInputStream ois = new ObjectInputStream(fis);
        Key HMACkey = (Key) ois.readObject();
        mac.init(HMACkey);
        mac.update(hasharray);
        String newhash = new String(mac.doFinal(), "UTF8");
        nonce++;

        // check hashes for equality
        if (hash.equals(newhash) != true) {
          System.out.println("HASH EQUALITY FAIL2, disconnecting for your own safety");
          disconnect();
          return false;
        }
      } else {
        System.out.println("Nonce FAIL UPLOADF");
        disconnect();
        return false;
      }
      // If server indicates success, return the member list

      FileInputStream encryptFIS = new FileInputStream(encryptFile);
      do {
        if ((Integer) env.getObjContents().get(1) == nonce) {
          buf = new byte[1024];
          if (!env.getMessage().equals("READY")) {
            System.out.printf("Server error: %s\n", env.getMessage());
            return false;
          }

          String hash = (String) env.getObjContents().get(0);
          concat = env.getMessage() + nonce; // reconstructs the hash
          hasharray = concat.getBytes();
          mac = Mac.getInstance("HmacSHA1");
          File HASHfile = new File("FHASHKey.bin");
          fis = new FileInputStream(HASHfile);
          ObjectInputStream ois = new ObjectInputStream(fis);
          Key HMACkey = (Key) ois.readObject();
          mac.init(HMACkey);
          mac.update(hasharray);
          String newhash = new String(mac.doFinal(), "UTF8");
          nonce++;

          ois.close();

          // check hashes for equality
          if (hash.equals(newhash) != true) {
            System.out.println("HASH EQUALITY FAIL3, disconnecting for your own safety");
            disconnect();
            return false;
          }

          message = new Envelope("CHUNK");
          int n = encryptFIS.read(buf); // can throw an IOException
          if (n > 0) {
            System.out.printf(".");
          } else if (n < 0) {
            System.out.println("Read error");
            return false;
          }

          message.addObject(buf);
          message.addObject(new Integer(n));
          concat = n + "CHUNK" + nonce; // concatinates all of the objects in envelope
          hasharray = concat.getBytes(); // turn the concat into a byte array
          mac = Mac.getInstance("HmacSHA1");
          mac.init(HMACkey);
          mac.update(hasharray);
          stringhash =
              new String(
                  mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
          message.addObject(stringhash);
          message.addObject(nonce);
          nonce++;

          messageBytes = Envelope.toByteArray(message);

          // Encrypt envelope w/ AES
          cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.ENCRYPT_MODE, AESkey);
          cipherBytes = cipher.doFinal(messageBytes);
          System.out.println("Concatsent" + concat);

          output.writeObject(
              cipherBytes); ///////////////////////////////////////////
                            // HERE/////////////////////////////////

          responseCipherBytes = (byte[]) input.readObject();

          // Decrypt response
          cipher.init(Cipher.DECRYPT_MODE, AESkey);
          responseBytes = cipher.doFinal(responseCipherBytes);

          env = Envelope.getEnvelopefromBytes(responseBytes);

        } else {
          System.out.println("Nonce FAIL UPLOADF");
          disconnect();
          return false;
        }
      } while (encryptFIS.available() > 0);
      encryptFIS.close();

      // If server indicates success, return the member list
      if (env.getMessage().compareTo("READY") == 0
          && (Integer) env.getObjContents().get(1) == nonce) {
        nonce++;
        message = new Envelope("EOF");
        concat = "EOF" + nonce; // concatinates all of the objects in envelope
        hasharray = concat.getBytes(); // turn the concat into a byte array
        mac = Mac.getInstance("HmacSHA1");
        mac.init(HMACkey);
        mac.update(hasharray);
        stringhash =
            new String(mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!

        message.addObject(stringhash);
        message.addObject(nonce);
        System.out.println(nonce);
        nonce++;

        messageBytes = Envelope.toByteArray(message);

        // Encrypt envelope w/ AES
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, AESkey);
        cipherBytes = cipher.doFinal(messageBytes);

        output.writeObject(cipherBytes);

        responseCipherBytes = (byte[]) input.readObject();

        // Decrypt response
        cipher.init(Cipher.DECRYPT_MODE, AESkey);
        responseBytes = cipher.doFinal(responseCipherBytes);

        env = Envelope.getEnvelopefromBytes(responseBytes);

        if (env.getMessage().compareTo("OK") == 0
            && (Integer) env.getObjContents().get(1) == nonce) {
          System.out.printf("\nFile data upload successful\n");
        } else if ((Integer) env.getObjContents().get(1) != nonce) {
          System.out.println("Nonce FAIL UPLOADF");
          disconnect();
          return false;
        } else {
          System.out.printf("\nUpload failed: %s\n", env.getMessage());
          return false;
        }
      } else if ((Integer) env.getObjContents().get(1) != nonce) {
        System.out.println("Nonce FAIL UPLOADF");
        disconnect();
        return false;
      } else {
        System.out.printf("Upload failed: %s\n", env.getMessage());
        return false;
      }
    } catch (Exception e1) {
      System.err.println("Error: " + e1.getMessage());
      e1.printStackTrace(System.err);
      return false;
    }
    return true;
  }
  public boolean download(
      String sourceFile, String destFile, UserToken token, HashMap<String, ArrayList<Key>> keys) {
    try {
      destFile = "." + destFile;

      if (sourceFile.charAt(0) == '/') {
        sourceFile = sourceFile.substring(1);
      }

      File file = new File(destFile);

      if (!file.exists()) {
        file.createNewFile();

        FileOutputStream fos = new FileOutputStream(file);
        Envelope env = new Envelope("DOWNLOADF"); // Success
        env.addObject(sourceFile);
        env.addObject(token);
        String concat =
            sourceFile
                + token.toString()
                + "DOWNLOADF"
                + nonce; // concatinates all of the objects in envelope
        byte[] hasharray = concat.getBytes(); // turn the concat into a byte array
        Mac mac = Mac.getInstance("HmacSHA1");
        mac.init(HMACkey);
        mac.update(hasharray);
        String stringhash =
            new String(mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
        env.addObject(stringhash);
        env.addObject(nonce);
        nonce++;

        byte[] envBytes = Envelope.toByteArray(env);

        // Encrypt envelope w/ AES
        Cipher cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, AESkey);
        byte[] cipherBytes = cipher.doFinal(envBytes);

        output.writeObject(cipherBytes); // here in download

        byte[] responseCipherBytes = (byte[]) input.readObject();

        // Decrypt response
        cipher.init(Cipher.DECRYPT_MODE, AESkey);
        byte[] responseBytes = cipher.doFinal(responseCipherBytes);

        env = Envelope.getEnvelopefromBytes(responseBytes);
        ShareFile sf = (ShareFile) env.getObjContents().get(2);
        int keyNum = sf.getKeyNum();
        ArrayList<Key> groupKeys = keys.get(sf.getGroup());
        Key key = groupKeys.get(keyNum);
        byte[] initialVector = sf.getIV();
        IvParameterSpec ivs = new IvParameterSpec(initialVector);
        byte[] decryptBuf = new byte[1024];

        while (env.getMessage().compareTo("CHUNK") == 0
            && (Integer) env.getObjContents().get(4) == nonce) {
          String hash = (String) env.getObjContents().get(3);
          concat =
              (Integer) env.getObjContents().get(1)
                  + env.getMessage()
                  + nonce; // reconstructs the hash
          System.out.println("Concat:" + concat);
          hasharray = concat.getBytes();
          mac = Mac.getInstance("HmacSHA1");
          File HASHfile = new File("FHASHKey.bin");
          FileInputStream fis = new FileInputStream(HASHfile);
          ObjectInputStream ois = new ObjectInputStream(fis);
          HMACkey = (Key) ois.readObject();
          mac.init(HMACkey);
          mac.update(hasharray);
          String newhash = new String(mac.doFinal(), "UTF8");
          nonce++;

          // check hashes for equality
          if (hash.equals(newhash) != true) {
            System.out.println("HASH EQUALITY FAIL1");
            disconnect();
            return false;
          } else {
            decryptBuf = new byte[1024];
            System.out.println("env.getMessage: " + env.getMessage());
            cipher = Cipher.getInstance("AES/CBC/NoPadding");
            cipher.init(Cipher.DECRYPT_MODE, key, ivs);
            decryptBuf = cipher.doFinal((byte[]) env.getObjContents().get(0));

            // Write encrypted file to disk
            fos.write(decryptBuf);
            System.out.printf(".");
            env = new Envelope("DOWNLOADF"); // Success
            concat = env.getMessage() + nonce; // concatinates all of the objects in envelope
            hasharray = concat.getBytes(); // turn the concat into a byte array
            mac = Mac.getInstance("HmacSHA1");
            mac.init(HMACkey);
            mac.update(hasharray);
            stringhash =
                new String(
                    mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
            env.addObject(stringhash);
            env.addObject(nonce);
            nonce++;

            envBytes = Envelope.toByteArray(env);

            // Encrypt envelope w/ AES
            cipher = Cipher.getInstance("AES");
            cipher.init(Cipher.ENCRYPT_MODE, AESkey);
            cipherBytes = cipher.doFinal(envBytes);

            output.writeObject(cipherBytes);

            responseCipherBytes = (byte[]) input.readObject();

            // Decrypt response
            cipher.init(Cipher.DECRYPT_MODE, AESkey);
            responseBytes = cipher.doFinal(responseCipherBytes);

            env = Envelope.getEnvelopefromBytes(responseBytes);
          }
        }
        fos.close();
        if (env.getMessage().compareTo("EOF") == 0
            && (Integer) env.getObjContents().get(1) == nonce) {
          String hash = (String) env.getObjContents().get(0);
          concat = env.getMessage() + nonce; // reconstructs the hash
          hasharray = concat.getBytes();
          mac = Mac.getInstance("HmacSHA1");
          File HASHfile = new File("FHASHKey.bin");
          FileInputStream fis = new FileInputStream(HASHfile);
          ObjectInputStream ois = new ObjectInputStream(fis);
          HMACkey = (Key) ois.readObject();
          mac.init(HMACkey);
          mac.update(hasharray);
          String newhash = new String(mac.doFinal(), "UTF8");

          if (hash.equals(newhash) != true) // check hashes for equality
          {
            System.out.println("HASH EQUALITY FAIL2");
            disconnect();
          }

          fos.close();
          System.out.printf("\nTransfer successful file %s\n", sourceFile);
          nonce++;
          env = new Envelope("OK"); // Success
          concat = env.getMessage() + nonce; // concatinates all of the objects in envelope
          hasharray = concat.getBytes(); // turn the concat into a byte array
          mac = Mac.getInstance("HmacSHA1");
          mac.init(HMACkey);
          mac.update(hasharray);
          stringhash =
              new String(
                  mac.doFinal(), "UTF8"); // turn the hash into a string for easy comparision!
          env.addObject(stringhash);
          env.addObject(nonce);
          nonce++;

          envBytes = Envelope.toByteArray(env);

          // Encrypt envelope w/ AES
          cipher = Cipher.getInstance("AES");
          cipher.init(Cipher.ENCRYPT_MODE, AESkey);
          cipherBytes = cipher.doFinal(envBytes);

          output.writeObject(cipherBytes);

        } else if ((Integer) env.getObjContents().get(1) != nonce) {
          System.out.println("Nonce FAIL DOWNLOADF");
          disconnect();
          return false;
        } else {
          System.out.printf("Error reading file %s (%s)\n", sourceFile, env.getMessage());
          file.delete();
          return false;
        }
      } else {
        System.out.printf("Error couldn't create file %s\n", destFile);
        return false;
      }

    } catch (InvalidAlgorithmParameterException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IllegalBlockSizeException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(1);
    } catch (BadPaddingException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(2);
    } catch (InvalidKeyException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(3);
    } catch (NoSuchAlgorithmException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(4);
    } catch (NoSuchPaddingException ex) {
      Logger.getLogger(FileClient.class.getName()).log(Level.SEVERE, null, ex);
      System.out.println(5);
    } catch (IOException e1) {

      System.out.printf("Error couldn't create file %s\n", destFile);
      return false;

    } catch (ClassNotFoundException e1) {
      e1.printStackTrace(System.err);
    }
    return true;
  }
Esempio n. 7
0
  /**
   * Reads the raw data from the SecretKey File, creates a SecretKey from that raw data, reads the
   * raw data from the input File, and then decrypts and saves its contents to the output File.
   *
   * @param input the File to be read and decrypted
   * @param output the File the decrypted data will be saved to
   * @param keyFile the File the SecretKey data will be loaded from
   * @throws InvalidKeyException if the given key material is shorter than 8 bytes or if the given
   *     key is inappropriate for initializing this cipher, or if this cipher is being initialized
   *     for decryption and requires algorithm parameters that cannot be determined from the given
   *     key, or if the given key has a keysize that exceeds the maximum allowable keysize (as
   *     determined from the configured jurisdiction policy files).
   * @throws IOException if any of the files do not exist, are a directory rather than a regular
   *     file, or for some other reason cannot be opened for reading or if an I/O error occurs.
   * @throws IllegalBlockSizeException if the cipher is a block cipher, no padding has been
   *     requested (only in encryption mode), and the total input length of the data processed by
   *     this cipher is not a multiple of block size; or if this encryption algorithm is unable to
   *     process the input data provided.
   * @throws BadPaddingException if the cipher is in decryption mode, and (un)padding has been
   *     requested, but the decrypted data is not bounded by the appropriate padding bytes.
   * @throws NoSuchAlgorithmException if no Provider supports a SecretKeyFactorySpi implementation
   *     for the specified algorithm.
   * @throws InvalidKeySpecException if the given key specification is inappropriate for this
   *     secret-key factory to produce a secret key.
   * @throws UnsupportedOperationException if algorithm is not DES or DESede
   */
  public void decrypt(File input, File output, File keyFile)
      throws InvalidKeyException, IOException, IllegalBlockSizeException, BadPaddingException,
          NoSuchAlgorithmException, InvalidKeySpecException {
    if (debug) {
      System.out.println("Loading key...");
    }
    FileInputStream fis = null;
    try {
      fis = new FileInputStream(keyFile);
      data = new byte[fis.available()];
      fis.read(data);
    } finally {
      if (fis != null) {
        fis.close();
      }
    }
    switch (Algorithm.valueOf(algorithm)) {
      case DES:
        key = SecretKeyFactory.getInstance(algorithm).generateSecret(new DESKeySpec(data));
        break;
      case DESede:
        key = SecretKeyFactory.getInstance(algorithm).generateSecret(new DESedeKeySpec(data));
        break;
      default:
        throw new UnsupportedOperationException("Unsupported decryption algorithm");
    }

    if (debug) {
      System.out.println("Initializing decryption...");
    }
    cipher.init(Cipher.DECRYPT_MODE, key);
    if (debug) {
      System.out.println("Reading data...");
    }
    fis = null;
    try {
      fis = new FileInputStream(input);
      data = new byte[(int) input.length()];
      fis.read(data);
    } finally {
      if (fis != null) {
        fis.close();
      }
    }
    if (debug) {
      System.out.println("Decrypting data...");
    }
    data = cipher.doFinal(data);
    if (debug) {
      System.out.println("Saving data...");
    }
    FileOutputStream fos = null;
    try {
      fos = new FileOutputStream(output);
      fos.write(data);
    } finally {
      if (fos != null) {
        fos.close();
      }
    }
    if (debug) {
      System.out.println("Decryption complete!");
    }
    data = null;
  }