Beispiel #1
0
 private String getPublicKey(String pubKeyUrl) {
   URL url;
   InputStream in = null;
   try {
     url = new URL(pubKeyUrl);
     HttpURLConnection conn = (HttpURLConnection) url.openConnection();
     log.debug("url request in success");
     in = conn.getInputStream();
     BufferedReader br = new BufferedReader(new InputStreamReader(in));
     String readLine;
     String separator = System.getProperty("line.separator");
     StringBuilder sb = new StringBuilder();
     while ((readLine = br.readLine()) != null) {
       sb.append(readLine).append(separator);
     }
     String result = sb.toString();
     result = result.replace("-----BEGIN PUBLIC KEY-----", "");
     result = result.replace("-----END PUBLIC KEY-----", "");
     return result;
   } catch (IOException e) {
     log.error(e.getMessage());
   } finally {
     try {
       if (in != null) {
         in.close();
       }
     } catch (IOException e) {
       log.error(e.getMessage());
     }
   }
   return null;
 }
Beispiel #2
0
  String[] getMedkit(
      String[] availableResources,
      String[] requiredResources,
      String[] missions,
      double P,
      double C) {
    try {
      Runtime rt = Runtime.getRuntime();
      Process proc = rt.exec(exec);
      OutputStream os = proc.getOutputStream();
      InputStream is = proc.getInputStream();
      new ErrorReader(proc.getErrorStream()).start();

      StringBuffer sb = new StringBuffer();
      append(sb, availableResources);
      append(sb, requiredResources);
      append(sb, missions);
      sb.append(P).append('\n');
      sb.append(C).append('\n');
      os.write(sb.toString().getBytes());

      BufferedReader br = new BufferedReader(new InputStreamReader(is));
      int N = Integer.parseInt(br.readLine().trim());
      String[] ret = new String[N];
      for (int i = 0; i < N; i++) ret[i] = br.readLine().trim();
      return ret;

    } catch (Exception e) {
      System.err.println("An error occurred while executing your program");
      e.printStackTrace();
      return null;
    }
  }
