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

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

Introduction

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

Prototype

public static HashFunction sha1() 

Source Link

Document

Returns a hash function implementing the SHA-1 algorithm (160 hash bits) by delegating to the SHA-1 MessageDigest .

Usage

From source file:jinex.Parser.java

JarMetadata parseJar(final File jarFile) throws IOException, NoSuchAlgorithmException {
    List<ClassMetadata> list = new ArrayList<ClassMetadata>();

    final JarFile jfile = new JarFile(jarFile);

    try {/*  w w  w  .j  a  v a 2  s.  c  o  m*/
        Enumeration<JarEntry> entries = jfile.entries();

        while (entries.hasMoreElements()) {
            final JarEntry entry = entries.nextElement();
            if (entry.isDirectory())
                continue;

            if (entry.getName().endsWith(".class")) {

                try {
                    JavaClass jclass = new ClassParser(jfile.getInputStream(entry), entry.getName()).parse();
                    DependencyEmitter visitor = new DependencyEmitter(jclass);
                    DescendingVisitor classWalker = new DescendingVisitor(jclass, visitor);
                    classWalker.visit();

                    HashCode hash = ByteStreams.hash(new InputSupplier<InputStream>() {
                        public InputStream getInput() throws IOException {
                            return jfile.getInputStream(entry);
                        }
                    }, Hashing.sha1());

                    visitor.deps.remove(jclass.getClassName());

                    ClassMetadata classInfo = new ClassMetadata(hash.toString(), jclass.getClassName(),
                            visitor.deps);
                    list.add(classInfo);
                } catch (Exception e) {
                    log.error("Skipping class " + entry.getName() + " due to exeception", e);
                }
            }
        }
    } finally {
        jfile.close();
    }

    HashCode jarHash = ByteStreams.hash(new InputSupplier<InputStream>() {
        public InputStream getInput() throws IOException {
            return new FileInputStream(jarFile);
        }
    }, Hashing.sha1());

    return new JarMetadata(jarFile.getName(), jarHash.toString(), list);
}

From source file:org.apache.accumulo.core.client.sample.AbstractHashSampler.java

/**
 * Subclasses with options should override this method and call {@code super.init(config)}.
 *///  w  w w  .j  a va2 s .c o  m
@SuppressFBWarnings(value = "UNSAFE_HASH_EQUALS", justification = "these hashes don't protect any secrets, just used for binning")
@Override
public void init(SamplerConfiguration config) {
    String hasherOpt = config.getOptions().get("hasher");
    String modulusOpt = config.getOptions().get("modulus");

    requireNonNull(hasherOpt, "Hasher not specified");
    requireNonNull(modulusOpt, "Modulus not specified");

    for (String option : config.getOptions().keySet()) {
        checkArgument(isValidOption(option), "Unknown option : %s", option);
    }

    switch (hasherOpt) {
    case "murmur3_32":
        hashFunction = Hashing.murmur3_32();
        break;
    case "md5":
        @SuppressWarnings("deprecation")
        HashFunction deprecatedMd5 = Hashing.md5();
        hashFunction = deprecatedMd5;
        break;
    case "sha1":
        @SuppressWarnings("deprecation")
        HashFunction deprecatedSha1 = Hashing.sha1();
        hashFunction = deprecatedSha1;
        break;
    default:
        throw new IllegalArgumentException("Unknown hahser " + hasherOpt);
    }

    modulus = Integer.parseInt(modulusOpt);
}

From source file:com.torchmind.stockpile.server.controller.v1.BlacklistController.java

/**
 * Checks an IP address against the blacklist.
 *
 * @param address an address.//from   ww  w  . j av a  2 s  . c om
 * @return a blacklist result.
 */
@Nonnull
private BlacklistResult checkAddress(@Nonnull String address) {
    List<String> addressParts = Splitter.on('.').splitToList(address);

    for (int i = (addressParts.size() - 1); i >= 1; --i) {
        String currentAddress = Joiner.on('.').join(addressParts.subList(0, i)) + ".*";
        String hash = Hashing.sha1().hashString(currentAddress, StandardCharsets.ISO_8859_1).toString();

        if (this.hashes.contains(hash)) {
            return new BlacklistResult(currentAddress, true);
        }
    }

    return new BlacklistResult(address, false);
}

