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

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

Introduction

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

Prototype

public static HashFunction sha256() 

Source Link

Document

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

Usage

From source file:org.apache.james.mailbox.tika.CachingTextExtractor.java

@Override
public ParsedContent extractContent(InputStream inputStream, String contentType) throws Exception {
    byte[] bytes = IOUtils.toByteArray(inputStream);
    String key = Hashing.sha256().hashBytes(bytes).toString();

    try {//ww  w  . j a v  a  2s .com
        return cache.get(key, () -> retrieveAndUpdateWeight(bytes, contentType));
    } catch (ExecutionException | UncheckedExecutionException e) {
        throw unwrap(e);
    }
}

From source file:at.ac.univie.isc.asio.database.MysqlUserRepository.java

/**
 * Derive a unique username and obfuscated password from the given schema name.
 * The username is the base64 encoded SHA-256 hash of the schema name prefixed with {@code '_:'}
 * and truncated to fit the 16 character limit of MySql.
 * The password is the base64 encoded SHA-256 hash of the schema name, salted with the prefix
 * {@code 'asio:'}./*from  www. j ava2  s . c o m*/
 *
 * @param schema name of a mysql database
 * @return derived, unique credentials
 */
private Identity translateToCredentials(final String schema) {
    Preconditions.checkNotNull(schema, "jdbc schema name missing");
    final String hashedSchemaName = BaseEncoding.base64()
            .encode(Hashing.sha256().hashString(schema, Charsets.UTF_8).asBytes());
    final String username = USERNAME_PREFIX + hashedSchemaName.substring(0, 14);
    final String password = BaseEncoding.base64()
            .encode(Hashing.sha256().hashString(PASSWORD_SALT + schema, Charsets.UTF_8).asBytes());
    return Identity.from(username, password);
}

From source file:it.anyplace.sync.bep.BlockPuller.java

public FileDownloadObserver pullBlocks(FileBlocks fileBlocks) throws InterruptedException {
    logger.info("pulling file = {}", fileBlocks);
    checkArgument(connectionHandler.hasFolder(fileBlocks.getFolder()),
            "supplied connection handler %s will not share folder %s", connectionHandler,
            fileBlocks.getFolder());//from ww w  .ja va2 s .c om
    final Object lock = new Object();
    final AtomicReference<Exception> error = new AtomicReference<>();
    final Object listener = new Object() {
        @Subscribe
        public void handleResponseMessageReceivedEvent(ResponseMessageReceivedEvent event) {
            synchronized (lock) {
                try {
                    if (!requestIds.contains(event.getMessage().getId())) {
                        return;
                    }
                    checkArgument(equal(event.getMessage().getCode(), ErrorCode.NO_ERROR),
                            "received error response, code = %s", event.getMessage().getCode());
                    byte[] data = event.getMessage().getData().toByteArray();
                    String hash = BaseEncoding.base16().encode(Hashing.sha256().hashBytes(data).asBytes());
                    blockCache.pushBlock(data);
                    if (missingHashes.remove(hash)) {
                        blocksByHash.put(hash, data);
                        logger.debug("aquired block, hash = {}", hash);
                        lock.notify();
                    } else {
                        logger.warn("received not-needed block, hash = {}", hash);
                    }
                } catch (Exception ex) {
                    error.set(ex);
                    lock.notify();
                }
            }
        }
    };
    FileDownloadObserver fileDownloadObserver = new FileDownloadObserver() {

        private long getReceivedData() {
            return blocksByHash.size() * BLOCK_SIZE;
        }

        private long getTotalData() {
            return (blocksByHash.size() + missingHashes.size()) * BLOCK_SIZE;
        }

        @Override
        public double getProgress() {
            return isCompleted() ? 1d : getReceivedData() / ((double) getTotalData());
        }

        @Override
        public String getProgressMessage() {
            return (Math.round(getProgress() * 1000d) / 10d) + "% "
                    + FileUtils.byteCountToDisplaySize(getReceivedData()) + " / "
                    + FileUtils.byteCountToDisplaySize(getTotalData());
        }

        @Override
        public boolean isCompleted() {
            return missingHashes.isEmpty();
        }

        @Override
        public void checkError() {
            if (error.get() != null) {
                throw new RuntimeException(error.get());
            }
        }

        @Override
        public double waitForProgressUpdate() throws InterruptedException {
            if (!isCompleted()) {
                synchronized (lock) {
                    checkError();
                    lock.wait();
                    checkError();
                }
            }
            return getProgress();
        }

        @Override
        public InputStream getInputStream() {
            checkArgument(missingHashes.isEmpty(), "pull failed, some blocks are still missing");
            List<byte[]> blockList = Lists
                    .newArrayList(Lists.transform(hashList, Functions.forMap(blocksByHash)));
            return new SequenceInputStream(Collections
                    .enumeration(Lists.transform(blockList, new Function<byte[], ByteArrayInputStream>() {
                        @Override
                        public ByteArrayInputStream apply(byte[] data) {
                            return new ByteArrayInputStream(data);
                        }
                    })));
        }

        @Override
        public void close() {
            missingHashes.clear();
            hashList.clear();
            blocksByHash.clear();
            try {
                connectionHandler.getEventBus().unregister(listener);
            } catch (Exception ex) {
            }
            if (closeConnection) {
                connectionHandler.close();
            }
        }
    };
    try {
        synchronized (lock) {
            hashList.addAll(Lists.transform(fileBlocks.getBlocks(), new Function<BlockInfo, String>() {
                @Override
                public String apply(BlockInfo block) {
                    return block.getHash();
                }
            }));
            missingHashes.addAll(hashList);
            for (String hash : missingHashes) {
                byte[] block = blockCache.pullBlock(hash);
                if (block != null) {
                    blocksByHash.put(hash, block);
                    missingHashes.remove(hash);
                }
            }
            connectionHandler.getEventBus().register(listener);
            for (BlockInfo block : fileBlocks.getBlocks()) {
                if (missingHashes.contains(block.getHash())) {
                    int requestId = Math.abs(new Random().nextInt());
                    requestIds.add(requestId);
                    connectionHandler.sendMessage(Request.newBuilder().setId(requestId)
                            .setFolder(fileBlocks.getFolder()).setName(fileBlocks.getPath())
                            .setOffset(block.getOffset()).setSize(block.getSize())
                            .setHash(ByteString.copyFrom(BaseEncoding.base16().decode(block.getHash())))
                            .build());
                    logger.debug("sent request for block, hash = {}", block.getHash());
                }
            }
            return fileDownloadObserver;
        }
    } catch (Exception ex) {
        fileDownloadObserver.close();
        throw ex;
    }
}

