Ejemplo n.º 1
1
  /**
   * Load the policies from the specified file. Also checks that the policies are correctly signed.
   */
  private static void loadPolicies(
      File jarPathName, CryptoPermissions defaultPolicy, CryptoPermissions exemptPolicy)
      throws Exception {

    JarFile jf = new JarFile(jarPathName);

    Enumeration<JarEntry> entries = jf.entries();
    while (entries.hasMoreElements()) {
      JarEntry je = entries.nextElement();
      InputStream is = null;
      try {
        if (je.getName().startsWith("default_")) {
          is = jf.getInputStream(je);
          defaultPolicy.load(is);
        } else if (je.getName().startsWith("exempt_")) {
          is = jf.getInputStream(je);
          exemptPolicy.load(is);
        } else {
          continue;
        }
      } finally {
        if (is != null) {
          is.close();
        }
      }

      // Enforce the signer restraint, i.e. signer of JCE framework
      // jar should also be the signer of the two jurisdiction policy
      // jar files.
      JarVerifier.verifyPolicySigned(je.getCertificates());
    }
    // Close and nullify the JarFile reference to help GC.
    jf.close();
    jf = null;
  }
Ejemplo n.º 2
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;
 }
Ejemplo n.º 3
0
  /**
   * Callback method from _scanKeychain. If a trusted certificate is found, this method will be
   * called.
   */
  private void createTrustedCertEntry(
      String alias, long keychainItemRef, long creationDate, byte[] derStream) {
    TrustedCertEntry tce = new TrustedCertEntry();

    try {
      CertificateFactory cf = CertificateFactory.getInstance("X.509");
      InputStream input = new ByteArrayInputStream(derStream);
      X509Certificate cert = (X509Certificate) cf.generateCertificate(input);
      input.close();
      tce.cert = cert;
      tce.certRef = keychainItemRef;

      // Make a creation date.
      if (creationDate != 0) tce.date = new Date(creationDate);
      else tce.date = new Date();

      int uniqueVal = 1;
      String originalAlias = alias;

      while (entries.containsKey(alias.toLowerCase())) {
        alias = originalAlias + " " + uniqueVal;
        uniqueVal++;
      }

      entries.put(alias.toLowerCase(), tce);
    } catch (Exception e) {
      // The certificate will be skipped.
      System.err.println("KeychainStore Ignored Exception: " + e);
    }
  }
  public static byte[] readFile(File file) throws IOException {
    InputStream is = new FileInputStream(file);

    // Get the size of the file
    long length = file.length();

    if (length > Integer.MAX_VALUE) {
      return null;
    }

    // Create the byte array to hold the data
    byte[] bytes = new byte[(int) length];

    // Read in the bytes
    int offset = 0;
    int numRead = 0;
    while (offset < bytes.length
        && (numRead = is.read(bytes, offset, bytes.length - offset)) >= 0) {
      offset += numRead;
    }

    // Ensure all the bytes have been read in
    if (offset < bytes.length) {
      throw new IOException("Could not completely read file " + file.getName());
    }

    // Close the input stream and return bytes
    is.close();
    return bytes;
  }
Ejemplo n.º 5
0
 static KeyStore getKeyStore() throws Exception {
   InputStream in = new FileInputStream(new File(BASE, "rsakeys.ks"));
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, password);
   in.close();
   return ks;
 }
Ejemplo n.º 6
0
 private static KeyStore readKeyStore(String name) throws Exception {
   File file = new File(PATH, name);
   InputStream in = new FileInputStream(file);
   KeyStore ks = KeyStore.getInstance("JKS");
   ks.load(in, passwd);
   in.close();
   return ks;
 }
 private String getUrlContent(CachedUrl url) throws IOException {
   InputStream content = url.getUnfilteredInputStream();
   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   StreamUtil.copy(content, baos);
   content.close();
   String contentStr = new String(baos.toByteArray());
   baos.close();
   return contentStr;
 }
  private void writeStegoEpubFile(InputStream is, OutputStream os, String stegoString)
      throws IOException {
    ZipInputStream zipInputStream = new ZipInputStream(is);
    ZipEntry entry;
    ZipOutputStream zos = new ZipOutputStream(os);
    HashMap<String, ZipEntry> nameZipEntryMap = new HashMap<String, ZipEntry>();
    HashMap<String, String> nameStringDataMap = new HashMap<String, String>();
    while ((entry = zipInputStream.getNextEntry()) != null) {
      String name = entry.getName();
      boolean needFile = false;
      String extension = null;
      for (String e : extensions) {
        if (name.toLowerCase().endsWith(e)) {
          extension = e;
          needFile = true;
          break;
        }
      }
      if (!needFile) {
        writeZipFile(zipInputStream, zos, entry.getName());
        continue;
      }

      String currentEntryData = readFile(zipInputStream);
      if (!nameZipEntryMap.containsKey(extension)
          || entry.getSize() > nameZipEntryMap.get(extension).getSize()) {
        if (nameZipEntryMap.containsKey(extension)) {
          writeZipFile(
              new ByteArrayInputStream(
                  nameStringDataMap.get(extension).getBytes(CharEncoding.UTF_8)),
              zos,
              nameZipEntryMap.get(extension).getName());
        }
        nameZipEntryMap.put(extension, entry);
        nameStringDataMap.put(extension, currentEntryData);
      } else {
        writeZipFile(
            new ByteArrayInputStream(currentEntryData.getBytes(CharEncoding.UTF_8)),
            zos,
            entry.getName());
      }
    }

    for (String extension : nameZipEntryMap.keySet()) {
      String stegoFile = getStegoFile(nameStringDataMap.get(extension), stegoString, extension);
      InputStream newis = new ByteArrayInputStream(stegoFile.getBytes(CharEncoding.UTF_8));
      writeZipFile(newis, zos, nameZipEntryMap.get(extension).getName());
      newis.close();
    }

    is.close();
    zos.close();
  }
