Example #1
0
 boolean isEnabled(long m) {
   if (enabledMechanisms != null) {
     return enabledMechanisms.contains(Long.valueOf(m));
   }
   if (disabledMechanisms != null) {
     return !disabledMechanisms.contains(Long.valueOf(m));
   }
   return true;
 }
Example #2
0
 private Set<Long> parseMechanisms(String keyword) throws IOException {
   checkDup(keyword);
   Set<Long> mechs = new HashSet<Long>();
   parseEquals();
   parseOpenBraces();
   while (true) {
     int token = nextToken();
     if (isCloseBraces(token)) {
       break;
     }
     if (token == TT_EOL) {
       continue;
     }
     if (token != TT_WORD) {
       throw excToken("Expected mechanism, read");
     }
     long mech = parseMechanism(st.sval);
     mechs.add(Long.valueOf(mech));
   }
   if (DEBUG) {
     System.out.print("mechanisms: [");
     for (Long mech : mechs) {
       System.out.print(Functions.getMechanismName(mech));
       System.out.print(", ");
     }
     System.out.println("]");
   }
   return mechs;
 }
Example #3
0
  /**
   * Creates a <tt>UUID</tt> from the string standard representation as described in the {@link
   * #toString} method.
   *
   * @param name a string that specifies a <tt>UUID</tt>.
   * @return a <tt>UUID</tt> with the specified value.
   * @throws IllegalArgumentException if name does not conform to the string representation as
   *     described in {@link #toString}.
   */
  public static UUID fromString(String name) {
    String[] components = name.split("-");
    if (components.length != 5) throw new IllegalArgumentException("Invalid UUID string: " + name);
    for (int i = 0; i < 5; i++) components[i] = "0x" + components[i];

    long mostSigBits = Long.decode(components[0]).longValue();
    mostSigBits <<= 16;
    mostSigBits |= Long.decode(components[1]).longValue();
    mostSigBits <<= 16;
    mostSigBits |= Long.decode(components[2]).longValue();

    long leastSigBits = Long.decode(components[3]).longValue();
    leastSigBits <<= 48;
    leastSigBits |= Long.decode(components[4]).longValue();

    return new UUID(mostSigBits, leastSigBits);
  }
Example #4
0
 public TcpSocket bind(TcpSocket fan, IpAddr addr, Long port) {
   try {
     InetAddress javaAddr = (addr == null) ? null : addr.peer.java;
     int javaPort = (port == null) ? 0 : port.intValue();
     socket.bind(new InetSocketAddress(javaAddr, javaPort));
     return fan;
   } catch (IOException e) {
     throw IOErr.make(e);
   }
 }
Example #5
0
 private boolean parseBody() {
   String[] parts = this.body.split("&");
   for (String part : parts) {
     String[] subParts = part.split("=");
     String key = subParts[0];
     String value = subParts[1];
     if ("bucket".equals(key)) {
       this.bucket = value;
     } else if ("object".equals(key)) {
       this.object = URLDecoder.decode(value);
     } else if ("userId".equals(key)) {
       this.userId = Long.valueOf(value);
     } else if ("transcode".equals(key)) {
       this.transcode = Long.valueOf(value) == 1;
     }
   }
   return (!StringUtils.isEmpty(this.bucket)
       && !StringUtils.isEmpty(this.object)
       && this.userId != 0);
 }
Example #6
0
 /**
  * Creates a byte array representation from the specified long value, using Java's standard
  * method.
  *
  * @param integer value to be converted
  * @return byte array
  */
 public static byte[] token(final long integer) {
   return integer >= Integer.MIN_VALUE && integer <= Integer.MAX_VALUE
       ? token((int) integer)
       : token(Long.toString(integer));
 }
Example #7
0
 /** Returns val represented by the specified number of hex digits. */
 private static String digits(long val, int digits) {
   long hi = 1L << (digits * 4);
   return Long.toHexString(hi | (val & (hi - 1))).substring(1);
 }
Example #8
0
 /* GuardedBy(lock) */
 private String generateName() {
   return "generated_" + Long.toString(nextID++); // $NON-NLS-1$;
 }
