Example #1
0
  public void run() {
    try {
      ObjectInputStream ois = new ObjectInputStream(s.getInputStream());
      ObjectOutputStream oos = new ObjectOutputStream(s.getOutputStream());

      BigInteger bg = dhSpec.getG();
      BigInteger bp = dhSpec.getP();
      oos.writeObject(bg);
      oos.writeObject(bp);

      KeyPairGenerator kpg = KeyPairGenerator.getInstance("DH");
      kpg.initialize(1024);
      KeyPair kpa = (KeyPair) ois.readObject();
      KeyAgreement dh = KeyAgreement.getInstance("DH");
      KeyPair kp = kpg.generateKeyPair();

      oos.writeObject(kp);

      dh.init(kp.getPrivate());
      Key pk = dh.doPhase(kpa.getPublic(), true);

      MessageDigest sha256 = MessageDigest.getInstance("SHA-256");
      byte[] rawbits = sha256.digest(dh.generateSecret());

      Cipher c = Cipher.getInstance(CIPHER_MODE);
      SecretKey key = new SecretKeySpec(rawbits, 0, 16, "AES");
      byte ivbits[] = (byte[]) ois.readObject();
      IvParameterSpec iv = new IvParameterSpec(ivbits);
      c.init(Cipher.DECRYPT_MODE, key, iv);

      Mac m = Mac.getInstance("HmacSHA1");
      SecretKey mackey = new SecretKeySpec(rawbits, 16, 16, "HmacSHA1");
      m.init(mackey);

      byte ciphertext[], cleartext[], mac[];
      try {
        while (true) {
          ciphertext = (byte[]) ois.readObject();
          mac = (byte[]) ois.readObject();
          if (Arrays.equals(mac, m.doFinal(ciphertext))) {
            cleartext = c.update(ciphertext);
            System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
          } else {
            // System.exit(1);
            System.out.println(ct + "error");
          }
        }
      } catch (EOFException e) {
        cleartext = c.doFinal();
        System.out.println(ct + " : " + new String(cleartext, "UTF-8"));
        System.out.println("[" + ct + "]");
      } finally {
        if (ois != null) ois.close();
        if (oos != null) oos.close();
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  public static void main(String[] args) throws Exception {
    Provider p = new SampleProvider();

    // Serialize and deserialize the above Provider object
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ObjectOutputStream oos = new ObjectOutputStream(baos);
    oos.writeObject(p);
    oos.close();
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    ObjectInputStream ois = new ObjectInputStream(bais);
    Provider p2 = (Provider) ois.readObject();
    ois.close();

    checkProviderInfoEntries(p2);
  }
  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;
  }
Example #4
0
  public static void main(String[] args) {
    try {
      if (args[0].equals("-genkey")) {
        KeyPairGenerator pairgen = KeyPairGenerator.getInstance("RSA");
        SecureRandom random = new SecureRandom();
        pairgen.initialize(KEYSIZE, random);
        KeyPair keyPair = pairgen.generateKeyPair();
        ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(args[1]));
        out.writeObject(keyPair.getPublic());
        out.close();
        out = new ObjectOutputStream(new FileOutputStream(args[2]));
        out.writeObject(keyPair.getPrivate());
        out.close();
      } else if (args[0].equals("-encrypt")) {
        KeyGenerator keygen = KeyGenerator.getInstance("AES");
        SecureRandom random = new SecureRandom();
        keygen.init(random);
        SecretKey key = keygen.generateKey();

        // wrap with RSA public key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key publicKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.WRAP_MODE, publicKey);
        byte[] wrappedKey = cipher.wrap(key);
        DataOutputStream out = new DataOutputStream(new FileOutputStream(args[2]));
        out.writeInt(wrappedKey.length);
        out.write(wrappedKey);

        InputStream in = new FileInputStream(args[1]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        crypt(in, out, cipher);
        in.close();
        out.close();
      } else {
        DataInputStream in = new DataInputStream(new FileInputStream(args[1]));
        int length = in.readInt();
        byte[] wrappedKey = new byte[length];
        in.read(wrappedKey, 0, length);

        // unwrap with RSA private key
        ObjectInputStream keyIn = new ObjectInputStream(new FileInputStream(args[3]));
        Key privateKey = (Key) keyIn.readObject();
        keyIn.close();

        Cipher cipher = Cipher.getInstance("RSA");
        cipher.init(Cipher.UNWRAP_MODE, privateKey);
        Key key = cipher.unwrap(wrappedKey, "AES", Cipher.SECRET_KEY);

        OutputStream out = new FileOutputStream(args[2]);
        cipher = Cipher.getInstance("AES");
        cipher.init(Cipher.DECRYPT_MODE, key);

        crypt(in, out, cipher);
        in.close();
        out.close();
      }
    } catch (IOException e) {
      e.printStackTrace();
    } catch (GeneralSecurityException e) {
      e.printStackTrace();
    } catch (ClassNotFoundException e) {
      e.printStackTrace();
    }
  }