/** * Copy from the copy method in StructUtil. Did not want to drag that code in. maybe this actually * should go to struct. * * @param from * @param to * @param excludes * @return * @throws Exception */ public static <T extends struct> T xcopy(struct from, T to, String... excludes) throws Exception { Arrays.sort(excludes); for (Field f : from.fields()) { if (Arrays.binarySearch(excludes, f.getName()) >= 0) continue; Object o = f.get(from); if (o == null) continue; Field tof = to.getField(f.getName()); if (tof != null) try { tof.set(to, Converter.cnv(tof.getGenericType(), o)); } catch (Exception e) { System.out.println( "Failed to convert " + f.getName() + " from " + from.getClass() + " to " + to.getClass() + " value " + o + " exception " + e); } } return to; }
private X509Certificate[] doBuild(X509Certificate[] chain, Collection otherCerts) throws CertificateException { try { PKIXBuilderParameters params = (PKIXBuilderParameters) parameterTemplate.clone(); setDate(params); // setup target constraints X509CertSelector selector = new X509CertSelector(); selector.setCertificate(chain[0]); params.setTargetCertConstraints(selector); // setup CertStores Collection certs = new ArrayList(); certs.addAll(Arrays.asList(chain)); if (otherCerts != null) { certs.addAll(otherCerts); } CertStore store = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certs)); params.addCertStore(store); // do the build CertPathBuilder builder = CertPathBuilder.getInstance("PKIX"); PKIXCertPathBuilderResult result = (PKIXCertPathBuilderResult) builder.build(params); return toArray(result.getCertPath(), result.getTrustAnchor()); } catch (GeneralSecurityException e) { throw new ValidatorException("PKIX path building failed: " + e.toString(), e); } }
/** * Initialises the Ciphers for both encryption and decryption using the generated or supplied * secret key. * * @param algorithm * @param secret * @throws Exception */ private void initSymCiphers(String algorithm, SecretKey secret) throws Exception { log.debug("initializing symmetric ciphers (pool size=%d)", cipher_pool_size); for (int i = 0; i < cipher_pool_size; i++) { encoding_ciphers[i] = symProvider != null && !symProvider.trim().isEmpty() ? Cipher.getInstance(algorithm, symProvider) : Cipher.getInstance(algorithm); encoding_ciphers[i].init(Cipher.ENCRYPT_MODE, secret); decoding_ciphers[i] = symProvider != null && !symProvider.trim().isEmpty() ? Cipher.getInstance(algorithm, symProvider) : Cipher.getInstance(algorithm); decoding_ciphers[i].init(Cipher.DECRYPT_MODE, secret); encoding_locks[i] = new ReentrantLock(); decoding_locks[i] = new ReentrantLock(); } // set the version MessageDigest digest = MessageDigest.getInstance("MD5"); digest.reset(); digest.update(secret.getEncoded()); byte[] tmp = digest.digest(); symVersion = Arrays.copyOf(tmp, tmp.length); // symVersion = byteArrayToHexString(digest.digest()); log.debug("initialized symmetric ciphers with secret key (" + symVersion.length + " bytes)"); }
/** * Converts a token to a sequence of codepoints. * * @param token token * @return codepoints */ public static int[] cps(final byte[] token) { int pos = 0; final int len = token.length; final int[] cp = new int[len]; for (int i = 0; i < len; i += cl(token, i)) cp[pos++] = cp(token, i); return pos < len ? Arrays.copyOf(cp, pos) : cp; }
/** * Ecrit la piece donnée dans le fichier temporaire sur le disque * * @param piece : pièce à écrire * @param num : numéros de la pièce */ private synchronized void writePieceTmpFile(byte[] piece, int num) { if (num < 0 || num >= this.nbPieces()) { throw new IllegalArgumentException(); } if (piece.length > _piecesize) { throw new IllegalArgumentException(); } try { RandomAccessFile writer_tmp = new RandomAccessFile(this, "rw"); FileChannel writer = writer_tmp.getChannel(); int index_piece = ((int) this.length() - this.headerSize()) / _piecesize; if (piece.length < _piecesize) { piece = Arrays.copyOf(piece, _piecesize); } Tools.write(writer, 4 + _key.length() + 4 + 4 + 4 * num, index_piece); Tools.write(writer, this.headerSize() + _piecesize * index_piece, piece); writer.force(true); writer_tmp.close(); } catch (Exception e) { System.out.println("Unable to write tmp file piece"); e.printStackTrace(); } }
public void checkPermission(Permission perm) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); boolean needsRestriction = false; String restrictor = ""; for (int i = 3; i < stack.length; i++) { String clazz = stack[i].getClassName(); String method = stack[i].getMethodName(); if (clazz.equals("java.security.AccessController") && method.equals("doPrivileged")) { break; } if (clazz.startsWith("java.") || clazz.startsWith("apple.") || clazz.startsWith("javax.") || clazz.startsWith("sun.")) { } else { needsRestriction = true; restrictor = stack[i].toString(); break; } } /* if (! needsRestriction) { System.out.println("NO RESTRICTION "+Arrays.asList(cc)); }*/ // Allow all other actions if (needsRestriction && !isImplied(perm)) { System.err.println("StrictSecurityManager.checkPermision(" + perm + ")"); System.err.println(" " + Arrays.asList(stack)); System.err.println(" " + restrictor); throw new AccessControlException("Not allowed " + perm, perm); } }
/** * Removes leading and trailing whitespaces from the specified token. * * @param token token to be trimmed * @return trimmed token */ public static byte[] trim(final byte[] token) { int s = -1; int e = token.length; while (++s < e) if (token[s] > ' ' || token[s] < 0) break; while (--e > s) if (token[e] > ' ' || token[e] < 0) break; if (++e == token.length && s == 0) return token; return s == e ? EMPTY : Arrays.copyOfRange(token, s, e); }
/** * Chops a token to the specified length and adds dots. * * @param token token to be chopped * @param max maximum length * @return chopped token */ public static byte[] chop(final byte[] token, final int max) { if (token.length <= max) return token; final byte[] tt = Arrays.copyOf(token, max); if (max > 2) tt[max - 3] = '.'; if (max > 1) tt[max - 2] = '.'; if (max > 0) tt[max - 1] = '.'; return tt; }
public Message updateState(AuthenticationMessage msg) throws AuthenticationException, GeneralSecurityException { switch (state) { case CL_CHALLANGE_SENT: { ChallangeResponseMessage crm = null; byte[] resp; if (msg instanceof ChallangeResponseMessage) { crm = (ChallangeResponseMessage) msg; resp = crm.getResponse(); } else { throw new AuthenticationException("State Error"); } if (!Arrays.equals(randNumber, resp)) { throw new AuthenticationException("Authentication Failed"); } state = SR_AUTH_SERVER; // wait for challenge ChallangeCheckStatusMessage check = new ChallangeCheckStatusMessage(); check.setOk(true); return check; } case SR_AUTH_SERVER: { ChallangeMessage cm = null; if (msg instanceof ChallangeMessage) { cm = (ChallangeMessage) msg; } else { throw new AuthenticationException("State Error"); } // send reponse ChallangeResponseMessage crm = new ChallangeResponseMessage(); byte[] passhash = UserManager.v().getPassHash(username); if (passhash == null) { throw new AuthenticationException("User has no password"); } crm.produceResponse(cm.getChallange(), passhash); authenticated = true; logger.info("User " + username + " logged in"); state = DONE_STATE; // complete the challenege-response return crm; } default: { if (msg instanceof ChallangeCheckStatusMessage) { return null; } } } throw new AuthenticationException("State Incomplete"); }
public void run() { try { InputStream in; OutputStream out; try { in = sk.getInputStream(); out = sk.getOutputStream(); } catch (IOException e) { throw (new RuntimeException(e)); } while (true) { try { int len = Utils.int32d(read(in, 4), 0); if (!auth && (len > 256)) return; Message msg = new MessageBuf(read(in, len)); String cmd = msg.string(); Object[] args = msg.list(); Object[] reply; if (auth) { Command cc = commands.get(cmd); if (cc != null) reply = cc.run(this, args); else reply = new Object[] {"nocmd"}; } else { if (cmd.equals("nonce")) { reply = new Object[] {nonce}; } else if (cmd.equals("auth")) { if (Arrays.equals((byte[]) args[0], ckey)) { reply = new Object[] {"ok"}; auth = true; } else { reply = new Object[] {"no"}; } } else { return; } } MessageBuf rb = new MessageBuf(); rb.addlist(reply); byte[] rbuf = new byte[4 + rb.size()]; Utils.uint32e(rb.size(), rbuf, 0); rb.fin(rbuf, 4); out.write(rbuf); } catch (IOException e) { return; } } } catch (InterruptedException e) { } finally { try { sk.close(); } catch (IOException e) { throw (new RuntimeException(e)); } } }
/** * Returns a partial token. * * @param token input text * @param start start position * @param end end position * @return resulting text */ public static byte[] subtoken(final byte[] token, final int start, final int end) { int s = Math.max(0, start); final int e = Math.min(end, token.length); if (s == 0 && e == token.length) return token; if (s >= e) return EMPTY; int t = Math.max(0, s - 4); for (; t != s && t < e; t += cl(token, t)) { if (t >= s) s = t; } for (; t < e; t += cl(token, t)) ; return Arrays.copyOfRange(token, s, t); }
/** * Normalizes all whitespace occurrences from the specified token. * * @param token token * @return normalized token */ public static byte[] norm(final byte[] token) { final int l = token.length; final byte[] tmp = new byte[l]; int c = 0; boolean ws1 = true; for (final byte t : token) { final boolean ws2 = ws(t); if (ws2 && ws1) continue; tmp[c++] = ws2 ? (byte) ' ' : t; ws1 = ws2; } if (c > 0 && ws(tmp[c - 1])) --c; return c == l ? tmp : Arrays.copyOf(tmp, c); }
private void checkHashSet( SimulatedArchivalUnit sau, boolean namesOnly, boolean filter, byte[] expected) throws Exception { enableFilter(sau, filter); CachedUrlSet set = sau.getAuCachedUrlSet(); byte[] hash = getHash(set, namesOnly); assertEquals(expected, hash); String parent = sau.getUrlRoot() + "/branch1"; CachedUrlSetSpec spec = new RangeCachedUrlSetSpec(parent); set = sau.makeCachedUrlSet(spec); byte[] hash2 = getHash(set, namesOnly); assertFalse(Arrays.equals(hash, hash2)); }
private int compare(Revision a, Revision b) { if (Arrays.equals(a._id, b._id)) return 0; Version va = getVersion(a); Version vb = getVersion(b); int n = va.compareTo(vb); if (n != 0) return n; if (a.created != b.created) return a.created > b.created ? 1 : -1; for (int i = 0; i < a._id.length; i++) if (a._id[i] != b._id[i]) return a._id[i] > b._id[i] ? 1 : -1; return 0; }
/** * Does the actual work for decrypting - if version does not match current cipher then tries the * previous cipher */ private Message decryptMessage(Cipher cipher, Message msg) throws Exception { EncryptHeader hdr = (EncryptHeader) msg.getHeader(this.id); if (!Arrays.equals(hdr.getVersion(), getSymVersion())) { log.warn( "attempting to use stored cipher as message does not use current encryption version "); cipher = keyMap.get(new AsciiString(hdr.getVersion())); if (cipher == null) { log.warn("unable to find a matching cipher in previous key map"); return null; } log.trace("decrypting using previous cipher version"); synchronized (cipher) { return _decrypt(cipher, msg, hdr.encryptEntireMessage()); } } return _decrypt(cipher, msg, hdr.encryptEntireMessage()); }
public boolean validate(XMLValidateContext validateContext) throws XMLSignatureException { if (validateContext == null) { throw new NullPointerException("validateContext cannot be null"); } if (validated) { return validationStatus; } Data data = dereference(validateContext); calcDigestValue = transform(data, validateContext); if (log.isLoggable(Level.FINE)) { log.log(Level.FINE, "Expected digest: " + Base64.encode(digestValue)); log.log(Level.FINE, "Actual digest: " + Base64.encode(calcDigestValue)); } validationStatus = Arrays.equals(digestValue, calcDigestValue); validated = true; return validationStatus; }
public void init(FrameworkListener... listeners) throws BundleException { if (listeners != null) { if (getEquinoxContainer().getConfiguration().getDebug().DEBUG_SYSTEM_BUNDLE) { Debug.println( "Initializing framework with framework listeners: " + listeners); // $NON-NLS-1$ } initListeners.addAll(Arrays.asList(listeners)); } else { if (getEquinoxContainer().getConfiguration().getDebug().DEBUG_SYSTEM_BUNDLE) { Debug.println("Initializing framework with framework no listeners"); // $NON-NLS-1$ } } try { ((SystemModule) getModule()).init(); } finally { if (!initListeners.isEmpty()) { getEquinoxContainer().getEventPublisher().flushFrameworkEvents(); removeInitListeners(); } } }
public boolean equals(Object o) { if (this == o) { return true; } if (!(o instanceof Reference)) { return false; } Reference oref = (Reference) o; boolean idsEqual = (id == null ? oref.getId() == null : id.equals(oref.getId())); boolean urisEqual = (uri == null ? oref.getURI() == null : uri.equals(oref.getURI())); boolean typesEqual = (type == null ? oref.getType() == null : type.equals(oref.getType())); boolean digestValuesEqual = Arrays.equals(digestValue, oref.getDigestValue()); return (digestMethod.equals(oref.getDigestMethod()) && idsEqual && urisEqual && typesEqual && transforms.equals(oref.getTransforms())); }
public String verify(JarFile jar, String... algorithms) throws IOException { if (algorithms == null || algorithms.length == 0) algorithms = new String[] {"MD5", "SHA"}; else if (algorithms.length == 1 && algorithms[0].equals("-")) return null; try { Manifest m = jar.getManifest(); if (m.getEntries().isEmpty()) return "No name sections"; for (Enumeration<JarEntry> e = jar.entries(); e.hasMoreElements(); ) { JarEntry je = e.nextElement(); if (MANIFEST_ENTRY.matcher(je.getName()).matches()) continue; Attributes nameSection = m.getAttributes(je.getName()); if (nameSection == null) return "No name section for " + je.getName(); for (String algorithm : algorithms) { try { MessageDigest md = MessageDigest.getInstance(algorithm); String expected = nameSection.getValue(algorithm + "-Digest"); if (expected != null) { byte digest[] = Base64.decodeBase64(expected); copy(jar.getInputStream(je), md); if (!Arrays.equals(digest, md.digest())) return "Invalid digest for " + je.getName() + ", " + expected + " != " + Base64.encodeBase64(md.digest()); } else reporter.error("could not find digest for " + algorithm + "-Digest"); } catch (NoSuchAlgorithmException nsae) { return "Missing digest algorithm " + algorithm; } } } } catch (Exception e) { return "Failed to verify due to exception: " + e.getMessage(); } return null; }
private X509Certificate[] doValidate(X509Certificate[] chain, PKIXBuilderParameters params) throws CertificateException { try { setDate(params); // do the validation CertPathValidator validator = CertPathValidator.getInstance("PKIX"); CertPath path = factory.generateCertPath(Arrays.asList(chain)); certPathLength = chain.length; PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(path, params); return toArray(path, result.getTrustAnchor()); } catch (GeneralSecurityException e) { if (e instanceof CertPathValidatorException) { // check cause Throwable cause = e.getCause(); if (cause != null && cause instanceof OCSPResponse.UnreliableException) { throw new ValidatorException(ValidatorException.T_OCSP_RESPONSE_UNRELIABLE); } } throw new ValidatorException("PKIX path validation failed: " + e.toString(), e); } }
ResolutionReport resolve() { if (!Module.RESOLVED_SET.contains(module.getState())) { return module.getContainer().resolve(Arrays.asList(module), true); } return null; }
/** * Returns a substring of the specified token. Note that this method does not correctly split UTF8 * character; use {@link #subtoken} instead. * * @param token input token * @param start start position * @param end end position * @return substring */ public static byte[] substring(final byte[] token, final int start, final int end) { final int s = Math.max(0, start); final int e = Math.min(end, token.length); if (s == 0 && e == token.length) return token; return s >= e ? EMPTY : Arrays.copyOfRange(token, s, e); }
private void setSymVersion(byte[] symVersion) { this.symVersion = Arrays.copyOf(symVersion, symVersion.length); }
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; } }
/** * StrictSecurityManager15 that disallows almost everything. This is used to test Quaqua in security * restricted environments. * * @author Werner Randelshofer * @version 1.0 February 10, 2007 Created. */ public class StrictSecurityManager15 extends SecurityManager { private static final List<String> ALLOWED_HOSTNAMES = Arrays.asList( new String[] { "localhost", "127.0.0.1", }); private static final List<Permission> ALLOWED_PERMISSIONS = Arrays.asList( new Permission[] { new AWTPermission("accessClipboard"), new AWTPermission("showWindowWithoutWarningBanner"), // new AWTPermission("listenToAllAWTEvents"), // new AWTPermission("accessEventQueue"), new FilePermission("/-", "read"), new LoggingPermission("control", null), new PropertyPermission("*", "read"), new PropertyPermission("apple.laf.useScreenMenuBar", "write"), new PropertyPermission("com.apple.macos.useScreenMenuBar", "write"), new PropertyPermission("swing.aatext", "write"), new PropertyPermission("sun.awt.exception.handler", "write"), new PropertyPermission("user.timezone", "write"), new ReflectPermission("suppressAccessChecks"), new RuntimePermission("accessClassInPackage.*"), new RuntimePermission("accessDeclaredMembers"), new RuntimePermission("createClassLoader"), new RuntimePermission("exitVM"), new RuntimePermission("loadLibrary.*"), new RuntimePermission("modifyThread"), new RuntimePermission("modifyThreadGroup"), new RuntimePermission("setContextClassLoader"), new RuntimePermission("canProcessApplicationEvents"), new RuntimePermission("setFactory"), new SecurityPermission("getProperty.networkaddress.cache.*"), }); /** Creates a new instance. */ public StrictSecurityManager15() {} public void checkConnect(String host, int port, Object context) { checkConnect(host, port); } public void checkConnect(String host, int port) { if (host == null) { throw new NullPointerException("host can't be null"); } if (!host.startsWith("[") && host.indexOf(':') != -1) { host = "[" + host + "]"; } if (ALLOWED_HOSTNAMES.contains(host)) { return; } String hostPort; if (port == -1) { hostPort = host; } else { hostPort = host + ":" + port; } String message = "Opening a socket connection to " + hostPort + " is restricted."; throw new AccessControlException(message, new SocketPermission(hostPort, "connect")); } private boolean isImplied(Permission perm) { for (Permission p : ALLOWED_PERMISSIONS) { if (p.implies(perm)) { return true; } } return false; } public void checkPermission(Permission perm) { StackTraceElement[] stack = Thread.currentThread().getStackTrace(); boolean needsRestriction = false; String restrictor = ""; for (int i = 3; i < stack.length; i++) { String clazz = stack[i].getClassName(); String method = stack[i].getMethodName(); if (clazz.equals("java.security.AccessController") && method.equals("doPrivileged")) { break; } if (clazz.startsWith("java.") || clazz.startsWith("apple.") || clazz.startsWith("javax.") || clazz.startsWith("sun.")) { } else { needsRestriction = true; restrictor = stack[i].toString(); break; } } /* if (! needsRestriction) { System.out.println("NO RESTRICTION "+Arrays.asList(cc)); }*/ // Allow all other actions if (needsRestriction && !isImplied(perm)) { System.err.println("StrictSecurityManager.checkPermision(" + perm + ")"); System.err.println(" " + Arrays.asList(stack)); System.err.println(" " + restrictor); throw new AccessControlException("Not allowed " + perm, perm); } } public void checkPermission(Permission perm, Object context) { // Allow all other actions throw new AccessControlException("Not allowed context ", perm); } }
@Override public int hashCode() { return (superClass.hashCode() + Arrays.hashCode(interfaces)) ^ names.size(); }