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:com.imaginarycode.minecraft.bungeejson.impl.auth.ApiKeyAuthenticationProvider.java

@Override
public void onEnable() {
    if (BungeeJSONPlugin.getPlugin().getConfig().get("api-keys") == null
            || !(BungeeJSONPlugin.getPlugin().getConfig().get("api-keys") instanceof List)) {
        BungeeJSONPlugin.getPlugin().getLogger()
                .info("You don't seem to have any API keys, so I'm adding one for your convenience.");
        byte[] bytes = new byte[16];
        new Random().nextBytes(bytes);
        String firstKey = Hashing.sha1().hashBytes(bytes).toString();
        BungeeJSONPlugin.getPlugin().getConfig().set("api-keys", Collections.singletonList(firstKey));
        BungeeJSONPlugin.getPlugin().saveConfig();
        BungeeJSONPlugin.getPlugin().getLogger().info("Your new API key is " + firstKey + ".");
    }//  w  w  w  . ja v  a2 s . c  o  m
}

From source file:org.glowroot.agent.central.SharedQueryTextLimiter.java

Aggregate.SharedQueryText buildAggregateSharedQueryText(String fullText, List<String> fullTextSha1s) {
    if (fullText.length() > Constants.AGGREGATE_QUERY_TEXT_TRUNCATE) {
        String fullTextSha1 = Hashing.sha1().hashString(fullText, UTF_8).toString();
        if (sentInThePastDay.getIfPresent(fullTextSha1) == null) {
            // need to send full text
            fullTextSha1s.add(fullTextSha1);
            return Aggregate.SharedQueryText.newBuilder().setFullText(fullText).build();
        } else {/*from ww w . ja va 2s.  c om*/
            // ok to just send truncated text
            return Aggregate.SharedQueryText.newBuilder()
                    .setTruncatedText(fullText.substring(0, Constants.AGGREGATE_QUERY_TEXT_TRUNCATE))
                    .setFullTextSha1(fullTextSha1).build();
        }
    } else {
        return Aggregate.SharedQueryText.newBuilder().setFullText(fullText).build();
    }
}

From source file:net.yoomai.wechat.utils.StringUtils.java

/**
 * ????/*from   w  w w  .  j a  va 2s  . c  om*/
 *
 * @param params  ?ASCII ????
 * @param encrypt ? SHA1 MD5
 * @return
 */
public static String signature(String buffer, String encrypt, boolean toUpperCase) {
    String sign = "";

    if ("MD5".equals(encrypt)) {
        // MD5
        sign = Hashing.md5().hashString(buffer, Charsets.UTF_8).toString();
    } else if ("SHA1".equals(encrypt)) {
        // SHA1
        sign = Hashing.sha1().hashString(buffer, Charsets.UTF_8).toString();
    }

    if (toUpperCase) {
        sign = sign.toUpperCase();
    }

    return sign;
}

From source file:com.facebook.buck.rules.macros.OutputToFileExpanderUtils.java

/** @return The absolute path to the temp file. */
private static Path createTempFile(ProjectFilesystem filesystem, BuildTarget target,
        MacroMatchResult matchResult) throws IOException {
    Path directory = BuildTargets.getScratchPath(filesystem, target, "%s/tmp");
    filesystem.mkdirs(directory);//from w  ww  .  ja v  a 2 s  .  c  o  m

    // "prefix" should give a stable name, so that the same delegate with the same input can output
    // the same file. We won't optimise for this case, since it's actually unlikely to happen within
    // a single run, but using a random name would cause 'buck-out' to expand in an uncontrolled
    // manner.
    String prefix = Hashing.sha1().newHasher().putString(matchResult.getMacroType(), UTF_8)
            .putString(Joiner.on('\0').join(matchResult.getMacroInput()), UTF_8).hash().toString();

    return filesystem.createTempFile(directory, prefix, ".macro");
}

From source file:com.facebook.buck.rules.Sha1HashCode.java

public static Sha1HashCode newRandomHashCode() {
    HashCode randomHashCode = Hashing.sha1().newHasher().putString(UUID.randomUUID().toString(), Charsets.UTF_8)
            .hash();/*from   w w w  . ja  va  2s. c om*/
    return new Sha1HashCode(randomHashCode.toString());
}

From source file:com.vertixtech.antiquity.graph.ElementUtils.java

/**
 * <p>// ww w. j  a  v a  2s  .  c o m
 * Calculate the private hash of an {@link Element}.
 * </p>
 * 
 * <p>
 * The private hash contains only the properties of the {@link Element}, without its associated elements.
 * </p>
 * 
 * <p>
 * The hash is calculated based on SHA1 algorithm
 * </p>
 * 
 * TODO Handle arrays values properly.
 * 
 * @param element
 *            The element to calculate the private hash for.
 * @param excludedKeys
 *            the keys to exclude when hash is calculated.
 * @return A string representation of the hash
 * @see HashCode#toString()
 */
