Пример #1
0
 /**
  * Sets the public parameters to the ones given in string parameter
  *
  * @param params must be of the form g p l, where g, p, and l are the public parameters for DH key
  *     exchange
  */
 public void setPubParams(String params) {
   String[] parts = params.split(" ");
   BigInteger g = new BigInteger(parts[0]);
   BigInteger p = new BigInteger(parts[1]);
   int l = Integer.parseInt(parts[2]);
   KeyPair keyPair = getKeyPair(g, p, l);
   this.pubKey = keyPair.getPublic();
   this.privKey = keyPair.getPrivate();
   ByteArrayOutputStream baos = null;
   ObjectOutputStream oos = null;
   try {
     baos = new ByteArrayOutputStream();
     oos = new ObjectOutputStream(baos);
     oos.writeObject(pubKey);
     byte[] pubKeyBytes = baos.toByteArray();
     this.strPubKey = new Base64().encodeToString(pubKeyBytes);
     oos.close();
     baos.close();
   } catch (Exception e) {
     if (DEBUG) {
       System.out.println("Not persisted");
       e.printStackTrace();
     }
   }
 }
Пример #2
0
  /**
   * Performs a handshake for key exchange between two people. This method must be called by both
   * people to ensure that the agreement has been reached on both ends.
   *
   * @param otherKey the serialized string version of the public key for the other person. Must not
   *     be null.
   */
  public void handShake(String otherKey) {
    if (DEBUG) {
      System.out.println("Performing handshake...");
    }
    try {
      byte[] otherPubBytes = new Base64().decode(otherKey);
      ByteArrayInputStream bais = new ByteArrayInputStream(otherPubBytes);
      ObjectInputStream ois = new ObjectInputStream(bais);

      KeyAgreement keyAgree = KeyAgreement.getInstance("DiffieHellman");
      keyAgree.init(privKey);
      Key otherPub = (Key) ois.readObject();
      keyAgree.doPhase(otherPub, true);
      msgKey = keyAgree.generateSecret("DESede");
      cipher = Cipher.getInstance("DESede");
      mac = Mac.getInstance("HmacSHA512");
      if (DEBUG) {
        System.out.println("Handshake completed");
      }
    } catch (Exception e) {
      System.out.println("Could not complete handshake...");
      System.out.println("Agreement not confirmed");
      if (DEBUG) {
        e.printStackTrace();
      }
    }
  }
Пример #3
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 boolean shareAESkey() {
    try {
      Envelope message = null, e = null;

      // Generate AES key
      KeyGenerator keyGen = KeyGenerator.getInstance("AES");
      AESkey = keyGen.generateKey();
      keyGen = KeyGenerator.getInstance("HmacSHA1");
      HMACkey = keyGen.generateKey();
      byte[] keyBytes = AESkey.getEncoded();
      byte[] hashBytes = HMACkey.getEncoded();
      System.out.println("AES key generated");
      System.out.println("HMAC key generated");
      System.out.println("Begin Encryption...");
      // Encrypt message  w/ provided public key
      Cipher cipher = Cipher.getInstance("RSA/ECB/PKCS1Padding");

      cipher.init(Cipher.ENCRYPT_MODE, pubKey);
      byte[] cipherBytes = cipher.doFinal(keyBytes);
      byte[] cipherBytes1 = cipher.doFinal(hashBytes);
      System.out.println("Encryption Complete");

      message = new Envelope("SKEY");
      message.addObject(cipherBytes); // Add AESkey to message
      message.addObject(cipherBytes1);
      message.addObject(nonce);
      nonce++;

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

      output.writeObject(messageBytes);

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

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

      Envelope response = Envelope.getEnvelopefromBytes(responseBytes);

      // If server indicates success, return the member list
      if (response.getMessage().equals("OK")
          && (Integer) response.getObjContents().get(0) == nonce) {
        return true;
      } else {
        return false;
      }
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
      e.printStackTrace(System.err);
      return false;
    }
  }
 public static byte[] decode(byte[] paramArrayOfByte1, byte[] paramArrayOfByte2) {
   SecretKeySpec localSecretKeySpec = new SecretKeySpec(paramArrayOfByte2, "AES");
   try {
     Cipher localCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
     localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
     byte[] arrayOfByte = localCipher.doFinal(paramArrayOfByte1);
     return arrayOfByte;
   } catch (Exception localException) {
     localException.printStackTrace();
   }
   return null;
 }
