Пример #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();
    }
  }
Пример #2
0
 public static void savePublicKeyInFile(String path, PublicKey key) {
   try {
     KeyFactory fac = KeyFactory.getInstance("RSA");
     RSAPublicKeySpec RSAspec = fac.getKeySpec(key, RSAPublicKeySpec.class);
     FileOutputStream file3 = new FileOutputStream(path);
     ObjectOutputStream obj_stream = new ObjectOutputStream(file3);
     obj_stream.writeObject(RSAspec.getModulus());
     obj_stream.writeObject(RSAspec.getPublicExponent());
   } catch (Exception ex) {
     System.err.println("Probeleme de sauvegarde de la cle public dans un fichier: " + ex);
   }
 }
Пример #3
0
  private static void saveKey(String fileName, Key key) {
    try {
      FileOutputStream fos = new FileOutputStream(new File(fileName));
      ObjectOutputStream oos = new ObjectOutputStream(fos);

      oos.writeObject(key);
      oos.flush();
      fos.close();

    } catch (IOException e) {
      e.printStackTrace();
    }
  }
Пример #4
0
  /**
   * Sends the specified file to the client. File must exist or client and server threads will hang
   * indefinitely. Generates a session key to encrypt the file over transfer; session key is
   * encrypted using the client's public (asymmetric) key.
   *
   * @param aFile The name or path of the file to send.
   * @throws IOException Error reading from socket.
   */
  private void sendFile(String aFile) throws IOException {
    try {
      // get client public key
      ObjectInputStream clientPubIn = new ObjectInputStream(connectedSocket.getInputStream());
      PublicKey clientPublicKey = (PublicKey) clientPubIn.readObject();

      // generate key string and send to client using their public key encrypted with RSA
      // (asymmetric)
      String keyString = generateKeyString();
      Cipher keyCipher = Cipher.getInstance("RSA");
      keyCipher.init(Cipher.ENCRYPT_MODE, clientPublicKey);
      SealedObject sealedKeyString = new SealedObject(keyString, keyCipher);
      ObjectOutputStream testOut = new ObjectOutputStream(outToClient);
      testOut.writeObject(sealedKeyString);
      testOut.flush();

      // generate key spec from keyString
      SecretKeySpec keySpec = new SecretKeySpec(keyString.getBytes(), "DES");

      // set up encryption
      Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
      cipher.init(Cipher.ENCRYPT_MODE, keySpec);
      CipherOutputStream cipherOut = new CipherOutputStream(outToClient, cipher);

      // send file
      byte[] fileBuffer = new byte[BUFFER_SIZE];
      InputStream fileReader = new BufferedInputStream(new FileInputStream(aFile));
      int bytesRead;
      while ((bytesRead = fileReader.read(fileBuffer)) != EOF) {
        cipherOut.write(fileBuffer, 0, bytesRead);
      }
      cipherOut.flush();
      cipherOut.close();
      disconnect();
    } catch (NoSuchPaddingException nspe) {
      System.out.println("No such padding.");
    } catch (NoSuchAlgorithmException nsae) {
      System.out.println("Invalid algorithm entered");
    } catch (ClassNotFoundException cnfe) {
      System.out.println("Class not found.");
    } catch (InvalidKeyException ike) {
      System.out.println("Invalid key used for file encryption.");
    } catch (FileNotFoundException fnfe) {
      System.out.println("Invalid file entered.");
      return;
    } catch (IllegalBlockSizeException ibse) {
      System.out.println("Illegal block size used for encryption.");
    }
  }
Пример #5
0
  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);
  }
Пример #6
0
  // Needed by NativeJavaObject serializer
  public static void writeAdapterObject(Object javaObject, ObjectOutputStream out)
      throws IOException {
    Class<?> cl = javaObject.getClass();
    out.writeObject(cl.getSuperclass().getName());

    Class<?>[] interfaces = cl.getInterfaces();
    String[] interfaceNames = new String[interfaces.length];

    for (int i = 0; i < interfaces.length; i++) interfaceNames[i] = interfaces[i].getName();

    out.writeObject(interfaceNames);

    try {
      Object delegee = cl.getField("delegee").get(javaObject);
      out.writeObject(delegee);
      return;
    } catch (IllegalAccessException e) {
    } catch (NoSuchFieldException e) {
    }
    throw new IOException();
  }