Example #9
0
  /**
   * Returns the key associated with the given alias, using the given password to recover it.
   *
   * @param alias the alias name
   * @param password the password for recovering the key. This password is used internally as the
   *     key is exported in a PKCS12 format.
   * @return the requested key, or null if the given alias does not exist or does not identify a
   *     <i>key entry</i>.
   * @exception NoSuchAlgorithmException if the algorithm for recovering the key cannot be found
   * @exception UnrecoverableKeyException if the key cannot be recovered (e.g., the given password
   *     is wrong).
   */
  public Key engineGetKey(String alias, char[] password)
      throws NoSuchAlgorithmException, UnrecoverableKeyException {
    permissionCheck();

    // An empty password is rejected by MacOS API, no private key data
    // is exported. If no password is passed (as is the case when
    // this implementation is used as browser keystore in various
    // deployment scenarios like Webstart, JFX and applets), create
    // a dummy password so MacOS API is happy.
    if (password == null || password.length == 0) {
      // Must not be a char array with only a 0, as this is an empty
      // string.
      if (random == null) {
        random = new SecureRandom();
      }
      password = Long.toString(random.nextLong()).toCharArray();
    }

    Object entry = entries.get(alias.toLowerCase());

    if (entry == null || !(entry instanceof KeyEntry)) {
      return null;
    }

    // This call gives us a PKCS12 bag, with the key inside it.
    byte[] exportedKeyInfo = _getEncodedKeyData(((KeyEntry) entry).keyRef, password);
    if (exportedKeyInfo == null) {
      return null;
    }

    PrivateKey returnValue = null;

    try {
      byte[] pkcs8KeyData = fetchPrivateKeyFromBag(exportedKeyInfo);
      byte[] encryptedKey;
      AlgorithmParameters algParams;
      ObjectIdentifier algOid;
      try {
        // get the encrypted private key
        EncryptedPrivateKeyInfo encrInfo = new EncryptedPrivateKeyInfo(pkcs8KeyData);
        encryptedKey = encrInfo.getEncryptedData();

        // parse Algorithm parameters
        DerValue val = new DerValue(encrInfo.getAlgorithm().encode());
        DerInputStream in = val.toDerInputStream();
        algOid = in.getOID();
        algParams = parseAlgParameters(in);

      } catch (IOException ioe) {
        UnrecoverableKeyException uke =
            new UnrecoverableKeyException(
                "Private key not stored as " + "PKCS#8 EncryptedPrivateKeyInfo: " + ioe);
        uke.initCause(ioe);
        throw uke;
      }

      // Use JCE to decrypt the data using the supplied password.
      SecretKey skey = getPBEKey(password);
      Cipher cipher = Cipher.getInstance(algOid.toString());
      cipher.init(Cipher.DECRYPT_MODE, skey, algParams);
      byte[] decryptedPrivateKey = cipher.doFinal(encryptedKey);
      PKCS8EncodedKeySpec kspec = new PKCS8EncodedKeySpec(decryptedPrivateKey);

      // Parse the key algorithm and then use a JCA key factory to create the private key.
      DerValue val = new DerValue(decryptedPrivateKey);
      DerInputStream in = val.toDerInputStream();

      // Ignore this -- version should be 0.
      int i = in.getInteger();

      // Get the Algorithm ID next
      DerValue[] value = in.getSequence(2);
      AlgorithmId algId = new AlgorithmId(value[0].getOID());
      String algName = algId.getName();

      // Get a key factory for this algorithm.  It's likely to be 'RSA'.
      KeyFactory kfac = KeyFactory.getInstance(algName);
      returnValue = kfac.generatePrivate(kspec);
    } catch (Exception e) {
      UnrecoverableKeyException uke =
          new UnrecoverableKeyException("Get Key failed: " + e.getMessage());
      uke.initCause(e);
      throw uke;
    }

    return returnValue;
  }
  // Program demonstrating how to create a random key and then search for the key value.
  public static void main(String[] args) {
    if (2 != args.length) {
      System.out.println("Usage: java SealedDES #KEYSIZE #NUMTHREADS");
      return;
    }

    // create object to printf to the console
    PrintStream p = new PrintStream(System.out);

    // Get the argument
    long keybits = Long.parseLong(args[0]);
    int numThreads = Integer.parseInt(args[1]);

    long maxkey = ~(0L);
    maxkey = maxkey >>> (64 - keybits);

    // Create a simple cipher
    SealedDES enccipher = new SealedDES();

    // Get a number between 0 and 2^64 - 1
    Random generator = new Random();
    long key = generator.nextLong();

    // Mask off the high bits so we get a short key
    key = key & maxkey;

    // Set up a key
    enccipher.setKey(key);

    // Generate a sample string
    String plainstr = "Johns Hopkins afraid of the big bad wolf?";

    long runstart;
    runstart = System.currentTimeMillis();
    Thread[] threads = new Thread[numThreads];
    Runnable[] decrypters = new Runnable[numThreads];

    long keySpaceSize = 0;
    if (numThreads > 0) {
      keySpaceSize = maxkey / numThreads;
    }

    for (int i = 0; i < numThreads; i++) {
      SealedObject sldObj = enccipher.encrypt(plainstr);
      decrypters[i] =
          new DecryptionRunner(
              i, new SealedDES(), keySpaceSize * i, keySpaceSize * (i + 1), sldObj);
      threads[i] = new Thread(decrypters[i]);
      threads[i].start();
    }

    for (int i = 0; i < numThreads; i++) {
      try {
        threads[i].join();
      } catch (InterruptedException e) {
        System.out.println("Join on thread [" + i + "] interrupted");
        break;
      }
    }

    // Output search time
    long elapsed = System.currentTimeMillis() - runstart;
    long keys = maxkey + 1;
    System.out.println("Completed search of " + keys + " keys at " + elapsed + " milliseconds.");
  }