Пример #6
0
  private long addCertificateToKeychain(String alias, Certificate cert) {
    byte[] certblob = null;
    long returnValue = 0;

    try {
      certblob = cert.getEncoded();
      returnValue = _addItemToKeychain(alias, true, certblob, null);
    } catch (Exception e) {
      e.printStackTrace();
    }

    return returnValue;
  }
Пример #7
0
  // decrypts string
  public String decrypt(String toDecrypt) {
    try {
      // see the above comment for rant, replacing Encoder with Decoder... kthxbye
      // note: "above comment" no longer exists
      byte[] decoded = Base64.decode(toDecrypt);

      // decrypt
      byte[] bytes = decryptionCipher.doFinal(decoded);
      return new String(bytes, "ASCII");
    } catch (Exception e) {
      System.out.println("Decryption Error: " + e);
      e.printStackTrace();
    }
    return null;
  }
Пример #8
0
 /**
  * Generates the private RSA key from the given information paramter. The info must be RSA private
  * information and of the form "privMod privExp"
  *
  * @param info must be RSA private information and of the form "privMod privExp"
  */
 public void genRSAPrivKey(String info) {
   try {
     String[] parts = info.split(" ");
     BigInteger mod = new BigInteger(parts[0]);
     BigInteger exp = new BigInteger(parts[1]);
     KeySpec ks = (KeySpec) new RSAPrivateKeySpec(mod, exp);
     KeyFactory kf = KeyFactory.getInstance("RSA");
     privRSAKey = kf.generatePrivate(ks);
   } catch (Exception e) {
     if (DEBUG) {
       System.out.println("Could not generate the RSA private key");
       e.printStackTrace();
     }
   }
 }
  public static byte[] decode64(byte[] paramArrayOfByte) {
    SecretKeySpec localSecretKeySpec = new SecretKeySpec(BaseSecretKey, "AES");
    try {
      //      byte[] arrayOfByte1 = Base64.decodeBase64(paramArrayOfByte);
      byte[] arrayOfByte1 = Base64.decode(paramArrayOfByte, Base64.DEFAULT);

      Cipher localCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
      localCipher.init(Cipher.DECRYPT_MODE, localSecretKeySpec);
      byte[] arrayOfByte2 = localCipher.doFinal(arrayOfByte1);
      return arrayOfByte2;
    } catch (Exception localException) {
      localException.printStackTrace();
    }
    return null;
  }
Пример #10
0
  /**
   * 对字符串加密
   *
   * @param source String 要加密的字符串
   * @return byte[] 已加密的字节
   */
  public byte[] encrypt(String source) {
    try {
      // Encode the string into bytes using utf-8
      // byte[] utf8 = new sun.misc.BASE64Decoder().decodeBuffer(str);

      // Encrypt
      byte[] enc = ecipher.doFinal(source.getBytes());

      // Encode bytes to base64 to get a string
      // return new sun.misc.BASE64Encoder().encode(enc);
      return enc;
    } catch (Exception e) {
      e.printStackTrace();
    }
    return null;
  }
Пример #11
0
 static void getBytes(String inPath) {
   Scanner scan = new Scanner(inPath);
   fileType = scan.next(); // save the file name for reconstruction later
   filePath = inPath; // assign global var
   file = new File(filePath); // new file to encrypt
   Path path = Paths.get(filePath); // return the path for the file
   try {
     plainText = Files.readAllBytes(path); // attempts to read the bytes from path
   }
   // some sort of runtime error here, null size buffer error
   catch (Exception e) {
     e.printStackTrace();
   } finally {
     scan.close();
   }
 }