Beispiel #3
0
 String[] readFile(String fn) throws IOException {
   BufferedReader br = new BufferedReader(new FileReader(fn));
   String s;
   ArrayList al = new ArrayList();
   while ((s = br.readLine()) != null) {
     al.add(s);
   }
   return (String[]) al.toArray(new String[0]);
 }
 private String readFile(InputStream stream) throws IOException {
   BufferedReader br = new BufferedReader(new InputStreamReader(stream, CharEncoding.UTF_8));
   StringBuilder sb = new StringBuilder();
   String line = br.readLine();
   while (line != null) {
     sb.append(line);
     sb.append(System.getProperty("line.separator"));
     line = br.readLine();
   }
   return sb.toString();
 }
  public static void main(String[] args) throws Exception {
    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    // get user inputted key
    byte[] userkey = null;
    do {
      System.out.println("Please enter a 8 character string to generate a Secret Key");
      userkey = (in.readLine()).getBytes();
    } while (userkey.length != 8);

    // create Key Generator instance and generate a secret key
    KeyGenerator kgen = KeyGenerator.getInstance("DES");
    SecretKey skey = kgen.generateKey();

    byte[] key = userkey;
    // Create a Secret Key based on characters entered by the user
    SecretKeySpec skeyspec = new SecretKeySpec(key, "DES");

    // Create a cipher to encrypt with
    Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
    cipher.init(Cipher.ENCRYPT_MODE, skeyspec);

    // Get message
    System.out.println("Please enter a string to encrypt");
    byte[] userstring = null;
    userstring = (in.readLine()).getBytes();

    // Encrypt message with cipher
    byte[] encrypted = cipher.doFinal(userstring);
    String enc_string = new String(encrypted);
    System.out.println("The String is encrypted as " + enc_string);

    byte[] userdecrypt = null;
    byte[] decrypted = null;

    // Get user decrypt key
    do {
      System.out.println("Please enter the 8 character key to decrypt the message");
      userdecrypt = (in.readLine()).getBytes();
    } while (userdecrypt.length != 8);

    // Reinitialize Secret Key and Cipher
    key = userdecrypt;
    SecretKeySpec decryptkey = new SecretKeySpec(key, "DES");
    cipher.init(Cipher.DECRYPT_MODE, decryptkey);

    // Decrypt message
    decrypted = cipher.doFinal(encrypted);

    if ((new String(decrypted)).equals(new String(userstring)))
      System.out.println("\nMessage decrypted as: " + (new String(decrypted)));
    else System.out.println("\nMessage was not decrypted");
  }
  public static void main(String args[]) {

    int port = 6502;
    SSLServerSocket server;

    try {
      // get the keystore into memory
      KeyStore ks = KeyStore.getInstance("JKS");
      ks.load(new FileInputStream(keyStore), keyStorePass);

      // initialize the key manager factory with the keystore data
      KeyManagerFactory kmf = KeyManagerFactory.getInstance("SunX509");
      kmf.init(ks, keyStorePass);

      // initialize the SSLContext engine
      // may throw NoSuchProvider or NoSuchAlgorithm exception
      // TLS - Transport Layer Security most generic

      SSLContext sslContext = SSLContext.getInstance("TLS");

      // Inititialize context with given KeyManagers, TrustManagers,
      // SecureRandom defaults taken if null

      sslContext.init(kmf.getKeyManagers(), null, null);

      // Get ServerSocketFactory from the context object
      ServerSocketFactory ssf = sslContext.getServerSocketFactory();
      //  Now like programming with normal server sockets
      ServerSocket serverSocket = ssf.createServerSocket(port);

      System.out.println("Accepting secure connections");

      Socket client = serverSocket.accept();
      System.out.println("Got connection");

      BufferedWriter out = new BufferedWriter(new OutputStreamWriter(client.getOutputStream()));
      BufferedReader in = new BufferedReader(new InputStreamReader(client.getInputStream()));
      String username = in.readLine();
      String password = in.readLine();

      if (username.equals("Josh") && password.equals("GoBucs")) {
        out.write("Greeting Client");
      } else {
        out.write("Sorry, you are not authorized");
      }
      out.flush();
      in.close();
      out.close();
    } catch (Exception e) {
      System.out.println("Exception thrown " + e);
    }
  }
