Example usage for java.util Arrays copyOf

List of usage examples for java.util Arrays copyOf

Introduction

In this page you can find the example usage for java.util Arrays copyOf.

Prototype

public static boolean[] copyOf(boolean[] original, int newLength) 

Source Link

Document

Copies the specified array, truncating or padding with false (if necessary) so the copy has the specified length.

Usage

From source file:Main.java

static byte[] decryptJWE(String jwe, Key privRsaKey) {
    // Log.d("","decryptJWE");

    try {//from ww  w. j a  v a 2  s  . com
        // split jwe string
        StringTokenizer tokens = new StringTokenizer(jwe, ".");
        int count = tokens.countTokens();
        // Log.d("","parts.length: "+count);

        if (count != 5)
            return null;

        String jweProtectedHeader64 = tokens.nextToken();
        String jweEncrypted64 = tokens.nextToken();
        String jweInitVector64 = tokens.nextToken();
        String cryptedBytes64 = tokens.nextToken();
        String auth_tag64 = tokens.nextToken();

        // decrypt cek using private rsa key
        byte[] cek = decryptRsaB64(jweEncrypted64, privRsaKey);

        // check cek result byte array
        if (cek == null || cek.length == 0 || (cek.length % 2) != 0)
            return null;

        int keySize = cek.length / 2;
        Log.d("", "Decryption AES: " + keySize * 8);

        // build aes_key and hmac_key
        byte aes_key[] = new byte[keySize];
        byte hmac_key[] = new byte[keySize];

        System.arraycopy(cek, 0, hmac_key, 0, keySize);
        System.arraycopy(cek, keySize, aes_key, 0, keySize);

        // decode initialization vector
        byte[] iv_key = decodeB64(jweInitVector64);

        Log.d("", "hmac_key: " + bytesToHex(hmac_key));
        Log.d("", "aes_key:  " + bytesToHex(aes_key));
        Log.d("", "iv_key:   " + bytesToHex(iv_key));

        // decrypt content using aes_key and iv_key
        byte[] cryptedBytes = decodeB64(cryptedBytes64);
        Cipher decrypt = Cipher.getInstance("AES/CBC/PKCS5Padding", "SC");
        decrypt.init(Cipher.DECRYPT_MODE, new SecretKeySpec(aes_key, "AES"), new IvParameterSpec(iv_key));
        byte[] decryptedBytes = decrypt.doFinal(cryptedBytes);

        Log.d("", "decryptedBytes:");
        Log.d("", bytesToHex(decryptedBytes));

        // validation verification
        byte[] aad = jweProtectedHeader64.getBytes();
        long al = aad.length * 8;

        // concatenate aad, iv_key, cryptedBytes and al 
        byte[] hmacData = new byte[aad.length + iv_key.length + cryptedBytes.length + 8];
        int offset = 0;
        System.arraycopy(aad, offset, hmacData, 0, aad.length);
        offset += aad.length;
        System.arraycopy(iv_key, 0, hmacData, offset, iv_key.length);
        offset += iv_key.length;
        System.arraycopy(cryptedBytes, 0, hmacData, offset, cryptedBytes.length);
        offset += cryptedBytes.length;
        ByteBuffer buffer = ByteBuffer.allocate(8);
        buffer.putLong(al);
        System.arraycopy(buffer.array(), 0, hmacData, offset, 8);

        // compute hmac
        Mac hmac = Mac.getInstance("HmacSHA256", "SC");
        hmac.init(new SecretKeySpec(hmac_key, "HmacSHA256"));
        byte[] hmacValue = hmac.doFinal(hmacData);

        // pick authentication tag
        byte[] authTag = Arrays.copyOf(hmacValue, 16);

        // validate authentication tag
        byte[] authTagRead = decodeB64(auth_tag64);
        for (int i = 0; i < 16; i++) {
            if (authTag[i] != authTagRead[i]) {
                Log.d("", "validation failed");
                return decryptedBytes;
            }
        }

        Log.d("", "validation success");

        // validation success
        return decryptedBytes;

    } catch (Exception e) {
        e.printStackTrace();
    }

    return null;
}

From source file:knowledgeMiner.mining.SentenceParserHeuristic.java