Пример #12
0
 /**
  * Encrypts the given msg and returns the ciphertext for the encryted message
  *
  * @param msg != null
  * @return the encrypted message or null if encryption fails
  */
 public String encryptMsg(String msg) {
   try {
     cipher.init(Cipher.ENCRYPT_MODE, msgKey);
     mac.init(msgKey);
     byte[] c1 = cipher.doFinal(msg.getBytes());
     String c1Str = new Base64().encodeToString(c1);
     byte[] m = mac.doFinal(c1);
     String mStr = new Base64().encodeToString(m);
     return (c1Str + "::::" + mStr).replace("\r\n", "_").replace("\r", "-").replace("\n", "~");
   } catch (Exception e) {
     System.out.println("Could not encrypt the message");
     if (DEBUG) {
       e.printStackTrace();
     }
     return null;
   }
 }
Пример #13
0
  /**
   * Constructs an RSA key pair and returns the public key or null if the key pair could not be
   * generated
   *
   * @return the RSA public key generated from the construction of the key pair or null if the key
   *     pair could not be generated
   */
  public Key getRSAPair() {
    try {
      SecureRandom random = new SecureRandom();
      KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA");

      generator.initialize(1024, random);
      KeyPair pair = generator.generateKeyPair();
      PublicKey pubKey = pair.getPublic();
      PrivateKey privKey = pair.getPrivate();
      privRSAKey = privKey;
      pubRSAKey = pubKey;
      return pubKey;
    } catch (Exception e) {
      if (DEBUG) {
        System.out.println("Could not get the RSA pair");
        e.printStackTrace();
      }
      return null;
    }
  }
Пример #14
0
 /**
  * Decrypts the given String and returns the decrypted message if the message is verified to come
  * from the correct sender, or null otherwise
  *
  * @param encryptedMsg != null
  * @param nonce must be the nonce sent to the sender to use in the encryption of the message
  * @return the decrypted message or null if the message is not verified
  */
 public String decryptMsgNonce(String encryptedMsg) {
   try {
     cipher.init(Cipher.DECRYPT_MODE, msgKey);
     mac.init(msgKey);
     encryptedMsg = encryptedMsg.replace("~", "\n").replace("-", "\r").replace("_", "\r\n");
     String[] encMsgParts = encryptedMsg.split("::::");
     String encMsg = encMsgParts[0];
     String checkM = encMsgParts[1];
     byte[] encBytes = new Base64().decode(encMsg);
     byte[] message = cipher.doFinal(encBytes);
     byte[] m = mac.doFinal(encBytes);
     String mStr = new Base64().encodeToString(m);
     if (mStr.equals(checkM)) {
       String mess = new String(message);
       String[] parts = mess.split(":::");
       String msg = parts[0];
       int n = Integer.parseInt(parts[1]);
       if (nonceSet.contains(n)) {
         nonceSet.remove(n);
         return msg;
       } else {
         if (DEBUG) {
           System.out.println("Nonces don't match...");
           System.out.println("Expected: " + nonceSet.toString() + ", Actual: " + n);
         }
         return null;
       }
     } else {
       if (DEBUG) {
         System.out.println("MACs don't match...");
       }
       return null;
     }
   } catch (Exception e) {
     System.out.println("Could not decrypt");
     if (DEBUG) {
       e.printStackTrace();
     }
   }
   return null;
 }
Пример #15
0
  /**
   * Decrypts the given encrypted message using reverse RSA, meaning that it uses the public key to
   * decrypt, and returns the decrypte message or null if the message could not be decrypted
   *
   * @param encMsg != null and encrypted with either this object or a similar object that has the
   *     proper decryption parameters
   * @return the string representation of the message that was decrypted or null if the message
   *     could not be decrypted
   */
  public String decryptRSA(String encMsg) {
    try {
      encMsg = encMsg.replace("::", "\n").replace("~", "\r").replace("_", "\r\n");
      Cipher cipher = Cipher.getInstance("RSA");
      cipher.init(Cipher.DECRYPT_MODE, pubRSAKey);
      String result = "";
      for (int i = 0; i < encMsg.length() / 178; i++) {
        String subMsg = encMsg.substring(i * 178, Math.min((i + 1) * 178, encMsg.length()));

        byte[] msgBytes = cipher.doFinal(new Base64().decode(subMsg));
        result += new String(msgBytes);
      }
      return result;
    } catch (Exception e) {
      System.out.println("Could not decrypt the message with RSA");
      if (DEBUG) {
        e.printStackTrace();
      }
      return null;
    }
  }
