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.facebook.buck.util.hashing.FilePathHashLoader.java

@Override
public HashCode get(Path root) throws IOException {
    // In case the root path is a directory, collect all files contained in it and sort them before
    // hashing to avoid non-deterministic directory traversal order from influencing the hash.
    ImmutableSortedSet.Builder<Path> files = ImmutableSortedSet.naturalOrder();
    Files.walkFileTree(defaultCellRoot.resolve(root), ImmutableSet.of(FileVisitOption.FOLLOW_LINKS),
            Integer.MAX_VALUE, new SimpleFileVisitor<Path>() {
                @Override/* w ww.ja v a  2  s . com*/
                public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) {
                    files.add(file);
                    return FileVisitResult.CONTINUE;
                }
            });
    Hasher hasher = Hashing.sha1().newHasher();
    for (Path file : files.build()) {
        file = resolvePath(file);
        boolean assumeModified = assumeModifiedFiles.contains(file);
        Path relativePath = MorePaths.relativize(defaultCellRoot, file);

        // For each file add its path to the hasher suffixed by whether we assume the file to be
        // modified or not. This way files with different paths always result in different hashes and
        // files that are assumed to be modified get different hashes than all unmodified files.
        StringHashing.hashStringAndLength(hasher, relativePath.toString());
        hasher.putBoolean(assumeModified);
    }
    return hasher.hash();
}

From source file:com.dangdang.config.service.zkdao.AuthDao.java

private String sha1Digest(String text) {
    return Hashing.sha1().hashBytes(text.getBytes()).toString();
}

From source file:io.awacs.server.DefaultPlugins.java

@Override
public void init(Configuration configuration) throws InitializationException {
    String[] pluginNames = configuration.getString(Configurations.PLUGIN_PREFIX).trim().split(",");
    for (String pluginName : pluginNames) {
        try {/*from  ww  w  .j av a2  s . c  om*/
            logger.info("Plugin {} configuration found.", pluginName);
            ImmutableMap<String, String> pluginConfig = configuration
                    .getSubProperties(Configurations.PLUGIN_PREFIX + "." + pluginName + ".");

            String handlerClassName = pluginConfig.get(Configurations.HANDLER_CLASS);
            String keyType = pluginConfig.get(Configurations.KEY_CLASS);
            String keyValue = pluginConfig.get(Configurations.KEY_VALUE);

            String pluginClassName = pluginConfig.get(Configurations.PLUGIN_CLASS);
            String pluginPathRoot = Configurations.getPluginPath();
            String relativePath = "/awacs-" + pluginName + "-plugin.jar";
            String pluginPath = pluginPathRoot + relativePath;
            String fileHash = Files.hash(new File(pluginPath), Hashing.sha1()).toString();

            PluginDescriptor descriptor = new PluginDescriptor().setPluginClass(pluginClassName)
                    .setHash(fileHash).setName(pluginName).setKeyClass(keyType).setKeyValue(keyValue)
                    .setDownloadUrl(relativePath);

            Class<?> clazz = Class.forName(handlerClassName);
            PluginHandler handler = (PluginHandler) clazz.newInstance();
            handler.init(new Configuration(pluginConfig));
            if (handler instanceof RepositoriesAware) {
                ((RepositoriesAware) handler).setContext(repositories);
            }
            if (clazz.isAnnotationPresent(EnableInjection.class)) {
                List<Field> waitForInject = Stream.of(clazz.getDeclaredFields()).filter(
                        f -> f.isAnnotationPresent(Resource.class) || f.isAnnotationPresent(Injection.class))
                        .collect(Collectors.toList());
                for (Field f : waitForInject) {
                    f.setAccessible(true);
                    if (f.get(handler) == null) {
                        String name;
                        if (f.isAnnotationPresent(Resource.class)) {
                            Resource r = f.getDeclaredAnnotation(Resource.class);
                            name = r.name();
                        } else {
                            Injection i = f.getDeclaredAnnotation(Injection.class);
                            name = i.name();
                        }
                        Object repo = repositories.lookup(name, f.getType());
                        f.set(handler, repo);
                        logger.debug("Inject repository {} to plugin handler {}", repo, handler);
                    }
                }
            }
            Key<?> k = Key.getKey(keyType, keyValue);
            handlers.put(k, handler);
            descriptors.put(k, descriptor);
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IOException
                | NoSuchKeyTypeException | RepositoryNotFoundException e) {
            e.printStackTrace();
            throw new InitializationException();
        }
    }
}