private String disambiguateTree(Parse parse, String[] predicateStrs, MappableConcept focusConcept,
        SortedMap<String, String> anchors, WMISocket wmi, OntologySocket cyc, MiningHeuristic heuristic,
        Collection<PartialAssertion> results) throws Exception {
    if (predicateStrs == null) {
        predicateStrs = new String[1];
        predicateStrs[0] = "";
    }//from   ww w. j  a  va  2  s.  com

    Parse[] children = parse.getChildren();
    String type = parse.getType();
    String text = parse.getCoveredText();

    // No children? Return value
    if (children.length == 0)
        return text;

    // Recurse to 'left'
    int childIndex = 0;
    String left = disambiguateTree(children[childIndex++], Arrays.copyOf(predicateStrs, predicateStrs.length),
            focusConcept, anchors, wmi, cyc, heuristic, results);

    // If VP or PP, add to predicate
    boolean canCreate = true;
    if (left != null) {
        if (type.equals("VP"))
            predicateStrs[0] = left.trim();
        else if (type.equals("PP")) {
            // If PP, split recursion into two predicates
            predicateStrs[0] = (predicateStrs[0] + " " + left).trim();
            if (!predicateStrs[0].equals(left)) {
                predicateStrs = Arrays.copyOf(predicateStrs, predicateStrs.length + 1);
                predicateStrs[predicateStrs.length - 1] = left;
            }
        }
    } else
        canCreate = false;

    for (; childIndex < children.length; childIndex++) {
        Parse childParse = children[childIndex];
        String result = disambiguateTree(childParse, Arrays.copyOf(predicateStrs, predicateStrs.length),
                focusConcept, anchors, wmi, cyc, heuristic, results);
        if (result == null) {
            canCreate = false;
        }
    }

    if (type.equals("VP") || type.equals("PP"))
        return null;

    // Can create and we have a target and predicate(s)
    if (canCreate && type.equals("NP") && !predicateStrs[0].isEmpty()) {
        for (String predStr : predicateStrs) {
            AssertionArgument predicate = null;
            if (isCopula(predStr)) {
                predicate = CycConstants.ISA_GENLS.getConcept();
            } else {
                // TODO Figure out a safe way to parse predicates. Probably
                // need to look at the parse code again.
                // predStr = reAnchorString(predStr, anchors);
                // predicate = new TextMappedConcept(predStr, true, true);
            }

            if (predicate == null)
                continue;

            // Return the possible noun strings
            Collection<Tree<String>> nounStrs = composeAdjNounsTree(parse, anchors);
            logger_.trace("createAssertions: " + predicate.toString() + " "
                    + nounStrs.toString().replaceAll("\\\\\n", " "));

            // Recurse through the tree and build the partial assertions
            HeuristicProvenance provenance = new HeuristicProvenance(heuristic, predStr + "+" + text);
            Collection<PartialAssertion> currAssertions = recurseStringTree(predicate, focusConcept, nounStrs,
                    provenance);

            // Add the assertions
            for (PartialAssertion pa : currAssertions)
                if (!results.contains(pa)) {
                    results.add(pa);
                    canCreate = false;
                }
        }
    }

    if (!canCreate)
        return null;

    return text;
}

From source file:de.tudarmstadt.informatik.secuso.phishedu2.backend.networkTasks.GetUrlsTask.java

