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:de.schildbach.wallet.util.PaymentProtocol.java

public static PaymentIntent parsePaymentRequest(@Nonnull final byte[] serializedPaymentRequest)
        throws PaymentRequestException {
    try {/*from w w  w.j a v  a 2  s . co m*/
        if (serializedPaymentRequest.length > 50000)
            throw new PaymentRequestException("payment request too big: " + serializedPaymentRequest.length);

        final Protos.PaymentRequest paymentRequest = Protos.PaymentRequest.parseFrom(serializedPaymentRequest);

        final String pkiName;
        final String pkiOrgName;
        final String pkiCaName;
        if (!"none".equals(paymentRequest.getPkiType())) {
            // implicitly verify PKI signature
            final PkiVerificationData verificationData = new PaymentSession(paymentRequest,
                    true).pkiVerificationData;
            pkiName = verificationData.name;
            pkiOrgName = verificationData.orgName;
            pkiCaName = verificationData.rootAuthorityName;
        } else {
            pkiName = null;
            pkiOrgName = null;
            pkiCaName = null;
        }

        if (paymentRequest.getPaymentDetailsVersion() != 1)
            throw new PaymentRequestException.InvalidVersion(
                    "cannot handle payment details version: " + paymentRequest.getPaymentDetailsVersion());

        final Protos.PaymentDetails paymentDetails = Protos.PaymentDetails.newBuilder()
                .mergeFrom(paymentRequest.getSerializedPaymentDetails()).build();

        final long currentTimeSecs = System.currentTimeMillis() / 1000;
        if (paymentDetails.hasExpires() && currentTimeSecs >= paymentDetails.getExpires())
            throw new PaymentRequestException.Expired("payment details expired: current time " + currentTimeSecs
                    + " after expiry time " + paymentDetails.getExpires());

        if (!paymentDetails.getNetwork().equals(Constants.NETWORK_PARAMETERS.getPaymentProtocolId()))
            throw new PaymentRequestException.InvalidNetwork(
                    "cannot handle payment request network: " + paymentDetails.getNetwork());

        final ArrayList<PaymentIntent.Output> outputs = new ArrayList<PaymentIntent.Output>(
                paymentDetails.getOutputsCount());
        for (final Protos.Output output : paymentDetails.getOutputsList())
            outputs.add(parseOutput(output));

        final String memo = paymentDetails.hasMemo() ? paymentDetails.getMemo() : null;
        final String paymentUrl = paymentDetails.hasPaymentUrl() ? paymentDetails.getPaymentUrl() : null;
        final byte[] merchantData = paymentDetails.hasMerchantData()
                ? paymentDetails.getMerchantData().toByteArray()
                : null;

        final byte[] paymentRequestHash = Hashing.sha256().hashBytes(serializedPaymentRequest).asBytes();

        final PaymentIntent paymentIntent = new PaymentIntent(PaymentIntent.Standard.BIP70, pkiName, pkiOrgName,
                pkiCaName, outputs.toArray(new PaymentIntent.Output[0]), memo, paymentUrl, merchantData, null,
                paymentRequestHash);

        if (paymentIntent.hasPaymentUrl() && !paymentIntent.isSupportedPaymentUrl())
            throw new PaymentRequestException.InvalidPaymentURL(
                    "cannot handle payment url: " + paymentIntent.paymentUrl);

        return paymentIntent;
    } catch (final InvalidProtocolBufferException x) {
        throw new PaymentRequestException(x);
    } catch (final UninitializedMessageException x) {
        throw new PaymentRequestException(x);
    }
}

From source file:uk.ac.horizon.artcodes.server.ImageServlet.java