From source file:org.macgyver.mercator.ucs.UCSScanner.java

protected void recordChassis(Element element) {

    ObjectNode n = toJson(element);/*from   w w  w.ja  va 2s .  c o  m*/

    String serial = n.get("serial").asText();
    String mercatorId = Hashing.sha1().hashString(serial, Charsets.UTF_8).toString();
    n.put("mercatorId", mercatorId);
    String cypher = "merge (c:UCSChassis {mercatorId:{mercatorId}}) set c+={props}, c.updateTs=timestamp()";

    getProjector().getNeoRxClient().execCypher(cypher, "mercatorId", mercatorId, "props", n);

    cypher = "match (m:UCSManager {mercatorId:{managerId}}), (c:UCSChassis {mercatorId:{chassisId}}) merge (m)-[r:MANAGES]->(c)";

    getProjector().getNeoRxClient().execCypher(cypher, "managerId", getUCSClient().getUCSManagerId(),
            "chassisId", mercatorId);

    getUCSClient().resolveChildren(n.get("dn").asText(), "computeBlade").forEach(it -> {
        recordComputeBlade(mercatorId, it);

    });

}

From source file:org.lanternpowered.server.resourcepack.LanternResourcePackFactory.java

private ResourcePack fromUri(URI uri, boolean unchecked) throws IOException {
    final CacheKey key = new CacheKey(uri, unchecked);
    if (this.resourcePacksByKey.containsKey(key)) {
        return this.resourcePacksByKey.get(key);
    }//from  w  w w. j a v  a 2  s.  c  o  m
    final String path = uri.toString();
    final String plainPath = path.replaceAll("[^\\p{L}\\p{Nd}]+", "");
    String hash = null;
    String id = "{URI:" + path;
    if (!unchecked) {
        if (path.startsWith("level://")) {
            final String path0 = path.replaceFirst("level://", "");
            final Path file = this.levelPacksFolder.resolve(path0);
            if (!Files.exists(file)) {
                throw new FileNotFoundException("Cannot find the file: \"" + file.toAbsolutePath() + "\" which"
                        + " is required to generate the hash for \"" + path + "\"");
            }
            uri = file.toUri();
        }
        try (InputStream is = uri.toURL().openStream()) {
            hash = Hashing.sha1().hashBytes(ByteStreams.toByteArray(is)).toString();
        }
        id += ";Hash:" + hash;
    }
    id += "}";
    final ResourcePack resourcePack = new LanternResourcePack(uri, plainPath, id, hash);
    this.resourcePacks.put(id, resourcePack);
    this.resourcePacksByKey.put(key, resourcePack);
    return resourcePack;
}

From source file:de.brendamour.jpasskit.signing.PKInMemorySigningUtil.java

private ByteBuffer createManifestJSONFile(Map<String, ByteBuffer> allFiles) throws PKSigningException {
    Map<String, String> fileWithHashMap = new HashMap<String, String>();

    HashFunction hashFunction = Hashing.sha1();
    hashFiles(allFiles, fileWithHashMap, hashFunction);
    ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
    try {/*from www  . jav a2s. c o m*/
        objectWriter.writeValue(byteArrayOutputStream, fileWithHashMap);
        return ByteBuffer.wrap(byteArrayOutputStream.toByteArray());
    } catch (IOException e) {
        throw new PKSigningException("Error when writing pass.json", e);
    } finally {
        IOUtils.closeQuietly(byteArrayOutputStream);
    }
}

From source file:ch.raffael.doclets.pegdown.integrations.idea.TempFileManager.java

public synchronized URL saveTempFile(byte[] bytes, String extension) throws IOException {
    String name = Hashing.sha1().hashBytes(bytes).toString() + "." + extension;
    File tempFile = new File(baseDir, Hashing.sha1().hashBytes(bytes).toString() + "." + extension);
    synchronized (index) {
        if (!tempFile.isFile()) {
            FileUtil.writeToFile(tempFile, bytes);
        }/*w  ww .j  a  va 2s.  com*/
        index.put(name, System.currentTimeMillis());
        return tempFile.toURI().toURL();
    }
}