Пример #16
0
 /**
  * Creates a new MsgEncrypt object with the given parameters
  *
  * @param g != null, must satisfy DH key exchange
  * @param p != null, must satisfy DH key exchange
  * @param l must satisfy DH key exchange
  */
 private MsgEncrypt(BigInteger g, BigInteger p, int l) {
   KeyPair keyPair = getKeyPair(g, p, l);
   this.pubKey = keyPair.getPublic();
   this.privKey = keyPair.getPrivate();
   ByteArrayOutputStream baos = null;
   ObjectOutputStream oos = null;
   try {
     baos = new ByteArrayOutputStream();
     oos = new ObjectOutputStream(baos);
     oos.writeObject(pubKey);
     byte[] pubKeyBytes = baos.toByteArray();
     this.strPubKey = new Base64().encodeToString(pubKeyBytes);
     oos.close();
     baos.close();
   } catch (Exception e) {
     if (DEBUG) {
       System.out.println("Not persisted");
       e.printStackTrace();
     }
   }
 }
Пример #17
0
 /**
  * Encrypts the given message using reverse RSA (encrypts with the private key) and returns the
  * ciphertext of the message in String form or null if the message could not be encrypted
  *
  * @param msg != null
  * @return ciphertext form of the message made from RSA encryption or null if the message could
  *     not be encrypted
  */
 public String encryptRSA(String msg) {
   try {
     Cipher cipher = Cipher.getInstance("RSA");
     cipher.init(Cipher.ENCRYPT_MODE, privRSAKey);
     byte[] msgBytes = msg.getBytes();
     String result = "";
     for (int i = 0; i < (int) Math.ceil(msgBytes.length * 1.0 / 100); i++) {
       byte[] c =
           cipher.doFinal(
               Arrays.copyOfRange(msgBytes, i * 100, Math.min((i + 1) * 100, msgBytes.length)));
       result += new Base64().encodeToString(c);
     }
     return result.replace("\r\n", "_").replace("\r", "~").replace("\n", "::");
   } catch (Exception e) {
     System.out.println("Could not encrypt the message with RSA");
     if (DEBUG) {
       e.printStackTrace();
     }
     return null;
   }
 }