Beispiel #7
0
 public static String loadStringFromFile(String filename) {
   String line = "";
   File file = new File(filename);
   if (!file.exists()) return line;
   try {
     BufferedReader reader = new BufferedReader(new FileReader(file));
     line = reader.readLine();
     reader.close();
   } catch (Exception e) {
     e.printStackTrace();
   }
   return line;
 }
 /** Execute the system command 'cmd' and fill an ArrayList with the results. */
 public static ArrayList<String> executeSystemCommand(String cmd) {
   if (debug) System.out.println("cmd: " + cmd);
   ArrayList<String> list = new ArrayList<>();
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec(/*comSpec +*/ cmd).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (debug) System.out.println(line);
       list.add(line);
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return list;
 }
 public static String ping(String address) {
   String reply = "Request timed out";
   try (BufferedReader br =
       new BufferedReader(
           new InputStreamReader(RUNTIME.exec("ping " + address).getInputStream()))) {
     for (String line = null; (line = br.readLine()) != null; ) {
       if (line.trim().startsWith("Reply ")) {
         reply = line;
         break;
       }
     }
   } catch (IOException e) {
     e.printStackTrace();
   }
   return reply;
 }
  /**
   * Attempts to log a client in using the authentication server. Authentication server needs to run
   * on the same host as the file server.
   *
   * @throws IOException Error reading from socket.
   */
  private void login() throws IOException {
    // set up required variables
    DatagramSocket clientSocket = new DatagramSocket();
    InetAddress authServerIP =
        InetAddress
            .getLocalHost(); // because authentication server runs on same host as file server
    byte[] dataToSend;
    byte[] receivedData = new byte[BUFFER_SIZE];

    // get username and password
    String userName = inFromClient.readLine().trim(); // get username
    String password = inFromClient.readLine().trim(); // get password
    dataToSend = new String(userName + " " + password).getBytes();

    // send the username and password for processing by authentication server
    DatagramPacket packetToSend =
        new DatagramPacket(dataToSend, dataToSend.length, authServerIP, AUTHENTICATION_PORT);
    clientSocket.send(packetToSend);

    // receive the response from the authentication server
    DatagramPacket receivedPacket = new DatagramPacket(receivedData, receivedData.length);
    clientSocket.receive(receivedPacket);
    String receivedString = new String(receivedPacket.getData()).trim();
    receivedData = receivedString.getBytes();
    if (receivedString.equals("yes")) {
      outToClient.writeBytes(receivedString); // successful login
    } else {
      outToClient.writeBytes("no"); // unsuccessful login
    }
  }
 /**
  * Runs the server. Waits for client to send a message, and then executes the command matching
  * that message.
  */
 public void run() {
   try {
     String[] clientMessage;
     // loop for commands
     do {
       clientMessage = inFromClient.readLine().trim().split(" ");
       if (clientMessage.length >= 1) {
         if (clientMessage[0].equals("get")) {
           if (clientMessage.length >= 2) {
             sendFile(clientMessage[1]);
           }
         } else if (clientMessage[0].equals("list")) {
           listFiles();
         } else if (clientMessage[0].equals("disconnect")) {
           disconnect();
         } else if (clientMessage[0].equals("login")) {
           login();
         }
       }
     } while (!clientMessage.equals("disconnect"));
   } catch (IOException e) {
     // System.out.println("Error reading from client.");
   } catch (NullPointerException npe) {
     disconnect();
   }
 }
 public static Properties getEnvironmentVariables() {
   synchronized (cygstartPath) {
     if (envVars != null) return envVars;
     envVars = new Properties();
     try (BufferedReader br =
         new BufferedReader(
             new InputStreamReader(RUNTIME.exec(comSpec + "env").getInputStream()))) {
       for (String line = null; (line = br.readLine()) != null; ) {
         // if (debug) System.out.println("getEnvironmentVariables(): line=" + line);
         int idx = line.indexOf('=');
         if (idx > 0) envVars.put(line.substring(0, idx), line.substring(idx + 1));
       }
     } catch (IOException e) {
       e.printStackTrace();
     }
     return envVars;
   }
 }
Beispiel #13
0
  private static PermissionInfo[] getPermissionInfos(URL resource, Framework framework) {
    if (resource == null) return null;
    PermissionInfo[] info = EMPTY_PERM_INFO;
    DataInputStream in = null;
    try {
      in = new DataInputStream(resource.openStream());
      ArrayList permissions = new ArrayList();
      BufferedReader reader;
      try {
        reader = new BufferedReader(new InputStreamReader(in, "UTF8")); // $NON-NLS-1$
      } catch (UnsupportedEncodingException e) {
        reader = new BufferedReader(new InputStreamReader(in));
      }

      while (true) {
        String line = reader.readLine();
        if (line == null) /* EOF */ break;
        line = line.trim();
        if ((line.length() == 0)
            || line.startsWith("#")
            || line.startsWith("//")) /* comments */ // $NON-NLS-1$ //$NON-NLS-2$
        continue;

        try {
          permissions.add(new PermissionInfo(line));
        } catch (IllegalArgumentException iae) {
          /* incorrectly encoded permission */
          if (framework != null)
            framework.publishFrameworkEvent(FrameworkEvent.ERROR, framework.getBundle(0), iae);
        }
      }
      int size = permissions.size();
      if (size > 0) info = (PermissionInfo[]) permissions.toArray(new PermissionInfo[size]);
    } catch (IOException e) {
      // do nothing
    } finally {
      try {
        if (in != null) in.close();
      } catch (IOException ee) {
        // do nothing
      }
    }
    return info;
  }
