Example usage for com.google.common.hash Hashing md5

List of usage examples for com.google.common.hash Hashing md5

Introduction

In this page you can find the example usage for com.google.common.hash Hashing md5.

Prototype

public static HashFunction md5() 

Source Link

Document

Returns a hash function implementing the MD5 hash algorithm (128 hash bits) by delegating to the MD5 MessageDigest .

Usage

From source file:org.apache.accumulo.core.file.rfile.VisMetricsGatherer.java

@Override
public void printMetrics(boolean hash, String metricWord, PrintStream out) {
    for (int i = 0; i < numLG; i++) {
        String lGName = localityGroups.get(i);
        out.print("Locality Group: ");
        if (lGName == null)
            out.println("<DEFAULT>");
        else//from w w w.  j  av a  2s .  c om
            out.println(localityGroups.get(i));
        out.printf("%-27s", metricWord);
        out.println("Number of keys" + "\t   " + "Percent of keys" + "\t" + "Number of blocks" + "\t"
                + "Percent of blocks");
        for (Entry<String, Long> entry : metric.get(lGName).asMap().entrySet()) {
            HashFunction hf = Hashing.md5();
            HashCode hc = hf.newHasher().putString(entry.getKey(), UTF_8).hash();
            if (hash)
                out.printf("%-20s", hc.toString().substring(0, 8));
            else
                out.printf("%-20s", entry.getKey());
            out.print("\t\t" + entry.getValue() + "\t\t\t");
            out.printf("%.2f", ((double) entry.getValue() / numEntries.get(i)) * 100);
            out.print("%\t\t\t");

            long blocksIn = blocks.get(lGName).get(entry.getKey());

            out.print(blocksIn + "\t\t   ");
            out.printf("%.2f", ((double) blocksIn / numBlocks.get(i)) * 100);
            out.print("%");

            out.println("");
        }
        out.println("Number of keys: " + numEntries.get(i));
        out.println();
    }
}

From source file:com.android.ant.DexExecTask.java

private String getDexFileName(File inputFile) {
    // get the filename
    String name = inputFile.getName();
    // remove the extension
    int pos = name.lastIndexOf('.');
    if (pos != -1) {
        name = name.substring(0, pos);//from ww w.ja v a  2  s.  c o  m
    }

    // add a hash of the original file path
    HashFunction hashFunction = Hashing.md5();
    HashCode hashCode = hashFunction.hashString(inputFile.getAbsolutePath(), Charsets.UTF_16LE);

    return name + "-" + hashCode.toString() + ".jar";
}

From source file:com.android.builder.packaging.PackagingUtils.java

/**
 * Computes an "application hash", a reasonably unique identifier for an app.
 * <p>// ww w.j  a v  a  2 s. c  o m
 * This is currently used by Instant Run to prevent apps on a device from guessing
 * the authentication token associated with an instant run developed app on the same
 * device.
 * <p>
 * This method creates the "secret", the field in the AppInfo class which is used as a simple
 * authentication token between the IDE and the app server.
 * <p>
 * This is not a cryptographically strong unique id; we could attempt to make a truly random
 * number here, but we'd need to store that id somewhere such that subsequent builds
 * will use the same secret, to avoid having the IDE and the app getting out of sync,
 * and there isn't really a natural place for us to store the key to make it survive across
 * a clean build. (One possibility is putting it into local.properties).
 * <p>
 * However, we have much simpler needs: we just need a key that can't be guessed from
 * a hostile app on the developer's device, and it only has a few guesses (after providing
 * the wrong secret to the server a few times, the server will shut down.) We can't
 * rely on the package name alone, since the port number is known, and the package name is
 * discoverable by the hostile app (by querying the contents of /data/data/*). Therefore
 * we also include facts that the hostile app can't know, such as as the path on the
 * developer's machine to the app project and the name of the developer's machine, etc.
 * The goal is for this secret to be reasonably stable (e.g. the same from build to build)
 * yet not something an app could guess if it only has a couple of tries.
 */
public static long computeApplicationHash(@NonNull File projectDir) {
    HashFunction hashFunction = Hashing.md5();
    Hasher hasher = hashFunction.newHasher();
    try {
        projectDir = projectDir.getCanonicalFile();
    } catch (IOException ignore) {
        // If this throws an exception the assignment won't
        // be done and we'll stick with the regular project dir
    }
    String path = projectDir.getPath();
    hasher.putBytes(path.getBytes(Charsets.UTF_8));
    String user = System.getProperty("user.name");
    if (user != null) {
        hasher.putBytes(user.getBytes(Charsets.UTF_8));
    }
    return hasher.hash().asLong();
}

From source file:org.opendaylight.openflowplugin.applications.topology.lldp.utils.LLDPDiscoveryUtils.java

/**
 * @param nodeConnectorId//w  ww.j  av a 2 s . c o m
 * @return extra authenticator for lldp security
 * @throws NoSuchAlgorithmException
 */
public static byte[] getValueForLLDPPacketIntegrityEnsuring(final NodeConnectorId nodeConnectorId)
        throws NoSuchAlgorithmException {
    String finalKey;
    if (LLDPActivator.getLldpSecureKey() != null && !LLDPActivator.getLldpSecureKey().isEmpty()) {
        finalKey = LLDPActivator.getLldpSecureKey();
    } else {
        finalKey = ManagementFactory.getRuntimeMXBean().getName();
    }
    final String pureValue = nodeConnectorId + finalKey;

    final byte[] pureBytes = pureValue.getBytes();
    HashFunction hashFunction = Hashing.md5();
    Hasher hasher = hashFunction.newHasher();
    HashCode hashedValue = hasher.putBytes(pureBytes).hash();
    return hashedValue.asBytes();
}

From source file:org.openqa.selenium.BuckBuild.java