protected PhishURL[] doInBackground(Integer... params) {

    if (false) {/*from   w w  w .  ja  v  a 2s.  c o m*/
        int count = params[0];
        this.type = PhishAttackType.NoPhish;
        for (PhishAttackType type : PhishAttackType.values()) {
            if (type.getValue() == params[1]) {
                this.type = type;
                break;
            }
        }
        try {
            String url = "https://api.no-phish.de/urls/" + this.type.toString() + ".json";
            HttpResponse response = new DefaultHttpClient().execute(new HttpGet(url));
            StatusLine statusLine = response.getStatusLine();
            if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
                ByteArrayOutputStream out = new ByteArrayOutputStream();
                response.getEntity().writeTo(out);
                out.close();
                BasePhishURL[] result = BackendControllerImpl.deserializeURLs(out.toString());
                if (result.length > count) {
                    result = Arrays.copyOf(result, count);
                }
                return result;
            } else {
                //Closes the connection.
                response.getEntity().getContent().close();
                throw new IOException(statusLine.getReasonPhrase());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    return new PhishURL[0];
}

From source file:edu.vt.middleware.ldap.LdapUtil.java

/**
 * Concatenates multiple arrays together.
 *
 * @param  <T>  type of array//ww  w. ja v a 2  s.c om
 * @param  first  array to concatenate. Cannot be null.
 * @param  rest  of the arrays to concatenate. May be null.
 *
 * @return  array containing the concatenation of all parameters
 */
public static <T> T[] concatArrays(final T[] first, final T[]... rest) {
    int totalLength = first.length;
    for (T[] array : rest) {
        if (array != null) {
            totalLength += array.length;
        }
    }

    final T[] result = Arrays.copyOf(first, totalLength);

    int offset = first.length;
    for (T[] array : rest) {
        if (array != null) {
            System.arraycopy(array, 0, result, offset, array.length);
            offset += array.length;
        }
    }
    return result;
}

From source file:edu.umass.cs.nio.JSONPacket.java

/**
 * @param bytes//from   w  ww.ja v  a  2s.  c  o  m
 * @return True if this {@code bytes} could be possibly (but not
 *         necessarily) be in JSON format assuming the default
 *         {@link MessageExtractor} encoding.
 */
public static final boolean couldBeJSON(byte[] bytes) {
    String str;
    try {
        str = MessageExtractor.decode(Arrays.copyOf(bytes, 4));
        return str.startsWith("{") || str.startsWith("[");
    } catch (UnsupportedEncodingException e) {
        e.printStackTrace();
    }
    return bytes[0] == '{' || bytes[0] == '[';
}

From source file:com.almende.eve.protocol.jsonrpc.NamespaceUtil.java

/**
 * Populate cache./*from ww w  . ja  va2 s  . c o  m*/
 * 
 * @param destination
 *            the destination
 * @param steps
 *            the steps
 * @param methods
 *            the methods
 * @throws IllegalAccessException
 *             the illegal access exception
 * @throws InvocationTargetException
 *             the invocation target exception
 */
private void populateCache(final Object destination, final String steps, final AnnotatedMethod[] methods)
        throws IllegalAccessException, InvocationTargetException {
    final AnnotatedClass clazz = AnnotationUtil.get(destination.getClass());
    for (final AnnotatedMethod method : clazz.getAnnotatedMethods(Namespace.class)) {
        String namespace = method.getAnnotation(Namespace.class).value();
        final Object newDest = method.getActualMethod().invoke(destination, (Object[]) null);
        if (namespace.equals("*")) {
            // divert namespace labeling to referred class.
            if (newDest != null) {
                final AnnotatedClass destClazz = AnnotationUtil.get(newDest.getClass());
                namespace = destClazz.getAnnotation(Namespace.class).value();
            } else {
                return;
            }
        }
        final String path = steps + "." + namespace;
        methods[methods.length - 1] = method;
        CACHE.put(path, Arrays.copyOf(methods, methods.length));

        // recurse:
        if (newDest != null) {
            populateCache(newDest, path, Arrays.copyOf(methods, methods.length + 1));
        }
    }
}

From source file:hivemall.common.SpaceEfficientDenseModel.java

private void ensureCapacity(final int index) {
    if (index >= size) {
        int bits = MathUtils.bitsRequired(index);
        int newSize = (1 << bits) + 1;
        int oldSize = size;
        logger.info("Expands internal array size from " + oldSize + " to " + newSize + " (" + bits + " bits)");
        this.size = newSize;
        this.weights = Arrays.copyOf(weights, newSize);
        if (covars != null) {
            this.covars = Arrays.copyOf(covars, newSize);
            Arrays.fill(covars, oldSize, newSize, HalfFloat.ONE);
        }/*from w ww.  jav a  2 s  .co  m*/
    }
}

From source file:maspack.fileutil.FileCacher.java

public static void setDefaultFsOptions(FileSystemOptions opts) throws FileSystemException {

    // SSH Defaults
    // Don't check host key
    // Use paths relative to root (as opposed to the user's home dir)
    // 10 second timeout
    SftpFileSystemConfigBuilder.getInstance().setStrictHostKeyChecking(opts, "no");
    SftpFileSystemConfigBuilder.getInstance().setUserDirIsRoot(opts, true);
    SftpFileSystemConfigBuilder.getInstance().setTimeout(opts, 10000);

    /**/*from   w  ww  .j  av  a2s  . c om*/
     * Allow connection to silly UBC servers who don't update their credentials
     */
    TrustStrategy[] ts = { new UnsafeTrustStrategy() };
    HttpFileSystemConfigBuilder httpBuilder = HttpFileSystemConfigBuilder.getInstance();
    WebdavFileSystemConfigBuilder webdavBuilder = WebdavFileSystemConfigBuilder.getInstance();

    // allow all SSL connections
    httpBuilder.setTrustStrategies(opts, ts);
    webdavBuilder.setTrustStrategies(opts, ts);

    // silly deprecated UBC cipher suite
    String[] ciphers = httpBuilder.getDefaultSSLCipherSuites();
    ciphers = Arrays.copyOf(ciphers, ciphers.length + 1);
    ciphers[ciphers.length - 1] = "SSL_RSA_WITH_RC4_128_SHA";

    httpBuilder.setEnabledSSLCipherSuites(opts, ciphers);
    webdavBuilder.setEnabledSSLCipherSuites(opts, ciphers);

}

From source file:candr.yoclip.option.OptionSetter.java

/**
 * Get the names associated with the option.
 *
 * @return the option names as a string array or an empty array if the option does not have a name associated with it.
 *//* w  w w  .  j  ava  2  s . c o  m*/
@Override
public String[] getNames() {

    return Arrays.copyOf(option.name(), option.name().length);
}

From source file:com.opengamma.maths.lowlevelapi.functions.utilities.Unique.java

/**
 * Uniques the data, duplicates are removed based on bitwise comparison of data.
 * @param data double[] the data to unique
 * @return the double[] uniqued data//from w  ww  . ja  va2  s.  c o m
 */
public static double[] bitwise(double[] data) {
    Validate.notNull(data);
    int n = data.length;
    double[] sorteddata = Sort.stateless(data);
    int j = 0;
    for (int i = 1; i < n; i++) {
        if (Double.doubleToLongBits(sorteddata[i]) != Double.doubleToLongBits(sorteddata[j])) {
            j++;
            sorteddata[j] = sorteddata[i];
        }
    }
    return Arrays.copyOf(sorteddata, j + 1);
}