@Override
public void doPut(HttpServletRequest request, HttpServletResponse response) throws IOException {
    try {/*from  w w  w  .j  a  v  a  2s. co m*/
        if (request.getContentLength() > image_size) {
            throw new HTTPException(HttpServletResponse.SC_REQUEST_ENTITY_TOO_LARGE, "Image too large");
        }

        verifyUser(getUser(request));
        final String id = getImageID(request);
        final GcsService gcsService = GcsServiceFactory.createGcsService(RetryParams.getDefaultInstance());
        final GcsFilename filename = new GcsFilename(request.getServerName(), id);

        final GcsFileMetadata metadata = gcsService.getMetadata(filename);
        if (metadata != null) {
            throw new HTTPException(HttpServletResponse.SC_FORBIDDEN, "Cannot modify");
        }

        final BufferedInputStream inputStream = new BufferedInputStream(request.getInputStream());
        final String mimetype = URLConnection.guessContentTypeFromStream(inputStream);
        if (mimetype == null) {
            throw new HTTPException(HttpServletResponse.SC_BAD_REQUEST, "Unrecognised image type");
        }

        final GcsFileOptions.Builder fileOptionsBuilder = new GcsFileOptions.Builder();
        fileOptionsBuilder.mimeType(mimetype);
        final GcsFileOptions fileOptions = fileOptionsBuilder.build();
        final GcsOutputChannel outputChannel = gcsService.createOrReplace(filename, fileOptions);

        final HashingOutputStream outputStream = new HashingOutputStream(Hashing.sha256(),
                Channels.newOutputStream(outputChannel));
        ByteStreams.copy(inputStream, outputStream);

        String hash = outputStream.hash().toString();
        if (!hash.equals(id)) {
            gcsService.delete(filename);
            throw new HTTPException(HttpServletResponse.SC_BAD_REQUEST, "Invalid hash");
        }

        outputStream.close();
        outputChannel.close();
    } catch (HTTPException e) {
        e.writeTo(response);
    }
}

From source file:org.apache.james.blob.objectstorage.ObjectStorageBlobsDAO.java

private CompletableFuture<BlobId> save(InputStream data, BlobId id) {
    String containerName = this.containerName.value();
    HashingInputStream hashingInputStream = new HashingInputStream(Hashing.sha256(), data);
    Payload payload = payloadCodec.write(hashingInputStream);
    Blob blob = blobStore.blobBuilder(id.asString()).payload(payload).build();

    return CompletableFuture.supplyAsync(() -> blobStore.putBlob(containerName, blob), executor)
            .thenApply(any -> blobIdFactory.from(hashingInputStream.hash().toString()));
}

From source file:de.siegmar.securetransfer.service.MessageSenderService.java

public String newRandomId() {
    final UUID uuid = UUID.randomUUID();
    return Hashing.sha256().newHasher().putLong(System.nanoTime()).putLong(uuid.getMostSignificantBits())
            .putLong(uuid.getLeastSignificantBits()).hash().toString();
}

From source file:org.apache.beam.runners.fnexecution.artifact.BeamFileSystemArtifactRetrievalService.java

@Override
public void getArtifact(ArtifactApi.GetArtifactRequest request,
        StreamObserver<ArtifactApi.ArtifactChunk> responseObserver) {
    LOG.debug("GetArtifact {}", request);
    String name = request.getName();
    try {//from w  ww .  j a  v a2  s  .  co  m
        ArtifactApi.ProxyManifest proxyManifest = MANIFEST_CACHE.get(request.getRetrievalToken());
        // look for file at URI specified by proxy manifest location
        ArtifactApi.ProxyManifest.Location location = proxyManifest.getLocationList().stream()
                .filter(loc -> loc.getName().equals(name)).findFirst()
                .orElseThrow(() -> new StatusRuntimeException(Status.NOT_FOUND
                        .withDescription(String.format("Artifact location not found in manifest: %s", name))));

        List<ArtifactMetadata> existingArtifacts = proxyManifest.getManifest().getArtifactList();
        ArtifactMetadata metadata = existingArtifacts.stream().filter(meta -> meta.getName().equals(name))
                .findFirst().orElseThrow(() -> new StatusRuntimeException(Status.NOT_FOUND
                        .withDescription(String.format("Artifact metadata not found in manifest: %s", name))));

        ResourceId artifactResourceId = FileSystems.matchNewResource(location.getUri(),
                false /* is directory */);
        LOG.debug("Artifact {} located in {}", name, artifactResourceId);
        Hasher hasher = Hashing.sha256().newHasher();
        byte[] data = new byte[ARTIFACT_CHUNK_SIZE_BYTES];
        try (InputStream stream = Channels.newInputStream(FileSystems.open(artifactResourceId))) {
            int len;
            while ((len = stream.read(data)) != -1) {
                hasher.putBytes(data, 0, len);
                responseObserver.onNext(ArtifactApi.ArtifactChunk.newBuilder()
                        .setData(ByteString.copyFrom(data, 0, len)).build());
            }
        }
        if (metadata.getSha256() != null && !metadata.getSha256().isEmpty()) {
            String expected = metadata.getSha256();
            String actual = hasher.hash().toString();
            if (!actual.equals(expected)) {
                throw new StatusRuntimeException(Status.DATA_LOSS.withDescription(String.format(
                        "Artifact %s is corrupt: expected sha256 %s, actual %s", name, expected, actual)));
            }
        }
        responseObserver.onCompleted();
    } catch (IOException | ExecutionException e) {
        LOG.info("GetArtifact {} failed", request, e);
        responseObserver.onError(e);
    }
}