private void downloadBuckPexIfNecessary(ImmutableList.Builder<String> builder) throws IOException {
    Path projectRoot = InProject.locate("Rakefile").getParentFile().toPath();
    String buckVersion = new String(Files.readAllBytes(projectRoot.resolve(".buckversion"))).trim();

    Path pex = projectRoot.resolve("buck-out/crazy-fun/" + buckVersion + "/buck.pex");

    String expectedHash = new String(Files.readAllBytes(projectRoot.resolve(".buckhash"))).trim();
    HashCode md5 = Files.exists(pex) ? Hashing.md5().hashBytes(Files.readAllBytes(pex))
            : HashCode.fromString("aa"); // So we have a non-null value

    if (!Files.exists(pex) || !expectedHash.equals(md5.toString())) {
        log.warning("Downloading PEX");

        if (!Files.exists(pex.getParent())) {
            Files.createDirectories(pex.getParent());
        }/*from  www.jav a  2 s  .  c  o m*/

        URL url = new URL(String.format(
                "https://github.com/SeleniumHQ/buck/releases/download/buck-release-%s/buck.pex", buckVersion));
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setInstanceFollowRedirects(true);
        Files.copy(connection.getInputStream(), pex, REPLACE_EXISTING);
        // Do our best to make this executable
        pex.toFile().setExecutable(true);
    }

    md5 = Hashing.md5().hashBytes(Files.readAllBytes(pex));
    if (!expectedHash.equals(md5.toString())) {
        throw new WebDriverException("Unable to confirm that download is valid");
    }

    if (Platform.getCurrent().is(WINDOWS)) {
        String python = CommandLine.find("python2");
        if (python == null) {
            python = CommandLine.find("python");
        }
        Preconditions.checkNotNull(python, "Unable to find python executable");
        builder.add(python);
    }

    builder.add(pex.toAbsolutePath().toString());
}

From source file:com.google.gcloud.storage.StorageImpl.java

@Override
public Blob create(BlobInfo blobInfo, byte[] content, BlobTargetOption... options) {
    content = firstNonNull(content, EMPTY_BYTE_ARRAY);
    BlobInfo updatedInfo = blobInfo.toBuilder()
            .md5(BaseEncoding.base64().encode(Hashing.md5().hashBytes(content).asBytes()))
            .crc32c(BaseEncoding.base64().encode(Ints.toByteArray(Hashing.crc32c().hashBytes(content).asInt())))
            .build();//from ww  w  . j ava  2  s  . c o  m
    return create(updatedInfo, new ByteArrayInputStream(content), options);
}

From source file:com.bennavetta.appsite2.sync.Rsync.java

/**
 * Search for a match in a list of blocks.
 * @param blocks the blocks to search in
 * @param checksum the weak rolling checksum to search
 * @param data the data being searched for (in case a hash needs to be generated)
 * @return the index of the matching block, or {@code -1}
 *///ww w . j ava 2 s  .c o m
private static int findMatch(final ObjectArrayList<Block> blocks, final long checksum, final byte[] data) {
    //CHECKSTYLE.OFF: VisibilityModifier - using getters for the anonymous class is kind of pointless
    // use a predicate so we can stop iterating once a match is found
    return blocks.forEach(new ObjectPredicate<Block>() {
        int match = -1;
        int index;
        byte[] dataHash;

        @Override
        public boolean apply(final Block value) {
            if (value.getChecksum() == checksum) {
                // calculate the hash of the input data lazily
                if (dataHash == null) {
                    dataHash = Hashing.md5().hashBytes(data).asBytes();
                }
                if (Arrays.equals(dataHash, value.getHash())) {
                    match = index;
                    return false;
                }
            }
            index++;
            return true;
        }
    }).match;
    //CHECKSTYLE.ON: VisibilityModifier
}

From source file:storage.ConfigSaver.java

/**
 * Calculates a MD5 hash String for a ModuleConfiguration.
 * /*w  ww.j  a  v a  2s . co  m*/
 * @param config
 * @return MD5 hash String
 */
public static String hash(ModuleConfiguration config) {
    try {
        if (config != null) {
            ByteArrayOutputStream byteArray = new ByteArrayOutputStream(1200);
            initMapper().writeValue(byteArray, config);
            HashFunction hashFunction = Hashing.md5();
            HashCode hashCode = hashFunction.newHasher().putBytes(byteArray.toByteArray()).hash();
            return hashCode.toString();
        }
    } catch (IOException e) {
        EXCEPTION_LOGGER.log(Level.SEVERE, "Exception at hash()", e);
    }
    return "";
}

From source file:org.jclouds.digitalocean2.ssh.ECDSAKeys.java

/**
 * Create a fingerprint per the following <a href="http://tools.ietf.org/html/draft-friedl-secsh-fingerprint-00"
 * >spec</a>/*from   www  .  java 2  s  .c o m*/
 * 
 * @return hex fingerprint ex. {@code 2b:a9:62:95:5b:8b:1d:61:e0:92:f7:03:10:e9:db:d9}
 */
public static String fingerprint(ECPublicKey publicKey) {
    byte[] keyBlob = keyBlob(publicKey);
    return hexColonDelimited(Hashing.md5().hashBytes(keyBlob));
}

From source file:brooklyn.entity.container.DockerUtils.java

public static String imageName(Entity entity, String dockerfile) {
    String simpleName = entity.getEntityType().getSimpleName();
    String version = entity.config().get(SoftwareProcess.SUGGESTED_VERSION);

    String label = Joiner.on(":").skipNulls().join(simpleName, version, dockerfile);
    return Identifiers.makeIdFromHash(Hashing.md5().hashString(label, Charsets.UTF_8).asLong())
            .toLowerCase(Locale.ENGLISH);
}