From source file:com.zxy.commons.web.security.AbstractCustomerShiroDbRealm.java

/**
 * ?,./*w ww .  j a  va2s .c  om*/
 */
//    @Transactional(readOnly = false, rollbackFor = Exception.class)
@Override
protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) {
    Preconditions.checkArgument(authcToken instanceof UsernamePasswordToken,
            "AuthenticationToken is not UsernamePasswordToken instance.");
    UsernamePasswordToken token = (UsernamePasswordToken) authcToken;
    // ???
    String username = token.getUsername();
    String password = String.valueOf(token.getPassword());
    T sessionObject = sessionCheck(username, password);
    String decodePassword = Hashing.sha1().hashBytes(String.valueOf(token.getPassword()).getBytes()).toString();
    return new SimpleAuthenticationInfo(sessionObject, decodePassword.toCharArray(), getName());

}

From source file:org.obm.push.contacts.ContactCreationIdempotenceService.java

@VisibleForTesting
HashCode hash(MSContact contact) {/*from w  ww.j a v a 2s.c  o  m*/
    return Hashing.sha1().newHasher().putUnencodedChars(Strings.nullToEmpty(contact.getLastName()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getFirstName()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getMiddleName()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getFileAs()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getEmail1Address()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getEmail2Address()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getEmail3Address()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getAssistantName()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getAssistantPhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getAssistnamePhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusiness2PhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusinessAddressCity()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusinessPhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getWebPage()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusinessAddressCountry()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getDepartment()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusinessFaxNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getMiddleName()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHomeAddressCity()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHomeAddressCountry()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHomeFaxNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHomePhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHome2PhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHomeAddressPostalCode()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHomeAddressState()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getHomeAddressStreet()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getMobilePhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getSuffix()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getCompanyName()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getOtherAddressCity()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getOtherAddressCountry()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getCarPhoneNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getOtherAddressPostalCode()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getOtherAddressState()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getOtherAddressStreet()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getPagerNumber()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getTitle()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusinessPostalCode()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getSpouse()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusinessState()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getBusinessStreet()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getJobTitle()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getOfficeLocation()))
            .putUnencodedChars(Strings.nullToEmpty(contact.getRadioPhoneNumber())).hash();
}

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

/**
 * Subclasses with options should override this method and call {@code super.init(config)}.
 *//*from   w w w. ja  v  a  2  s  . c  o  m*/

@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":
        hashFunction = Hashing.md5();
        break;
    case "sha1":
        hashFunction = Hashing.sha1();
        break;
    default:
        throw new IllegalArgumentException("Uknown hahser " + hasherOpt);
    }

    modulus = Integer.parseInt(modulusOpt);
}

From source file:com.facebook.buck.android.PackageStringAssets.java

@Override
public List<Step> getBuildSteps(BuildContext context, BuildableContext buildableContext) {
    if (filteredResourcesProvider.getResDirectories().isEmpty()) {
        // There is no zip file, but we still need to provide a consistent hash to
        // ComputeExopackageDepsAbi in this case.
        buildableContext.addMetadata(STRING_ASSETS_ZIP_HASH, Hashing.sha1().hashInt(0).toString());
        return ImmutableList.of();
    }/*from   w w w.  ja  v  a 2  s  .c o m*/

    ImmutableList.Builder<Step> steps = ImmutableList.builder();
    // We need to generate a zip file with the following dir structure:
    // /assets/strings/*.fbstr
    Path pathToBaseDir = getPathToStringAssetsDir();
    Path pathToDirContainingAssetsDir = pathToBaseDir.resolve("string_assets");
    steps.add(new MakeCleanDirectoryStep(pathToDirContainingAssetsDir));
    Path pathToStrings = pathToDirContainingAssetsDir.resolve("assets").resolve("strings");
    Path pathToStringAssetsZip = getPathToStringAssetsZip();
    steps.add(new MakeCleanDirectoryStep(pathToStrings));
    steps.add(new CompileStringsStep(filteredResourcesProvider.getNonEnglishStringFiles(),
            uberRDotJava.getPathToGeneratedRDotJavaSrcFiles(), pathToStrings));
    steps.add(new ZipStep(pathToStringAssetsZip, ImmutableSet.<Path>of(), false, ZipStep.MAX_COMPRESSION_LEVEL,
            pathToDirContainingAssetsDir));
    steps.add(new RecordFileSha1Step(pathToStringAssetsZip, STRING_ASSETS_ZIP_HASH, buildableContext));
    buildableContext.recordArtifact(pathToStringAssetsZip);
    return steps.build();
}