Beispiel #14
0
    public void run() {
      try {
        BufferedReader br =
            new BufferedReader(new InputStreamReader(new FileInputStream(file), charset));
        if (outputFile != null) {
          bw =
              new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outputFile), charset));
        }
        String line;
        while ((line = br.readLine()) != null) {
          filePosition += line.length() + 2;
          line = line.trim();
          if (!line.startsWith("#")) {
            String[] sides = split(line);
            if ((sides != null) && !sides[0].equals("key")) {

              if (searchPHI) {
                // Search the decrypted PHI for the searchText
                sides[0] = decrypt(sides[0]);
                if (sides[0].indexOf(searchText) != -1) {
                  output(sides[0] + " = " + sides[1] + "\n");
                }
              } else {
                // Search the trial ID for the searchText
                if (sides[1].indexOf(searchText) != -1) {
                  sides[0] = decrypt(sides[0]);
                  output(sides[0] + " = " + sides[1] + "\n");
                }
              }
            }
          }
        }
        br.close();
        if (bw != null) {
          bw.flush();
          bw.close();
        }
      } catch (Exception e) {
        append("\n\n" + e.getClass().getName() + ": " + e.getMessage() + "\n");
      }
      append("\nDone.\n");
      setMessage("Ready...");
    }
  /**
   * readPEM: Read a PEM encoded base64 stream and decode it
   *
   * @param is Base64 PEM encoded stream
   * @param hdr Header delimeter (e.g. ----------CERTIFICATE---------)
   * @param ftr Footer delimeter (e.g. ----------END CERTIFICATE---------)
   * @return decoded DER bytes
   * @throws IOException if a read error occurs
   */
  public static byte[] readPEM(InputStream is, String hdr, String ftr) throws IOException {
    logger.debug("Reading PEM hdr:" + hdr + " ftr:" + ftr);
    is.reset();
    InputStreamReader irr = new InputStreamReader(is);
    BufferedReader r = new BufferedReader(irr);

    StringBuffer buff = new StringBuffer();
    String line;
    boolean read = false;

    while ((line = r.readLine()) != null) {
      if (line.equals(hdr)) {
        read = true;
        continue;
      }
      if (line.equals(ftr)) read = false;
      if (read) buff.append(line);
    }
    return Base64.decode(buff.toString().getBytes());
  }
Beispiel #16
0
 private void handleRequest() throws IOException {
   String line = in.readLine();
   if (line == null || line.length() == 0) {
     Log.warn(Thread.currentThread().getName() + ": ignoring empty request.");
     return;
   }
   if (handleCommand(line, out) == false) {
     out.println(
         Thread.currentThread().getName() + ": didn't understand request \"" + line + "\".");
   }
 }
  public static void loadPermissions(URL url) throws IOException, PermissionParseException {

    BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
    String line;
    Pattern ignore = Pattern.compile("^\\s*(//.*)?$");
    Pattern valid =
        Pattern.compile("^\\s*permission\\s+(\\S+)" + "(\\s+\"([^\"]*)\"(,\\s+\"([^\"]*)\")?)?;$");

    Set<Permission> perms = new HashSet<Permission>();

    while ((line = in.readLine()) != null) {
      if (ignore.matcher(line).matches()) {
        continue;
      }

      Matcher matcher = valid.matcher(line);
      if (!matcher.matches()) {
        throw new PermissionParseException("invalid syntax: " + line);
      }

      int nGroups = matcher.groupCount();
      String type = matcher.group(1);
      String name = expand(nGroups >= 3 ? matcher.group(3) : null);
      String actions = expand(nGroups >= 5 ? matcher.group(5) : null);

      try {
        Permission perm = getPermission(type, name, actions);
        perms.add(perm);
      } catch (Throwable e) {
        String message =
            String.format(
                "could not instantiate permission: " + "type=%s name=%s actions=",
                type, name, actions);
        throw new PermissionParseException(message, e);
      }
    }

    in.close();

    permSet.addAll(perms);
  }
  /** Write certficate bytes into a PEM encoded string */
  public static String writePEM(byte[] bytes, String hdr, String ftr) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    Base64OutputStream b64os = new Base64OutputStream(bos);
    b64os.write(bytes);
    b64os.flush();
    b64os.close();

    ByteArrayInputStream bis = new ByteArrayInputStream(bos.toByteArray());
    InputStreamReader irr = new InputStreamReader(bis);
    BufferedReader r = new BufferedReader(irr);

    StringBuffer buff = new StringBuffer();
    String line;
    buff.append(hdr);

    while ((line = r.readLine()) != null) {
      buff.append(line + "\n");
    }
    buff.append(ftr);
    return buff.toString();
  }