Ejemplo n.º 9
0
  void doTest(SSLSocket sslSocket) throws Exception {
    InputStream sslIS = sslSocket.getInputStream();
    OutputStream sslOS = sslSocket.getOutputStream();

    System.out.println("  Writing");
    sslOS.write(280);
    sslOS.flush();
    System.out.println("  Reading");
    sslIS.read();

    sslSocket.close();
  }
Ejemplo n.º 10
0
 private void digest(MessageDigest[] algorithms, Resource r) throws Exception {
   InputStream in = r.openInputStream();
   byte[] data = new byte[BUFFER_SIZE];
   int size = in.read(data);
   while (size > 0) {
     for (int a = 0; a < algorithms.length; a++) {
       if (algorithms[a] != null) {
         algorithms[a].update(data, 0, size);
       }
     }
     size = in.read(data);
   }
 }
Ejemplo n.º 11
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.");
    }
  }
Ejemplo n.º 12
0
 private static byte[] getZipDigest(ZipFile zipFile, ZipEntry ze, boolean zip)
     throws ZipException, IOException, Exception {
   System.out.println("z2e: " + ze.toString());
   InputStream is = null;
   if (zip) is = zipFile.getInputStream(ze);
   else is = new FileInputStream(testDirName + ze.toString());
   MessageDigest sha = MessageDigest.getInstance("SHA-1");
   byte[] buf = new byte[1024];
   int count;
   while ((count = is.read(buf)) != -1) {
     System.out.println("Count: " + count);
     sha.update(buf, 0, count);
   }
   is.close();
   return sha.digest();
 }
Ejemplo n.º 13
0
 public static void copyStream(InputStream in, OutputStream out) throws IOException {
   byte[] data = new byte[BUFFER];
   int currentByte;
   while ((currentByte = in.read(data, 0, BUFFER)) != -1) {
     out.write(data, 0, currentByte);
   }
 }
Ejemplo n.º 14
0
 void handleRequest(InputStream in, OutputStream out) throws IOException {
   boolean newline = false;
   StringBuilder sb = new StringBuilder();
   while (true) {
     int ch = in.read();
     if (ch < 0) {
       throw new EOFException();
     }
     sb.append((char) ch);
     if (ch == '\r') {
       // empty
     } else if (ch == '\n') {
       if (newline) {
         // 2nd newline in a row, end of request
         break;
       }
       newline = true;
     } else {
       newline = false;
     }
   }
   String request = sb.toString();
   if (request.startsWith("GET / HTTP/1.") == false) {
     throw new IOException("Invalid request: " + request);
   }
   out.write("HTTP/1.0 200 OK\r\n\r\n".getBytes());
 }