public static String calculateElementPrivateHash(Element element, Set<String> excludedKeys) {
    Map<String, Object> props = ElementUtils.getPropertiesAsMap(element, excludedKeys);
    Joiner.MapJoiner propsJoiner = Joiner.on('&').withKeyValueSeparator("=");

    HashFunction hf = Hashing.sha1();
    Hasher h = hf.newHasher();

    h.putString("[" + element.getId().toString() + "]");
    h.putString(propsJoiner.join(props));

    return h.hash().toString();
}

From source file:com.facebook.buck.apple.toolchain.impl.ProvisioningProfileMetadataFactory.java

public static ProvisioningProfileMetadata fromProvisioningProfilePath(ProcessExecutor executor,
        ImmutableList<String> readCommand, Path profilePath) throws IOException, InterruptedException {
    Set<Option> options = EnumSet.of(Option.EXPECTING_STD_OUT);

    // Extract the XML from its signed message wrapper.
    ProcessExecutorParams processExecutorParams = ProcessExecutorParams.builder().addAllCommand(readCommand)
            .addCommand(profilePath.toString()).build();
    ProcessExecutor.Result result;
    result = executor.launchAndExecute(processExecutorParams, options, /* stdin */ Optional.empty(),
            /* timeOutMs */ Optional.empty(), /* timeOutHandler */ Optional.empty());
    if (result.getExitCode() != 0) {
        throw new IOException(result.getMessageForResult("Invalid provisioning profile: " + profilePath));
    }/*from ww w.java 2 s .  c om*/

    try {
        NSDictionary plist = (NSDictionary) PropertyListParser.parse(result.getStdout().get().getBytes());
        Date expirationDate = ((NSDate) plist.get("ExpirationDate")).getDate();
        String uuid = ((NSString) plist.get("UUID")).getContent();

        ImmutableSet.Builder<HashCode> certificateFingerprints = ImmutableSet.builder();
        NSArray certificates = (NSArray) plist.get("DeveloperCertificates");
        HashFunction hasher = Hashing.sha1();
        if (certificates != null) {
            for (NSObject item : certificates.getArray()) {
                certificateFingerprints.add(hasher.hashBytes(((NSData) item).bytes()));
            }
        }

        ImmutableMap.Builder<String, NSObject> builder = ImmutableMap.builder();
        NSDictionary entitlements = ((NSDictionary) plist.get("Entitlements"));
        for (String key : entitlements.keySet()) {
            builder = builder.put(key, entitlements.objectForKey(key));
        }
        String appID = entitlements.get("application-identifier").toString();

        ProvisioningProfileMetadata.Builder provisioningProfileMetadata = ProvisioningProfileMetadata.builder();
        if (plist.get("Platform") != null) {
            for (Object platform : (Object[]) plist.get("Platform").toJavaObject()) {
                provisioningProfileMetadata.addPlatforms((String) platform);
            }
        }
        return provisioningProfileMetadata.setAppID(ProvisioningProfileMetadata.splitAppID(appID))
                .setExpirationDate(expirationDate).setUUID(uuid).setProfilePath(profilePath)
                .setEntitlements(builder.build())
                .setDeveloperCertificateFingerprints(certificateFingerprints.build()).build();
    } catch (Exception e) {
        throw new IllegalArgumentException("Malformed embedded plist: " + e);
    }
}

From source file:org.spongepowered.common.resourcepack.SpongeResourcePackFactory.java

@Override
public ResourcePack fromUri(URI uri) throws FileNotFoundException {
    checkNotNull(uri, "uri");
    try {/*www.ja v a2  s.  c o m*/
        Hasher hasher = Hashing.sha1().newHasher();
        InputStream in = openStream(uri);
        byte[] buf = new byte[256];
        while (true) {
            int read = in.read(buf);
            if (read <= 0) {
                break;
            }
            hasher.putBytes(buf, 0, read);
        }
        in.close();
        return SpongeResourcePack.create(uri, hasher.hash().toString());
    } catch (IOException e) {
        FileNotFoundException ex = new FileNotFoundException(e.toString());
        ex.initCause(e);
        throw ex;
    }
}

From source file:net.sourceforge.fenixedu.presentationTier.Action.NameRequest.java