Example #11
0
 public void setOutBufferSize(TcpSocket fan, Long v) {
   if (in != null) throw Err.make("Must set outBufSize before connection");
   outBufSize = (v == null) ? 0 : v.intValue();
 }
Example #12
0
 public Long getOutBufferSize(TcpSocket fan) {
   return (outBufSize <= 0) ? null : Long.valueOf(outBufSize);
 }
Example #13
0
 public Long getInBufferSize(TcpSocket fan) {
   return (inBufSize <= 0) ? null : Long.valueOf(inBufSize);
 }
Example #14
0
 public Long remotePort(TcpSocket fan) {
   if (!socket.isConnected()) return null;
   return Long.valueOf(remotePort);
 }
Example #15
0
 public Long localPort(TcpSocket fan) {
   if (!socket.isBound()) return null;
   int port = socket.getLocalPort();
   if (port <= 0) return null;
   return Long.valueOf(port);
 }
Example #16
0
  public double runTest(String exec, String seed) {
    try {
      this.exec = exec;
      readFiles();
      Random r;
      try {
        r = SecureRandom.getInstance("SHA1PRNG");
        r.setSeed(Long.parseLong(seed));
      } catch (Exception e) {
        return -1;
      }
      P = r.nextDouble() * 0.04 + 0.01;
      C = r.nextDouble() * 1e-3;
      String[] medkit = getMedkit(availableResources, requiredResources, missions, P, C);
      if (medkit == null) {
        System.err.println("Got null");
        return 0;
      }
      double[] mk = new double[10000];
      for (int i = 0; i < medkit.length; i++) {
        String[] sp = medkit[i].split(" ");
        if (sp.length != 2) {
          System.err.println("Invalid return.  Element not formatted correctly: " + medkit[i]);
          return 0;
        }
        try {
          int rid = Integer.parseInt(sp[0].substring(1));
          double cnt = Double.parseDouble(sp[1]);
          if (cnt < 0 || Double.isNaN(cnt) || Double.isInfinite(cnt)) {
            System.err.println("Your return contained an invalid double");
            return 0;
          }
          mk[rid] += cnt;
        } catch (Exception e) {
          System.err.println("Invalid return.  Element not formatted correctly: " + medkit[i]);
          return 0;
        }
      }
      String[] sample = missions;
      int[] used = new int[100000];
      ArrayList<String[]> al[] = new ArrayList[10000];
      Arrays.fill(used, -1);
      for (int i = 0; i < 10000; i++) {
        al[i] = new ArrayList();
        int j = r.nextInt(used.length);
        while (used[j] != -1) {
          j = r.nextInt(used.length);
        }
        used[j] = i;
      }
      for (int i = 0; i < sample.length; i++) {
        String[] sp = sample[i].split(" ");
        int mid = Integer.parseInt(sp[0]);
        if (used[mid - 1] != -1) {
          al[used[mid - 1]].add(sp);
        }
      }
      int evac = 0;
      for (int i = 0; i < 10000; i++) {
        double[] m = (double[]) mk.clone();
        evac += eval(m, al[i]);
      }
      System.err.println("Total evacuations: " + evac + "\n");
      if (evac <= P * 10000) {
        double score = 0;
        double m = 0, v = 0;
        for (int i = 0; i < mk.length; i++) {
          m += mass[i] * mk[i];
          v += vol[i] * mk[i];
        }
        score = C * v + m;
        System.out.println("Total mass: " + m + "\n");
        System.out.println("Total volume: " + v + "\n");
        return 1000 / score;
      } else {
        System.out.println("Evacutions exceeded allowed rate");
        return 0;
      }

    } catch (Exception e) {
      System.err.println(e.toString() + "\n");
      StackTraceElement[] ste = e.getStackTrace();
      for (int i = 0; i < ste.length; i++) System.err.println(ste[i] + "\n");
      return -1;
    }
  }