Ejemplo n.º 15
0
  /**
   * Reinitialize the logging properties and reread the logging configuration.
   *
   * <p>The same rules are used for locating the configuration properties as are used at startup. So
   * normally the logging properties will be re-read from the same file that was used at startup.
   *
   * <p>Any log level definitions in the new configuration file will be applied using
   * Logger.setLevel(), if the target Logger exists.
   *
   * <p>A PropertyChangeEvent will be fired after the properties are read.
   *
   * @exception SecurityException if a security manager exists and if the caller does not have
   *     LoggingPermission("control").
   * @exception IOException if there are IO problems reading the configuration.
   */
  public void readConfiguration() throws IOException, SecurityException {
    checkPermission();

    // if a configuration class is specified, load it and use it.
    String cname = System.getProperty("java.util.logging.config.class");
    if (cname != null) {
      try {
        // Instantiate the named class.  It is its constructor's
        // responsibility to initialize the logging configuration, by
        // calling readConfiguration(InputStream) with a suitable stream.
        try {
          Class clz = ClassLoader.getSystemClassLoader().loadClass(cname);
          clz.newInstance();
          return;
        } catch (ClassNotFoundException ex) {
          Class clz = Thread.currentThread().getContextClassLoader().loadClass(cname);
          clz.newInstance();
          return;
        }
      } catch (Exception ex) {
        System.err.println("Logging configuration class \"" + cname + "\" failed");
        System.err.println("" + ex);
        // keep going and useful config file.
      }
    }

    String fname = System.getProperty("java.util.logging.config.file");
    if (fname == null) {
      fname = System.getProperty("java.home");
      if (fname == null) {
        throw new Error("Can't find java.home ??");
      }
      File f = new File(fname, "lib");
      f = new File(f, "logging.properties");
      fname = f.getCanonicalPath();
    }
    InputStream in = new FileInputStream(fname);
    BufferedInputStream bin = new BufferedInputStream(in);
    try {
      readConfiguration(bin);
    } finally {
      if (in != null) {
        in.close();
      }
    }
  }
 private void writeZipFile(InputStream is, ZipOutputStream os, String filename)
     throws IOException {
   os.putNextEntry(new ZipEntry(filename));
   byte[] buf = new byte[1024];
   int len;
   while ((len = (is.read(buf))) > 0) {
     os.write(buf, 0, len);
   }
 }
Ejemplo n.º 17
0
 byte[] read(InputStream in, int bytes) throws IOException {
   byte[] ret = new byte[bytes];
   int n = 0;
   while (n < bytes) {
     int rv = in.read(ret, n, bytes - n);
     if (rv < 0) throw (new IOException("Unexpected end-of-file"));
     n += rv;
   }
   return (ret);
 }
 @Override
 public void update(InputStream input) throws BundleException {
   getEquinoxContainer().checkAdminPermission(this, AdminPermission.LIFECYCLE);
   try {
     if (input != null) input.close();
   } catch (IOException e) {
     // do nothing
   }
   ((EquinoxSystemModule) getModule()).asyncUpdate();
 }
Ejemplo n.º 19
0
    public void run() {
      try {
        URL url = new URL(protocol + "://localhost:" + port + "/test1/" + f);
        HttpURLConnection urlc = (HttpURLConnection) url.openConnection();
        if (urlc instanceof HttpsURLConnection) {
          HttpsURLConnection urlcs = (HttpsURLConnection) urlc;
          urlcs.setHostnameVerifier(
              new HostnameVerifier() {
                public boolean verify(String s, SSLSession s1) {
                  return true;
                }
              });
          urlcs.setSSLSocketFactory(ctx.getSocketFactory());
        }
        byte[] buf = new byte[4096];

        if (fixedLen) {
          urlc.setRequestProperty("XFixed", "yes");
        }
        InputStream is = urlc.getInputStream();
        File temp = File.createTempFile("Test1", null);
        temp.deleteOnExit();
        OutputStream fout = new BufferedOutputStream(new FileOutputStream(temp));
        int c, count = 0;
        while ((c = is.read(buf)) != -1) {
          count += c;
          fout.write(buf, 0, c);
        }
        is.close();
        fout.close();

        if (count != size) {
          throw new RuntimeException("wrong amount of data returned");
        }
        String orig = root + "/" + f;
        compare(new File(orig), temp);
        temp.delete();
      } catch (Exception e) {
        e.printStackTrace();
        fail = true;
      }
    }
Ejemplo n.º 20
0
 public CodeSigner[] getCodeSigners(JarFile jar, JarEntry entry) {
   String name = entry.getName();
   if (eagerValidation && sigFileSigners.get(name) != null) {
     /*
      * Force a read of the entry data to generate the
      * verification hash.
      */
     try {
       InputStream s = jar.getInputStream(entry);
       byte[] buffer = new byte[1024];
       int n = buffer.length;
       while (n != -1) {
         n = s.read(buffer, 0, buffer.length);
       }
       s.close();
     } catch (IOException e) {
     }
   }
   return getCodeSigners(name);
 }
Ejemplo n.º 21
0
 /**
  * Watches an event.
  *
  * @param name event name
  * @param notifier event notification
  * @throws IOException I/O exception
  */
 public void watch(final String name, final EventNotifier notifier) throws IOException {
   out.write(10);
   if (esocket == null) {
     final int eport = Integer.parseInt(receive());
     // initialize event socket
     esocket = new Socket();
     esocket.connect(new InetSocketAddress(ehost, eport), 5000);
     final OutputStream os = esocket.getOutputStream();
     receive(in, os);
     os.write(0);
     os.flush();
     final InputStream is = esocket.getInputStream();
     is.read();
     listen(is);
   }
   send(name);
   info = receive();
   if (!ok()) throw new IOException(info);
   notifiers.put(name, notifier);
 }