From source file:io.takari.jdkget.OracleWebsiteTransport.java

@Override
public boolean validate(Arch arch, JdkVersion jdkVersion, File jdkImage, IOutput output) throws IOException {
    if (isApple(arch, jdkVersion)) {
        return jdkImage.length() == 66724162L;
    } else {/*from  ww  w  .j a v a 2s.c  o  m*/
        JdkBinary bin = binary(arch, jdkVersion);

        int checks = 0;
        int failed = 0;

        if (bin.getSha256() != null) {
            checks++;
            String fileHash = hash(jdkImage, Hashing.sha256());
            if (!bin.getSha256().equals(fileHash)) {
                failed++;
                output.error("File sha256 `" + fileHash + "` differs from `" + bin.getSha256() + "`");
            }
        }
        if (bin.getMd5() != null) {
            checks++;
            String fileHash = hash(jdkImage, Hashing.md5());
            if (!bin.getMd5().equals(fileHash)) {
                failed++;
                output.error("File md5 `" + fileHash + "` differs from `" + bin.getMd5() + "`");
            }
        }
        if (bin.getSize() != -1) {
            checks++;
            if (bin.getSize() != jdkImage.length()) {
                failed++;
                output.error("File size `" + jdkImage.length() + "` differs from `" + bin.getSize() + "`");
            }
        }

        if (checks != 0 && failed > 0) {
            return false;
        }
    }
    return true;
}

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

/**
 * Expand the input given for the this macro to some string, which is intended to be written to a
 * file./*w  ww .  jav  a  2 s  . c  o  m*/
 */
private Arg expand(MacroContainer macroContainer, ActionGraphBuilder ruleResolver) throws MacroException {
    Arg arg = expand(macroContainer.getMacro(), ruleResolver);

    // If specified, wrap this macro's output in a `WriteToFileArg`.
    if (macroContainer.isOutputToFile()) {
        // "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.
        Hasher hasher = Hashing.sha256().newHasher();
        hasher.putString(macroContainer.getMacro().getClass().getName(), UTF_8);
        hasher.putInt(macroContainer.getMacro().hashCode());
        String prefix = hasher.hash().toString();
        arg = new WriteToFileArg(getBuildTarget(), prefix, arg);
    }

    return arg;
}