From source file:org.cinchapi.concourse.server.io.Composite.java

@Override
public String toString() {
    return Hashing.sha1().hashBytes(ByteBuffers.toByteArray(getBytes())).toString();
}

From source file:org.sonatype.nexus.rapture.internal.state.StateComponent.java

/**
 * Calculate (opaque) hash for given non-null value.
 *//*from   w  w  w.  j av a 2s  . com*/
@Nullable
private static String hash(@Nullable final Object value) {
    if (value != null) {
        // TODO: consider using Object.hashCode() and getting state contributors to ensure values have proper impls?
        // TODO: ... or something else which is more efficient than object->gson->sha1?
        String json = gson.toJson(value);
        log.trace("Hashing state: {}", json);
        return Hashing.sha1().hashString(json, Charsets.UTF_8).toString();
    }
    return null;
}

From source file:org.haiku.haikudepotserver.pkg.CreatedPkgVersionSyndEntrySupplier.java

@Override
public List<SyndEntry> generate(final FeedSpecification specification) {
    Preconditions.checkNotNull(specification);

    if (specification.getSupplierTypes().contains(FeedSpecification.SupplierType.CREATEDPKGVERSION)) {

        if (null != specification.getPkgNames() && specification.getPkgNames().isEmpty()) {
            return Collections.emptyList();
        }/*from   w w w  .j av  a 2s.  co m*/

        ObjectSelect<PkgVersion> objectSelect = ObjectSelect.query(PkgVersion.class)
                .where(PkgVersion.ACTIVE.isTrue()).and(PkgVersion.PKG.dot(Pkg.ACTIVE).isTrue())
                .orderBy(PkgVersion.CREATE_TIMESTAMP.desc()).limit(specification.getLimit());

        if (null != specification.getPkgNames()) {
            objectSelect.and(PkgVersion.PKG.dot(Pkg.NAME).in(specification.getPkgNames()));
        }

        ObjectContext context = serverRuntime.newContext();

        NaturalLanguage naturalLanguage = Strings.isBlank(specification.getNaturalLanguageCode())
                ? NaturalLanguage.getEnglish(context)
                : NaturalLanguage.getByCode(context, specification.getNaturalLanguageCode())
                        .orElseThrow(() -> new IllegalStateException(
                                "unable to find natural language; " + specification.getNaturalLanguageCode()));

        List<PkgVersion> pkgVersions = objectSelect.select(context);

        return pkgVersions.stream().map(pv -> {
            SyndEntry entry = new SyndEntryImpl();

            entry.setPublishedDate(pv.getCreateTimestamp());
            entry.setUpdatedDate(pv.getModifyTimestamp());
            entry.setUri(URI_PREFIX + Hashing.sha1()
                    .hashUnencodedChars(String.format("%s_::_%s_::_%s", this.getClass().getCanonicalName(),
                            pv.getPkg().getName(), pv.toVersionCoordinates().toString()))
                    .toString());

            {
                UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl).pathSegment("#",
                        "pkg");
                pv.appendPathSegments(builder);
                entry.setLink(builder.build().toUriString());
            }

            entry.setTitle(messageSource.getMessage("feed.createdPkgVersion.atom.title",
                    new Object[] { pv.toStringWithPkgAndArchitecture() },
                    new Locale(specification.getNaturalLanguageCode())));

            {
                ResolvedPkgVersionLocalization resolvedPkgVersionLocalization = pkgLocalizationService
                        .resolvePkgVersionLocalization(context, pv, null, naturalLanguage);

                SyndContent content = new SyndContentImpl();
                content.setType(MediaType.PLAIN_TEXT_UTF_8.type());
                content.setValue(resolvedPkgVersionLocalization.getSummary());
                entry.setDescription(content);
            }

            return entry;
        }).collect(Collectors.toList());

    }

    return Collections.emptyList();
}