Beispiel #19
0
 private boolean authenticateClient() throws IOException {
   String line = in.readLine();
   if (line == null || line.equals(secret) == false) {
     Log.warn(
         Thread.currentThread().getName()
             + ": failed authentication attempt with \""
             + line
             + "\".");
     out.println("Authentication failed");
     return false;
   }
   writeNewSecret();
   out.println("Authentication OK");
   return true;
 }
Beispiel #20
0
 private void handleClient() {
   try {
     this.in = new BufferedReader(new InputStreamReader(client.getInputStream()));
     this.out = new PrintWriter(new OutputStreamWriter(client.getOutputStream()));
     if (authenticateClient()) {
       handleRequest();
     }
     out.flush();
     out.close();
     in.close();
   } catch (Exception ex) {
     Log.warn(Thread.currentThread().getName() + ": failure handling client request.", ex);
   } finally {
     closeClientSocket();
   }
 }
  public static void main(String[] args) throws Exception {

    String digestType = args[0];
    String digestFile = args[1];

    Vector<String> digestListFiles = new Vector<String>();
    Vector<byte[]> calcDigests = new Vector<byte[]>();

    BufferedReader reader = null;
    byte[] fileContent;
    int i;

    for (i = 2; i < args.length; i++) {
      digestListFiles.add(args[i]);
    }

    // le os arquivos e calcula o digest de seus conteudos.
    for (i = 0; i < digestListFiles.size(); i++) {

      File file = new File(digestListFiles.get(i));

      fileContent = readFile(file);
      MessageDigest messageDigest;

      try {
        messageDigest = MessageDigest.getInstance(digestType);
      } catch (Exception e) {
        System.out.println("Inexistant cryptography algorithm given!");
        return;
      }

      messageDigest.update(fileContent);
      calcDigests.add(messageDigest.digest());
    }

    File digestListFile = new File(digestFile);

    // verifica se o arquivo existe.
    // caso nao exista, cria um novo.
    if (!digestListFile.exists()) digestListFile.createNewFile();

    // lista dos arquivos ja lidos
    Vector<String> fileNames = new Vector<String>();
    // lista do tipos dos digest dos arquivos
    Vector<String> fileTypes = new Vector<String>();
    // lista dos digest dos conteudos dos arquivos
    Vector<String> fileDigests = new Vector<String>();

    try {
      reader = new BufferedReader(new FileReader(digestListFile));
      String line;
      String[] splitLine;

      while ((line = reader.readLine()) != null) {
        splitLine = line.split(" ");
        fileNames.add(splitLine[0]); // le o nome do arquivo
        fileTypes.add(splitLine[1]); // le o tipo do digest
        fileDigests.add(splitLine[2]); // le o digest em hex
      }

    } catch (IOException e) {
      System.out.println("Problems reading digest file! " + e.getStackTrace().toString());
    }

    STATUS status;
    int pos;
    for (i = 0; i < digestListFiles.size(); i++) {

      // procura
      pos = find(fileNames, digestListFiles.get(i), fileTypes, digestType);

      if (pos != -1) { // achou

        // verifica se o conteudo eh igual
        if (fileDigests.get(pos).contentEquals(calcHex(calcDigests.get(i)))) {
          status = STATUS.OK; // conteudo igual
        } else {
          status = STATUS.NOTOK; // conteudo diferente
        }

      } else {
        // nao achou!
        // insere no arquivo
        writeToEOF(
            digestListFiles.get(i) + " " + digestType + " " + calcHex(calcDigests.get(i)) + "\n",
            digestListFile);

        fileNames.add(digestListFiles.get(i));
        fileTypes.add(digestType);
        fileDigests.add(calcHex(calcDigests.get(i)));

        status = STATUS.NOTFOUND;
      }

      System.out.println(
          digestListFiles.get(i)
              + " "
              + digestType
              + " "
              + calcHex(calcDigests.get(i))
              + " ("
              + status.toString()
              + ")");
    }
  }
  /**
   * Try to determine whether this application is running under Windows or some other platform by
   * examining the "os.name" property.
   */
  static {
    String os = System.getProperty("os.name");
    // String version = System.getProperty("os.version"); // for Win7, reports "6.0" on JDK7, should
    // be "6.1"; for Win8, reports "6.2" as of JDK7u17

    if (SystemUtils.startsWithIgnoreCase(os, "windows 7"))
      isWin7 = true; // reports "Windows Vista" on JDK7
    else if (SystemUtils.startsWithIgnoreCase(os, "windows 8"))
      isWin7 = true; // reports "Windows 8" as of JDK7u17
    else if (SystemUtils.startsWithIgnoreCase(os, "windows vista")) isVista = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows xp")) isWinXP = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows 2000")) isWin2k = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows nt")) isWinNT = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "windows"))
      isWin9X = true; // win95 or win98 (what about WinME?)
    else if (SystemUtils.startsWithIgnoreCase(os, "mac")) isMac = true;
    else if (SystemUtils.startsWithIgnoreCase(os, "so")) isSolaris = true; // sunos or solaris
    else if (os.equalsIgnoreCase("linux")) isLinux = true;
    else isUnix = true; // assume UNIX, e.g. AIX, HP-UX, IRIX

    String osarch = System.getProperty("os.arch");
    String arch = (osarch != null && osarch.contains("64")) ? "_x64" /* eg. 'amd64' */ : "_x32";
    String syslib = SYSLIB + arch;

    try { // loading a native lib in a static initializer ensures that it is available before any
          // method in this class is called:
      System.loadLibrary(syslib);
      System.out.println(
          "Done loading '" + System.mapLibraryName(syslib) + "', PID=" + getProcessID());
    } catch (Error e) {
      System.err.println(
          "Native library '"
              + System.mapLibraryName(syslib)
              + "' not found in 'java.library.path': "
              + System.getProperty("java.library.path"));
      throw e; // re-throw
    }

    if (isWinPlatform()) {
      System.setProperty(
          "line.separator", "\n"); // so we won't have to mess with DOS line endings ever again
      comSpec =
          getEnv(
              "comSpec"); // use native method here since getEnvironmentVariable() needs to know
                          // comSpec
      comSpec = (comSpec != null) ? comSpec + " /c " : "";

      try (BufferedReader br =
          new BufferedReader(
              new InputStreamReader(
                  RUNTIME.exec(comSpec + "ver").getInputStream()))) { // fix for Win7,8
        for (String line = null; (line = br.readLine()) != null; ) {
          if (isVista && (line.contains("6.1" /*Win7*/) || line.contains("6.2" /*Win8*/))) {
            isVista = false;
            isWin7 = true;
          }
        }
      } catch (IOException e) {
        e.printStackTrace();
      }

      String cygdir = getEnv("cygdir"); // this is set during CygWin install to "?:/cygwin/bin"
      isCygWin = (cygdir != null && !cygdir.equals("%cygdir%"));
      cygstartPath = cygdir + "/cygstart.exe"; // path to CygWin's cygutils' "cygstart" binary

      if (getDebug() && Desktop.isDesktopSupported()) {
        Desktop desktop = Desktop.getDesktop();
        for (Desktop.Action action : Desktop.Action.values())
          System.out.println(
              "Desktop action " + action + " supported?  " + desktop.isSupported(action));
      }
    }
  }