Пример #7
0
 public void disconnect() {
   if (isConnected()) {
     try {
       Envelope message = new Envelope("DISCONNECT");
       message.addObject(messageIndex);
       output.writeObject(encryptCipher.doFinal(message.getBytes()));
       sock.close();
       sock = null;
     } catch (Exception e) {
       System.err.println("Error: " + e.getMessage());
       e.printStackTrace(System.err);
     }
   }
 }
Пример #8
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();
    }
  }
Пример #9
0
  public boolean connect(String username, String weakSecret, final String server, final int port) {
    System.out.println("attempting to connect");

    try {
      sock = new Socket();
      sock.connect(new InetSocketAddress(server, port));
      output = new ObjectOutputStream(sock.getOutputStream());
      input = new ObjectInputStream(sock.getInputStream());
      output.writeObject(username);

      // do DH exchange and agree on starting message index
      try {
        if (weakSecret != null) // group server connect
        {
          HashMap<String, SecretKey> secretKeys =
              DHKeyExchange.generateSecretKeyWithWeakSecret(username, weakSecret, input, output);
          if (secretKeys == null) throw new Exception("Unable to verify server");
          encryptionKey = secretKeys.get("encryptionKey");
          signingKey = secretKeys.get("signingKey");
        } else // file server connect
        {
          PublicKey fileServerPublicKey = (PublicKey) input.readObject(); // read in public key

          File savedKeys = new File("savedkeys.bin");
          ArrayList<PublicKey> knownKeys = new ArrayList<PublicKey>();
          if (savedKeys.exists()) {
            ObjectInputStream in = new ObjectInputStream(new FileInputStream(savedKeys));
            knownKeys = (ArrayList<PublicKey>) in.readObject();
          }
          if (!knownKeys.contains(fileServerPublicKey)) // prompt the user to verify the key
          {
            MessageDigest sha = MessageDigest.getInstance("SHA-1");
            byte[] digest = sha.digest(fileServerPublicKey.getEncoded());
            System.out.println("RSA key fingerprint is " + getFingerprint(digest));
            System.out.println(
                "Please verify this is correct by contacting the file server owner.");
            System.out.println(
                "Do you want to add this key to your list of saved servers? (yes/no)");
            Scanner scanner = new Scanner(System.in);
            String answer = scanner.nextLine();
            if (answer.toLowerCase().equals("yes")) {
              knownKeys.add(fileServerPublicKey);
              savedKeys.delete();
              savedKeys.createNewFile();
              ObjectOutputStream out = new ObjectOutputStream(new FileOutputStream(savedKeys));
              out.writeObject(knownKeys);
              out.flush();
              out.close();
              output.writeObject("yes");
            } else {
              output.writeObject("no");
              System.out.println("Exiting");
              System.exit(0);
            }
          } else // accpet the key without prompt
          output.writeObject("yes");

          generateRSAKeypair();
          output.writeObject(publicKey);
          HashMap<String, SecretKey> secretKeys =
              DHKeyExchange.generateSecretKeySignedExchange(
                  input, output, privateKey, fileServerPublicKey);
          if (secretKeys == null) throw new Exception("Unable to verify server");
          encryptionKey = secretKeys.get("encryptionKey");
          signingKey = secretKeys.get("signingKey");
        }

        encryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        decryptCipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        MessageDigest sha = MessageDigest.getInstance("SHA-1");
        byte[] key = sha.digest(encryptionKey.getEncoded());
        key = Arrays.copyOf(key, 16); // use only first 128 bit

        SecretKeySpec secretKeySpec = new SecretKeySpec(key, "AES");
        encryptCipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes));
        decryptCipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(ivBytes));

        BigInteger R = new BigInteger(128, new SecureRandom());
        output.writeObject(encryptCipher.doFinal(R.toByteArray()));
        BigInteger start = new BigInteger(decryptCipher.doFinal((byte[]) input.readObject()));
        if (start.compareTo(R) < 0) throw new Exception("Invalid message index from server");
        else messageIndex = start.add(BigInteger.ONE);
      } catch (Exception ex) {
        System.out.println("Failed to connect: " + ex.getMessage());
        // if anything fails, we are not connected
        sock = null;
        return false;
      }
    } catch (IOException ex) {
      return false;
    }

    return true;
  }