From source file:com.facebook.buck.android.HashInputJarsToDexStep.java

@Override
public int execute(final ExecutionContext context) {
    ImmutableList.Builder<Path> allInputs = ImmutableList.builder();
    allInputs.addAll(primaryInputsToDex.get());
    if (secondaryOutputToInputs.isPresent()) {
        allInputs.addAll(secondaryOutputToInputs.get().get().values());
    }/*from w  w  w  .j  a  v a 2 s .c  o m*/

    final Map<String, HashCode> classNamesToHashes = classNamesToHashesSupplier.get();

    for (Path path : allInputs.build()) {
        try {
            final Hasher hasher = Hashing.sha1().newHasher();
            new DefaultClasspathTraverser().traverse(
                    new ClasspathTraversal(Collections.singleton(path), context.getProjectFilesystem()) {
                        @Override
                        public void visit(FileLike fileLike) throws IOException {
                            String className = fileLike.getRelativePath().replaceAll("\\.class$", "");
                            if (classNamesToHashes.containsKey(className)) {
                                HashCode classHash = classNamesToHashes.get(className);
                                hasher.putBytes(classHash.asBytes());
                            }
                        }
                    });
            dexInputsToHashes.put(path, new Sha1HashCode(hasher.hash().toString()));
        } catch (IOException e) {
            context.logError(e, "Error hashing smart dex input: %s", path);
            return 1;
        }
    }
    stepFinished = true;
    return 0;
}

From source file:sockslib.server.manager.HashPasswordProtector.java

private Hasher chooseHasher(HashAlgorithm algorithm) {
    Hasher hasher = null;//from  w ww.ja va 2s  .  c o  m
    switch (algorithm) {

    case MD5:
        hasher = Hashing.md5().newHasher();
        break;
    case SHA1:
        hasher = Hashing.sha1().newHasher();
        break;
    case SHA256:
        hasher = Hashing.sha256().newHasher();
        break;
    case SHA512:
        hasher = Hashing.sha512().newHasher();
        break;

    }
    return hasher;
}

From source file:es.udc.pfc.xmpp.handler.XEP0114Decoder.java

@Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception {
    if (e.getMessage() instanceof XMLEvent) {
        final XMLEvent event = (XMLEvent) e.getMessage();

        switch (status) {
        case CONNECT:
            if (event.isStartElement()) {
                final StartElement element = event.asStartElement();

                if (STREAM_NAME.equals(element.getName())
                        && XMPPNamespaces.ACCEPT.equals(element.getNamespaceURI(null))) {
                    if (!serverName.equals(element.getAttributeByName(new QName("from")).getValue())) {
                        throw new Exception("server name mismatch");
                    }//w w  w . j  a  v  a2s . com
                    streamID = element.getAttributeByName(new QName("id")).getValue();

                    status = Status.AUTHENTICATE;
                    Channels.write(ctx.getChannel(),
                            ChannelBuffers.copiedBuffer("<handshake>"
                                    + Hashing.sha1().hashString(streamID + secret, CharsetUtil.UTF_8).toString()
                                    + "</handshake>", CharsetUtil.UTF_8));
                }
            } else {
                throw new Exception("Expected stream:stream element");
            }
            break;
        case AUTHENTICATE:
        case READY:
            if (event.isEndElement()) {
                final EndElement element = event.asEndElement();

                if (STREAM_NAME.equals(element.getName())) {
                    Channels.disconnect(ctx.getChannel());
                    return;
                }
            }
            break;
        case DISCONNECTED:
            throw new Exception("received DISCONNECTED");
        }
    } else if (e.getMessage() instanceof XMLElement) {
        final XMLElement element = (XMLElement) e.getMessage();

        switch (status) {
        case AUTHENTICATE:
            if (!"handshake".equals(element.getTagName()))
                throw new Exception("expected handshake");
            status = Status.READY;
            System.out.println("logged in");

            ctx.getPipeline().get(XMPPStreamHandler.class).loggedIn();

            break;
        case READY:
            final Stanza stanza = Stanza.fromElement(element);
            if (stanza == null)
                throw new Exception("Unknown stanza");

            Channels.fireMessageReceived(ctx, stanza);
            break;
        default:
            throw new Exception("unexpected handleElement");
        }
    } else {
        ctx.sendUpstream(e);
    }
}