From source file:cc.mintcoin.wallet.service.DownloadCompleteReceiver.java

private static boolean isObbValid(final WalletApplication app, String obbFile) {
    File file = null;/*from  w  ww  . ja va  2s  .c o m*/
    String hash = null;
    if (OBB_MAIN_FILE.equals(obbFile)) {
        file = getObbPath(app, OBB_MAIN_FILENAME);
        hash = app.getConfiguration().getObbMainHash();
    } else if (OBB_PATCH_FILE.equals(obbFile)) {
        file = getObbPath(app, OBB_PATCH_FILENAME);
        hash = app.getConfiguration().getObbPatchHash();
    } else
        return false;

    try {
        HashCode fileHash = Files.hash(file, Hashing.sha256());

        log.info("isObbValid(): obbfile=" + obbFile + " file=" + file + " hash=" + hash + " calculatedHash="
                + fileHash.toString());

        if (fileHash.toString().toLowerCase().equals(hash.toLowerCase()))
            return true;
    } catch (IOException e) {
    }

    file.delete();
    return false;
}

From source file:de.siegmar.securetransfer.component.Cryptor.java

public byte[] keyFromSaltedPasswordAndSecret(final String password, final byte[] linkSecret) {
    return Hashing.sha256().newHasher().putBytes(salt).putBytes(linkSecret)
            .putString(password, StandardCharsets.UTF_8).hash().asBytes();
}

From source file:org.apache.servicecomb.codec.protobuf.internal.converter.SwaggerToProtoGenerator.java

private String tryFindEnumType(List<String> enums) {
    if (enums != null && !enums.isEmpty()) {
        String strEnums = enums.toString();
        String enumName = "Enum_" + Hashing.sha256().hashString(strEnums, StandardCharsets.UTF_8).toString();
        pending.add(() -> createEnum(enumName, enums));
        return enumName;
    }/*from  w w w.  ja  va 2s  . c  o  m*/
    return null;
}

From source file:org.onosproject.store.primitives.impl.FederatedDistributedPrimitiveCreator.java

/**
 * Returns the {@code DistributedPrimitiveCreator} to use for hosting a primitive.
 * @param name primitive name/*from  w w  w  .j  a  v  a  2 s  .c o  m*/
 * @return primitive creator
 */
private DistributedPrimitiveCreator getCreator(String name) {
    int hashCode = Hashing.sha256().hashString(name, Charsets.UTF_8).asInt();
    return members.get(sortedMemberPartitionIds.get(Math.abs(hashCode) % members.size()));
}

From source file:org.codice.ddf.security.handler.saml.SAMLAssertionHandler.java