Пример #18
0
  private CryptUtils(String passwd) {
    try {
      char[] chars = new char[passwd.length()];
      for (int i = 0; i < chars.length; i++) chars[i] = passwd.charAt(i);
      PBEKeySpec pbeKeySpec = new PBEKeySpec(chars);
      SecretKeyFactory keyFac = SecretKeyFactory.getInstance("PBEWithMD5AndDES");
      SecretKey pbeKey = keyFac.generateSecret(pbeKeySpec);

      // Create PBE encode Cipher
      encodeCipher = Cipher.getInstance("PBEWithMD5AndDES");
      // Salt
      byte[] salt = {
        (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c,
        (byte) 0x7e, (byte) 0xc8, (byte) 0xee, (byte) 0x99
      };

      // Iteration count
      int count = 20;

      // Create PBE parameter set
      PBEParameterSpec encodePbeParamSpec = new PBEParameterSpec(salt, count);

      // Initialize PBE encode Cipher with key and parameters
      encodeCipher.init(Cipher.ENCRYPT_MODE, pbeKey, encodePbeParamSpec);

      // Create PBE decode Cipher
      decodeCipher = Cipher.getInstance("PBEWithMD5AndDES");

      // Create PBE parameter set
      PBEParameterSpec decodePbeParamSpec = new PBEParameterSpec(salt, count);

      // Initialize PBE decode Cipher with key and parameters
      decodeCipher.init(Cipher.DECRYPT_MODE, pbeKey, decodePbeParamSpec);

    } catch (NoSuchPaddingException ex) {
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
Пример #19
0
 public Cifra(byte[] chave) {
   try {
     SecretKey key = new SecretKeySpec(chave, "AES");
     // Initialization Vector para CBC
     byte[] iv = {
       0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15,
       0x16
     };
     IvParameterSpec ivSpec = new IvParameterSpec(iv);
     encrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
     encrypt.init(Cipher.ENCRYPT_MODE, key, ivSpec);
     decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding");
     decrypt.init(Cipher.DECRYPT_MODE, key, ivSpec);
   } catch (InvalidKeyException ex) {
     Logger.getLogger(Cifra.class.getName()).log(Level.SEVERE, null, ex);
   } catch (NoSuchAlgorithmException ex) {
     Logger.getLogger(Cifra.class.getName()).log(Level.SEVERE, null, ex);
   } catch (NoSuchPaddingException ex) {
     Logger.getLogger(Cifra.class.getName()).log(Level.SEVERE, null, ex);
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Пример #20
0
 /**
  * Decrypts the given String and returns the decrypted message if the message is verified to come
  * from the correct sender, or null otherwise
  *
  * @param encryptedMsg != null
  * @return the decrypted message or null if the message is not verified
  */
 public String decryptMsg(String encryptedMsg) {
   try {
     cipher.init(Cipher.DECRYPT_MODE, msgKey);
     mac.init(msgKey);
     encryptedMsg = encryptedMsg.replace("~", "\n").replace("-", "\r").replace("_", "\r\n");
     String[] encMsgParts = encryptedMsg.split("::::");
     String encMsg = encMsgParts[0];
     String checkM = encMsgParts[1];
     byte[] encBytes = new Base64().decode(encMsg);
     byte[] message = cipher.doFinal(encBytes);
     byte[] m = mac.doFinal(encBytes);
     String mStr = new Base64().encodeToString(m);
     if (mStr.equals(checkM)) return new String(message);
     if (DEBUG) {
       System.out.println("MACs don't match...");
     }
   } catch (Exception e) {
     System.out.println("Could not decrypt");
     if (DEBUG) {
       e.printStackTrace();
     }
   }
   return null;
 }
Пример #21
0
  public EncryDes() {
    try {
      // Create the key,"hshundsun2008"为随即初始化密文
      String passPhrase = "hshundsun2008";
      /* 生成秘钥 */
      KeySpec keySpec = new DESKeySpec(passPhrase.getBytes());
      SecretKey key = SecretKeyFactory.getInstance("DES").generateSecret(keySpec);
      // SecretKeySpec key = new
      // SecretKeySpec(passPhrase.getBytes(),"DES");
      /* 初始化加解密实例 */
      ecipher = Cipher.getInstance(key.getAlgorithm());
      dcipher = Cipher.getInstance(key.getAlgorithm());

      // Prepare the parameter to the ciphers
      // AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt,
      // iterationCount);
      // Create the ciphers
      ecipher.init(Cipher.ENCRYPT_MODE, key);
      dcipher.init(Cipher.DECRYPT_MODE, key);

    } catch (Exception e) {
      e.printStackTrace();
    }
  }
  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;
  }
  @SuppressWarnings("unchecked")
  public List<String> listFiles(UserToken token) {
    try {
      Envelope env = null, e = null;
      // Tell the server to return the member list
      env = new Envelope("LFILES");
      env.addObject(token); // Add requester's token
      String concat =
          token.toString() + "LFILES" + 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);

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

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

      env = Envelope.getEnvelopefromBytes(responseBytes);

      if (env.getMessage().equals("FAIL")) {
        System.out.println("Error occured in ListFiles, disconnecting");
        disconnect();
        return null;
      } else if ((Integer) env.getObjContents().get(2) == nonce) {
        List<String> files = (List<String>) env.getObjContents().get(0);
        String hash = (String) env.getObjContents().get(1);
        concat = files.toString() + 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);
        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 FAIL");
          disconnect();
        } else {
          // If server indicates success, return the member list
          if (env.getMessage().equals("OK")) {
            return files; // This cast creates compiler warnings. Sorry.
          }
        }
      } else {
        System.out.println("Nonce FAIL LFILES");
        disconnect();
        return null;
      }

      return null;
    } catch (Exception e) {
      System.err.println("Error: " + e.getMessage());
      e.printStackTrace(System.err);
      return null;
    }
  }