public ActionForward resolve(ActionMapping mapping, ActionForm actionForm, HttpServletRequest request,
        final HttpServletResponse httpServletResponse) throws Exception {

    String digest = Hashing.sha1().hashString(storedPassword, Charsets.UTF_8).toString();
    String providedUsername = request.getParameter("username");
    String providedDigest = request.getParameter("password");

    if (storedUsername.equals(providedUsername) && digest.equals(providedDigest)) {
        String id = request.getParameter("id");
        User user = User.findByUsername(id);

        String name = user.getPerson().getName();
        String nickName = user.getPerson().getNickname();
        httpServletResponse.setHeader("Content-Type", "application/json; charset=" + CharEncoding.UTF_8);
        String message = "{\n" + "\"name\" : \"" + name + "\",\n" + "\"nickName\" : \"" + nickName + "\"\n"
                + "}";
        httpServletResponse.getOutputStream().write(message.getBytes(CharEncoding.UTF_8));
        httpServletResponse.getOutputStream().close();
        return null;

    } else {/*from   w w w  . j av a 2 s . c  o m*/
        throw new DocumentException("invalid.authentication");
    }

}

From source file:org.metaservice.core.vcs.git.GitProvider.java

@Override
public void process(URI uri, RepositoryConnection repositoryConnection) throws VcsException {

    try {//from ww  w  .j av  a 2  s. co  m
        ValueFactory valueFactory = repositoryConnection.getValueFactory();
        String urihash = Hashing.sha1().hashString(uri.toString(), Charset.forName("UTF-8")).toString();
        File wd = new File("/opt/metaservice_data/vcs/git/" + urihash);
        if (!wd.exists()) {
            Files.createDirectories(wd.toPath());
        }
        GitUtil gitUtil = new GitUtil(wd);
        if (!gitUtil.isInitialized()) {
            gitUtil.clone(uri.toString());
        }
        gitUtil.fetch();
        LOGGER.info("Will process " + gitUtil.getHashes().length);
        for (String hash : gitUtil.getHashes()) {
            LOGGER.info("processing " + hash);
            URI revisionURI = valueFactory.createURI(uri + "#revision/" + hash);
            repositoryConnection.add(revisionURI, RDF.TYPE, VCS.REVISION);
            repositoryConnection.add(uri, VCS.CONTAINS_REVISION, revisionURI);
            repositoryConnection.add(revisionURI, VCS.PART_OF_REPOSITORY, uri);
            gitUtil.checkOut(hash);
            for (File file : FileUtils.listFiles(wd, null, true)) {
                if (file.toString().contains(".git/"))
                    continue;
                Path relativePath = wd.toPath().relativize(file.toPath());

                LOGGER.debug("processing " + hash + "/" + relativePath);

                String fileHash = com.google.common.io.Files.hash(file, Hashing.sha1()).toString();
                LOGGER.debug("fileHash " + fileHash);

                long size = file.length();
                Path p = FileUriUtils.getFile(fileHash, size);
                FileIdentifier fileIdentifier = new FileIdentifier(fileHash, size);

                if (!p.toFile().exists()) {
                    FileUriUtils.storeFile(file.toURI());
                    FileRetrievalProcessor.addFile(repositoryConnection, fileIdentifier);
                }
                URI fileUri = valueFactory.createURI(revisionURI + "/" + relativePath);
                repositoryConnection.add(fileUri, RDF.TYPE, VCS.VCS_FILE);
                repositoryConnection.add(fileUri, VCS.REPOSITORY_PATH,
                        valueFactory.createLiteral(relativePath.toString()));
                repositoryConnection.add(fileUri, OWL.SAMEAS, fileIdentifier.getUri());
                repositoryConnection.add(fileUri, VCS.REFERENCES_REVISION, revisionURI);
                repositoryConnection.add(fileUri, VCS.PART_OF_REPOSITORY, uri);
                repositoryConnection.add(revisionURI, VCS.CONTAINS_FILE, fileUri);
            }
            String[] parents = gitUtil.getParentHashes(hash);
            for (String parentHash : parents) {
                URI parentUri = valueFactory.createURI(uri + "#revision/" + parentHash);
                LOGGER.info(parentUri.toString());
                repositoryConnection.add(revisionURI, VCS.SUCCESSOR_OF, parentUri);
                repositoryConnection.add(parentUri, VCS.PREDECESSOR_OF, revisionURI);
            }
            if (parents.length > 1) {
                repositoryConnection.add(revisionURI, RDF.TYPE, VCS.MERGE_REVISION);
            }
        }
        LOGGER.debug("loop end");

        //todo processTags
        //todo processNextFile
        //todo process Branches
    } catch (GitUtil.GitException | RepositoryException | FileProcessingException | IOException e) {
        throw new VcsException(e);
    }
}