@Override
public HandlerResult getNormalizedToken(ServletRequest request, ServletResponse response, FilterChain chain,
        boolean resolve) {
    HandlerResult handlerResult = new HandlerResult();

    SecurityToken securityToken;/*from   w w w.j  ava2 s  .co m*/
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    String authHeader = ((HttpServletRequest) request).getHeader(SecurityConstants.SAML_HEADER_NAME);

    // check for full SAML assertions coming in (federated requests, etc.)
    if (authHeader != null) {
        String[] tokenizedAuthHeader = authHeader.split(" ");
        if (tokenizedAuthHeader.length == 2 && tokenizedAuthHeader[0].equals("SAML")) {
            String encodedSamlAssertion = tokenizedAuthHeader[1];
            LOGGER.trace("Header retrieved");
            try {
                String tokenString = RestSecurity.inflateBase64(encodedSamlAssertion);
                LOGGER.trace("Header value: {}", tokenString);
                securityToken = SAMLUtils.getInstance().getSecurityTokenFromSAMLAssertion(tokenString);
                SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken);
                handlerResult.setToken(samlToken);
                handlerResult.setStatus(HandlerResult.Status.COMPLETED);
            } catch (IOException e) {
                LOGGER.info("Unexpected error converting header value to string", e);
            }
            return handlerResult;
        }
    }

    // Check for legacy SAML cookie
    Map<String, Cookie> cookies = HttpUtils.getCookieMap(httpRequest);
    Cookie samlCookie = cookies.get(SecurityConstants.SAML_COOKIE_NAME);
    if (samlCookie != null) {
        String cookieValue = samlCookie.getValue();
        LOGGER.trace("Cookie retrieved");
        try {
            String tokenString = RestSecurity.inflateBase64(cookieValue);
            LOGGER.trace("Cookie value: {}", tokenString);
            securityToken = new SecurityToken();
            Element thisToken = StaxUtils.read(new StringReader(tokenString)).getDocumentElement();
            securityToken.setToken(thisToken);
            SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, securityToken);
            handlerResult.setToken(samlToken);
            handlerResult.setStatus(HandlerResult.Status.COMPLETED);
        } catch (IOException e) {
            LOGGER.info("Unexpected error converting cookie value to string - proceeding without SAML token.",
                    e);
        } catch (XMLStreamException e) {
            LOGGER.info("Unexpected error converting XML string to element - proceeding without SAML token.",
                    e);
        }
        return handlerResult;
    }

    HttpSession session = httpRequest.getSession(false);
    if (httpRequest.getRequestedSessionId() != null && !httpRequest.isRequestedSessionIdValid()) {
        SecurityLogger.audit(
                "Incoming HTTP Request contained possible unknown session ID [{}] for this server.",
                Hashing.sha256().hashString(httpRequest.getRequestedSessionId(), StandardCharsets.UTF_8)
                        .toString());
    }
    if (session == null && httpRequest.getRequestedSessionId() != null) {
        session = sessionFactory.getOrCreateSession(httpRequest);
    }
    if (session != null) {
        // Check if there is a SAML Assertion in the session
        // If so, create a SAMLAuthenticationToken using the sessionId
        SecurityTokenHolder savedToken = (SecurityTokenHolder) session
                .getAttribute(SecurityConstants.SAML_ASSERTION);
        if (savedToken != null && savedToken.getSecurityToken() != null) {
            SecurityAssertionImpl assertion = new SecurityAssertionImpl(savedToken.getSecurityToken());
            if (assertion.isPresentlyValid()) {
                LOGGER.trace("Creating SAML authentication token with session.");
                SAMLAuthenticationToken samlToken = new SAMLAuthenticationToken(null, session.getId());
                handlerResult.setToken(samlToken);
                handlerResult.setStatus(HandlerResult.Status.COMPLETED);
                return handlerResult;
            } else {
                LOGGER.trace(
                        "SAML token in session has expired - removing from session and returning with no results");
                savedToken.remove();
            }
        } else {
            LOGGER.trace("No SAML token located in session - returning with no results");
        }
    } else {
        LOGGER.trace("No HTTP Session - returning with no results");
    }

    return handlerResult;
}