Ejemplo n.º 22
0
 public int read() throws IOException {
   if (numLeft > 0) {
     int b = is.read();
     jv.update(b, mev);
     numLeft--;
     if (numLeft == 0) jv.update(-1, mev);
     return b;
   } else {
     return -1;
   }
 }
Ejemplo n.º 23
0
 public void run() {
   try {
     byte[] ch = new byte[50000];
     int read;
     while ((read = error.read(ch)) > 0) {
       String s = new String(ch, 0, read);
       System.out.print(s);
       System.out.flush();
     }
   } catch (Exception e) {
   }
 }
 private Class<?> getClassFromStream(
     final InputStream stream, final String classname, final File container)
     throws IOException, SecurityException {
   final ByteArrayOutputStream baos = new ByteArrayOutputStream();
   int bytesRead = -1;
   final byte[] buffer = new byte[8192];
   while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
     baos.write(buffer, 0, bytesRead);
   }
   final byte[] classData = baos.toByteArray();
   return this.defineClassFromData(container, classData, classname);
 }
Ejemplo n.º 25
0
  public static String md5(File file)
      throws NoSuchAlgorithmException, FileNotFoundException, IOException {
    MessageDigest md = MessageDigest.getInstance("MD5");

    InputStream is = new FileInputStream(file);

    byte[] buffer = new byte[8192];
    int read = 0;

    while ((read = is.read(buffer)) > 0) md.update(buffer, 0, read);

    byte[] md5 = md.digest();
    BigInteger bi = new BigInteger(1, md5);

    is.close();
    String hex = bi.toString(16);
    while (hex.length() < 32) {
      hex = "0" + hex;
    } // Padding
    return hex;
  }
  protected void checkFilter(SimulatedArchivalUnit sau) throws Exception {
    log.debug("checkFilter()");
    CachedUrl cu = sau.makeCachedUrl(sau.getUrlRoot() + "/001file.html");

    enableFilter(sau, true);
    InputStream is = cu.openForHashing();
    String expected = "001file.html This is file 1, depth 0, branch 0. foobar ";
    assertEquals(expected, StringUtil.fromInputStream(is));
    is.close();
    enableFilter(sau, false);
    cu = sau.makeCachedUrl(sau.getUrlRoot() + "/001file.html");
    is = cu.openForHashing();
    expected =
        "<HTML><HEAD><TITLE>001file.html</TITLE></HEAD><BODY>\n"
            + "This is file 1, depth 0, branch 0.<br><!-- comment -->    "
            + "Citation String   foobar<br><script>"
            + "(defun fact (n) (cond ((= n 0) 1) (t (fact (sub1 n)))))</script>\n"
            + "</BODY></HTML>";
    assertEquals(expected, StringUtil.fromInputStream(is));
    is.close();
  }
Ejemplo n.º 27
0
  private byte[] readFully(InputStream istream) throws IOException {
    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    byte[] buf = new byte[1024];
    int num = 0;

    while ((num = istream.read(buf)) != -1) {
      bout.write(buf, 0, num);
    }

    byte[] ret = bout.toByteArray();

    return ret;
  }
Ejemplo n.º 28
0
 public static void close(Object o) {
   try {
     if (o == null) return;
     if (o instanceof InputStream) {
       ((InputStream) o).close();
     } else if (o instanceof OutputStream) {
       ((OutputStream) o).flush();
       ((OutputStream) o).close();
     }
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
Ejemplo n.º 29
0
 public byte[] getHash(File file) {
   InputStream is = null;
   Digest.reset();
   try {
     int read = 0;
     is = new FileInputStream(file);
     while (is.available() > 0) {
       read = is.read(Mem, 0, Mem.length);
       Digest.update(Mem, 0, read);
     }
   } catch (FileNotFoundException ex) {
     ex.printStackTrace();
   } catch (IOException ex) {
     ex.printStackTrace();
   } finally {
     try {
       is.close();
     } catch (IOException e) {
     }
   }
   return Digest.digest();
 }
Ejemplo n.º 30
0
    public int read(byte b[], int off, int len) throws IOException {
      if ((numLeft > 0) && (numLeft < len)) {
        len = (int) numLeft;
      }

      if (numLeft > 0) {
        int n = is.read(b, off, len);
        jv.update(n, b, off, len, mev);
        numLeft -= n;
        if (numLeft == 0) jv.update(-1, b, off, len, mev);
        return n;
      } else {
        return -1;
      }
    }