From source file:com.facebook.buck.features.go.GoTestCoverSource.java

static String getVarName(Path path) {
    return "Var_" + Hashing.sha256().hashString(path.getFileName().toString(), Charsets.UTF_8);
}

From source file:org.jclouds.glacier.util.AWSRequestSignerV4.java

private static HashCode buildHashedPayload(HttpRequest request) {
    HashingInputStream his = null;/*from   w  w  w  .  ja va2  s  . c  o  m*/
    try {
        his = new HashingInputStream(Hashing.sha256(),
                request.getPayload() == null ? ByteSource.empty().openStream()
                        : request.getPayload().openStream());
        ByteStreams.copy(his, ByteStreams.nullOutputStream());
        return his.hash();
    } catch (IOException e) {
        throw new HttpException("Error signing request", e);
    } finally {
        closeQuietly(his);
    }
}

From source file:it.anyplace.sync.core.security.KeystoreHandler.java

public static byte[] deviceIdStringToHashData(String deviceId) {
    checkArgument(deviceId.matches(/*from ww  w.  j a  v a2s.c  o  m*/
            "^[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}-[A-Z0-9]{7}$"),
            "device id syntax error for deviceId = %s", deviceId);
    String base32data = deviceId.replaceFirst("(.{7})-(.{6}).-(.{7})-(.{6}).-(.{7})-(.{6}).-(.{7})-(.{6}).",
            "$1$2$3$4$5$6$7$8") + "===";
    byte[] binaryData = BaseEncoding.base32().decode(base32data);
    checkArgument(binaryData.length == Hashing.sha256().bits() / 8);
    return binaryData;
}

From source file:org.smartdeveloperhub.vocabulary.language.lexvo.LexvoDataSource.java

private Model loadModel(final String version, final Path input) throws IOException {
    final byte[] rawData = readInput(input);
    final String data = stringifyRawData(rawData);
    final Model model = parseRDF(data);
    this.lexvoVersion = version;
    this.lexvoSha256 = Hashing.sha256().hashBytes(rawData).toString();
    this.lexvoSha512 = Hashing.sha512().hashBytes(rawData).toString();
    return model;
}

From source file:org.dhatim.dropwizard.jwt.cookie.authentication.JwtCookieAuthBundle.java

@Override
public void run(C configuration, Environment environment) throws Exception {
    JwtCookieAuthConfiguration conf = configurationSupplier.apply(configuration);

    //build the key from the key factory if it was provided
    Key key = Optional.ofNullable(keySuppplier).map(k -> k.apply(configuration, environment)).orElseGet(() ->
    //else make a key from the seed if it was provided
    Optional.ofNullable(conf.getSecretSeed())
            .map(seed -> Hashing.sha256().newHasher().putString(seed, UTF_8).hash().asBytes())
            .map(k -> (Key) new SecretKeySpec(k, HS256.getJcaName()))
            //else generate a random key
            .orElseGet(getHmacSha256KeyGenerator()::generateKey));

    JerseyEnvironment jerseyEnvironment = environment.jersey();

    jerseyEnvironment.register(new AuthDynamicFeature(new JwtCookieAuthRequestFilter.Builder()
            .setCookieName(DEFAULT_COOKIE_NAME)
            .setAuthenticator(new JwtCookiePrincipalAuthenticator(key, deserializer))
            .setPrefix(JWT_COOKIE_PREFIX).setAuthorizer((Authorizer<P>) (P::isInRole)).buildAuthFilter()));
    jerseyEnvironment.register(new AuthValueFactoryProvider.Binder<>(principalType));
    jerseyEnvironment.register(RolesAllowedDynamicFeature.class);

    jerseyEnvironment.register(new JwtCookieAuthResponseFilter<>(principalType, serializer, DEFAULT_COOKIE_NAME,
            conf.isHttpsOnlyCookie(), key,
            Ints.checkedCast(Duration.parse(conf.getSessionExpiryVolatile()).getSeconds()),
            Ints.checkedCast(Duration.parse(conf.getSessionExpiryPersistent()).getSeconds())));

    jerseyEnvironment.register(DontRefreshSessionFilter.class);
}