List of usage examples for com.google.common.hash HashCode asBytes
@CheckReturnValue public abstract byte[] asBytes();
From source file:com.infinities.keystone4j.utils.Cms.java
public String hashToken(String tokenid, Algorithm mode) throws UnsupportedEncodingException, NoSuchAlgorithmException, DecoderException { if (mode == null) { mode = Algorithm.md5;/*from ww w . j a va 2 s . co m*/ } if (Strings.isNullOrEmpty(tokenid)) { throw new NullPointerException("invalid tokenid"); } if (isAsn1Token(tokenid) || isPkiz(tokenid)) { HashFunction hf = Hashing.md5(); if (mode == Algorithm.sha1) { hf = Hashing.sha1(); } else if (mode == Algorithm.sha256) { hf = Hashing.sha256(); } else if (mode == Algorithm.sha512) { hf = Hashing.sha512(); } HashCode hc = hf.newHasher().putString(tokenid).hash(); return toHex(hc.asBytes()); } else { return tokenid; } }
From source file:org.jclouds.s3.filters.Aws4SignerForAuthorizationHeader.java
protected HttpRequest sign(HttpRequest request) throws HttpException { checkNotNull(request, "request is not ready to sign"); checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present."); Payload payload = request.getPayload(); // get host from request endpoint. String host = request.getEndpoint().getHost(); Date date = timestampProvider.get(); String timestamp = timestampFormat.format(date); String datestamp = dateFormat.format(date); String service = serviceAndRegion.service(); String region = serviceAndRegion.region(host); String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request"); HttpRequest.Builder<?> requestBuilder = request.toBuilder() // .removeHeader(AUTHORIZATION) // remove Authorization .removeHeader(DATE); // remove date ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap .<String, String>naturalOrder(); // Content Type // content-type is not a required signing param. However, examples use this, so we include it to ease testing. String contentType = getContentType(request); if (!Strings.isNullOrEmpty(contentType)) { requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType); signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType); }//from w w w . ja va 2 s . c om // Content-Length for PUT or POST request http method String contentLength = getContentLength(request); if (!Strings.isNullOrEmpty(contentLength)) { requestBuilder.replaceHeader(HttpHeaders.CONTENT_LENGTH, contentLength); signedHeadersBuilder.put(HttpHeaders.CONTENT_LENGTH.toLowerCase(), contentLength); } // Content MD5 String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5); if (payload != null) { HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode(); if (md5 != null) { contentMD5 = BaseEncoding.base64().encode(md5.asBytes()); } } if (contentMD5 != null) { requestBuilder.replaceHeader(CONTENT_MD5, contentMD5); signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5); } // host requestBuilder.replaceHeader(HttpHeaders.HOST, host); signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host); // user-agent if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) { signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(), request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT)); } // all x-amz-* headers appendAmzHeaders(request, signedHeadersBuilder); // x-amz-security-token Credentials credentials = creds.get(); if (credentials instanceof SessionCredentials) { String token = SessionCredentials.class.cast(credentials).getSessionToken(); requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token); signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token); } // x-amz-content-sha256 String contentSha256 = getPayloadHash(request); requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256); signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256); // put x-amz-date requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp); signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp); ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build(); String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders, timestamp, credentialScope, contentSha256); signatureWire.getWireLog().debug("<< " + stringToSign); byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service); String signature = base16().lowerCase().encode(hmacSHA256(stringToSign, signatureKey)); StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(" "); authorization.append("Credential=").append(Joiner.on("/").join(credentials.identity, credentialScope)) .append(", "); authorization.append("SignedHeaders=").append(Joiner.on(";").join(signedHeaders.keySet())).append(", "); authorization.append("Signature=").append(signature); return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()).build(); }
From source file:org.jclouds.googlecloudstorage.blobstore.functions.BlobMetadataToObjectTemplate.java
public ObjectTemplate apply(BlobMetadata from) { if (from == null) return null; String name = from.getName(); Map<String, String> userMeta = from.getUserMetadata(); ContentMetadata metadata = from.getContentMetadata(); String contentDisposition = metadata.getContentDisposition(); String contentEncoding = metadata.getContentEncoding(); String contentLanguage = metadata.getContentLanguage(); String contentType = metadata.getContentType(); Long contentLength = metadata.getContentLength(); HashCode md5 = metadata.getContentMD5AsHashCode(); ObjectTemplate template = new ObjectTemplate().contentType(contentType).size(contentLength) .contentEncoding(contentEncoding).contentLanguage(contentLanguage) .contentDisposition(contentDisposition).name(name).customMetadata(userMeta) .storageClass(StorageClass.fromTier(from.getTier())); if (md5 != null) { template.md5Hash(base64().encode(md5.asBytes())); }/*from w w w. j a v a 2s . c om*/ return template; }
From source file:org.jclouds.s3.filters.Aws4SignerForChunkedUpload.java
protected HttpRequest sign(HttpRequest request) throws HttpException { checkNotNull(request, "request is not ready to sign"); checkNotNull(request.getEndpoint(), "request is not ready to sign, request.endpoint not present."); Payload payload = request.getPayload(); // chunked upload required content-length. Long contentLength = payload.getContentMetadata().getContentLength(); // check contentLength not null checkNotNull(contentLength, "request is not ready to sign, payload contentLength not present."); // get host from request endpoint. String host = request.getEndpoint().getHost(); Date date = timestampProvider.get(); String timestamp = timestampFormat.format(date); String datestamp = dateFormat.format(date); String service = serviceAndRegion.service(); String region = serviceAndRegion.region(host); String credentialScope = Joiner.on('/').join(datestamp, region, service, "aws4_request"); HttpRequest.Builder<?> requestBuilder = request.toBuilder() // .removeHeader(AUTHORIZATION) // remove Authorization .removeHeader(DATE) // remove Date .removeHeader(CONTENT_LENGTH); // remove Content-Length ImmutableMap.Builder<String, String> signedHeadersBuilder = ImmutableSortedMap .<String, String>naturalOrder(); // content-encoding String contentEncoding = CONTENT_ENCODING_HEADER_AWS_CHUNKED; String originalContentEncoding = payload.getContentMetadata().getContentEncoding(); if (originalContentEncoding != null) { contentEncoding += "," + originalContentEncoding; }/*from w w w . ja va 2 s .c o m*/ requestBuilder.replaceHeader(HttpHeaders.CONTENT_ENCODING, contentEncoding); signedHeadersBuilder.put(HttpHeaders.CONTENT_ENCODING.toLowerCase(), contentEncoding); // x-amz-decoded-content-length requestBuilder.replaceHeader(AMZ_DECODED_CONTENT_LENGTH_HEADER, contentLength.toString()); signedHeadersBuilder.put(AMZ_DECODED_CONTENT_LENGTH_HEADER.toLowerCase(), contentLength.toString()); // how big is the overall request stream going to be once we add the signature // 'headers' to each chunk? long totalLength = calculateChunkedContentLength(contentLength, userDataBlockSize); requestBuilder.replaceHeader(CONTENT_LENGTH, Long.toString(totalLength)); signedHeadersBuilder.put(CONTENT_LENGTH.toLowerCase(), Long.toString(totalLength)); // Content MD5 String contentMD5 = request.getFirstHeaderOrNull(CONTENT_MD5); if (payload != null) { HashCode md5 = payload.getContentMetadata().getContentMD5AsHashCode(); if (md5 != null) { contentMD5 = BaseEncoding.base64().encode(md5.asBytes()); } } if (contentMD5 != null) { requestBuilder.replaceHeader(CONTENT_MD5, contentMD5); signedHeadersBuilder.put(CONTENT_MD5.toLowerCase(), contentMD5); } // Content Type // content-type is not a required signing param. However, examples use this, so we include it to ease testing. String contentType = getContentType(request); if (!Strings.isNullOrEmpty(contentType)) { requestBuilder.replaceHeader(HttpHeaders.CONTENT_TYPE, contentType); signedHeadersBuilder.put(HttpHeaders.CONTENT_TYPE.toLowerCase(), contentType); } else { requestBuilder.removeHeader(HttpHeaders.CONTENT_TYPE); } // host requestBuilder.replaceHeader(HttpHeaders.HOST, host); signedHeadersBuilder.put(HttpHeaders.HOST.toLowerCase(), host); // user-agent, not a required signing param if (request.getHeaders().containsKey(HttpHeaders.USER_AGENT)) { signedHeadersBuilder.put(HttpHeaders.USER_AGENT.toLowerCase(), request.getFirstHeaderOrNull(HttpHeaders.USER_AGENT)); } // all x-amz-* headers appendAmzHeaders(request, signedHeadersBuilder); // x-amz-security-token Credentials credentials = creds.get(); if (credentials instanceof SessionCredentials) { String token = SessionCredentials.class.cast(credentials).getSessionToken(); requestBuilder.replaceHeader(AMZ_SECURITY_TOKEN_HEADER, token); signedHeadersBuilder.put(AMZ_SECURITY_TOKEN_HEADER.toLowerCase(), token); } // x-amz-content-sha256 String contentSha256 = getPayloadHash(); requestBuilder.replaceHeader(AMZ_CONTENT_SHA256_HEADER, contentSha256); signedHeadersBuilder.put(AMZ_CONTENT_SHA256_HEADER.toLowerCase(), contentSha256); // put x-amz-date requestBuilder.replaceHeader(AMZ_DATE_HEADER, timestamp); signedHeadersBuilder.put(AMZ_DATE_HEADER.toLowerCase(), timestamp); ImmutableMap<String, String> signedHeaders = signedHeadersBuilder.build(); String stringToSign = createStringToSign(request.getMethod(), request.getEndpoint(), signedHeaders, timestamp, credentialScope, contentSha256); signatureWire.getWireLog().debug("<< " + stringToSign); byte[] signatureKey = signatureKey(credentials.credential, datestamp, region, service); // init hmacSHA256 processor for seed signature and chunked block signature ByteProcessor<byte[]> hmacSHA256; try { hmacSHA256 = hmacSHA256(crypto, signatureKey); } catch (InvalidKeyException e) { throw new ChunkedUploadException("invalid key", e); } // Calculating the Seed Signature String signature; try { signature = hex(readBytes(toInputStream(stringToSign), hmacSHA256)); } catch (IOException e) { throw new ChunkedUploadException("hmac sha256 seed signature error", e); } StringBuilder authorization = new StringBuilder(AMZ_ALGORITHM_HMAC_SHA256).append(" "); authorization.append("Credential=").append(Joiner.on("/").join(credentials.identity, credentialScope)) .append(", "); authorization.append("SignedHeaders=").append(Joiner.on(";").join(signedHeaders.keySet())).append(", "); authorization.append("Signature=").append(signature); // replace request payload with chunked upload payload ChunkedUploadPayload chunkedPayload = new ChunkedUploadPayload(payload, userDataBlockSize, timestamp, credentialScope, hmacSHA256, signature); chunkedPayload.getContentMetadata().setContentEncoding(null); return requestBuilder.replaceHeader(HttpHeaders.AUTHORIZATION, authorization.toString()) .payload(chunkedPayload).build(); }
From source file:io.divolte.server.ShortTermDuplicateMemory.java
private boolean isProbablyDuplicate(final HashCode eventDigest) { // Our hashing algorithm produces 8 bytes: // 0: slot[0] // 1: slot[1] // 2: slot[2] // 3: slot[3] // 4://www . j ava2 s. c o m // 5: // 6: // 7: // 8: signature[0] // 9: .. // 10: .. // 11: .. // 12: .. // 13: .. // 14: .. // 15: signature[7] final byte[] hashBytes = eventDigest.asBytes(); // We use the low int for the slot. final int slotSelector = Ints.fromBytes(hashBytes[0], hashBytes[1], hashBytes[2], hashBytes[3]); // We use the high long for the signature. final long signature = Longs.fromBytes(hashBytes[8], hashBytes[9], hashBytes[10], hashBytes[11], hashBytes[12], hashBytes[13], hashBytes[14], hashBytes[15]); final int slot = (slotSelector & Integer.MAX_VALUE) % memory.length; final boolean result = memory[slot] == signature; memory[slot] = signature; return result; }
From source file:org.jclouds.googlecloudstorage.blobstore.GoogleCloudStorageBlobStore.java
@Override public String putBlob(String container, Blob blob, PutOptions options) { long length = checkNotNull(blob.getPayload().getContentMetadata().getContentLength()); if (length != 0 && (options.isMultipart() || !blob.getPayload().isRepeatable())) { // JCLOUDS-912 prevents using single-part uploads with InputStream payloads. // Work around this with multi-part upload which buffers parts in-memory. return putMultipartBlob(container, blob, options); } else {// ww w. ja v a2 s . c o m ObjectTemplate template = blobMetadataToObjectTemplate.apply(blob.getMetadata()); HashCode md5 = blob.getMetadata().getContentMetadata().getContentMD5AsHashCode(); if (md5 != null) { template.md5Hash(base64().encode(md5.asBytes())); } if (options.getBlobAccess() == BlobAccess.PUBLIC_READ) { ObjectAccessControls controls = ObjectAccessControls.builder().entity("allUsers").bucket(container) .role(READER).build(); template.addAcl(controls); } return api.getObjectApi().multipartUpload(container, template, blob.getPayload()).etag(); } }
From source file:org.gaul.s3proxy.S3ProxyHandler.java
private static void addMetadataToResponse(HttpServletResponse response, BlobMetadata metadata) { ContentMetadata contentMetadata = metadata.getContentMetadata(); response.addHeader(HttpHeaders.CONTENT_DISPOSITION, contentMetadata.getContentDisposition()); response.addHeader(HttpHeaders.CONTENT_ENCODING, contentMetadata.getContentEncoding()); response.addHeader(HttpHeaders.CONTENT_LANGUAGE, contentMetadata.getContentLanguage()); response.addHeader(HttpHeaders.CONTENT_LENGTH, contentMetadata.getContentLength().toString()); response.setContentType(contentMetadata.getContentType()); HashCode contentMd5 = contentMetadata.getContentMD5AsHashCode(); if (contentMd5 != null) { byte[] contentMd5Bytes = contentMd5.asBytes(); response.addHeader(HttpHeaders.CONTENT_MD5, BaseEncoding.base64().encode(contentMd5Bytes)); response.addHeader(HttpHeaders.ETAG, "\"" + BaseEncoding.base16().lowerCase().encode(contentMd5Bytes) + "\""); }//from ww w. j a v a2 s. com Date expires = contentMetadata.getExpires(); if (expires != null) { response.addDateHeader(HttpHeaders.EXPIRES, expires.getTime()); } response.addDateHeader(HttpHeaders.LAST_MODIFIED, metadata.getLastModified().getTime()); for (Map.Entry<String, String> entry : metadata.getUserMetadata().entrySet()) { response.addHeader(USER_METADATA_PREFIX + entry.getKey(), entry.getValue()); } }
From source file:com.google.cloud.hadoop.gcsio.testing.InMemoryObjectEntry.java
public InMemoryObjectEntry(String bucketName, String objectName, long createTimeMillis, String contentType, Map<String, byte[]> metadata) { // Override close() to commit its completed byte array into completedContents to reflect // the behavior that any readable contents are only well-defined if the writeStream is closed. writeStream = new ByteArrayOutputStream() { @Override//from w w w.j av a2 s .co m public synchronized void close() throws IOException { synchronized (InMemoryObjectEntry.this) { completedContents = toByteArray(); HashCode md5 = Hashing.md5().hashBytes(completedContents); HashCode crc32c = Hashing.crc32c().hashBytes(completedContents); writeStream = null; writeChannel = null; info = new GoogleCloudStorageItemInfo(info.getResourceId(), info.getCreationTime(), completedContents.length, null, null, info.getContentType(), info.getMetadata(), info.getContentGeneration(), 0L, new VerificationAttributes(md5.asBytes(), Ints.toByteArray(crc32c.asInt()))); } } }; // We have to delegate because we can't extend from the inner class returned by, // Channels.newChannel, and the default version doesn't enforce ClosedChannelException // when trying to write to a closed channel; probably because it relies on the underlying // output stream throwing when closed. The ByteArrayOutputStream doesn't enforce throwing // when closed, so we have to manually do it. WritableByteChannel delegateWriteChannel = Channels.newChannel(writeStream); writeChannel = new WritableByteChannelImpl(delegateWriteChannel); // Size 0 initially because this object exists, but contains no data. info = new GoogleCloudStorageItemInfo(new StorageResourceId(bucketName, objectName), createTimeMillis, 0, null, null, contentType, ImmutableMap.copyOf(metadata), createTimeMillis, 0L); }
From source file:com.pmeade.websocket.io.WebSocketServerInputStream.java
/** * Perform the initial WebSocket handshake. WebSockets connect with an * HTTP Request to upgrade the connection to a WebSocket connection. This * method ensures that the request is correctly formed, and provides * the appropriate response to the client. After this method is called, * further communication is performed solely with WebSocket frames. * @throws IOException if anything goes wrong with the underlying stream *///from w ww . j a v a 2 s. c o m private void shakeHands() throws IOException { HttpRequest req = new HttpRequest(inputStream); String requestLine = req.get(HttpRequest.REQUEST_LINE); handshakeComplete = checkStartsWith(requestLine, "GET /") && checkContains(requestLine, "HTTP/") && req.get("Host") != null && checkContains(req.get("Upgrade"), "websocket") && checkContains(req.get("Connection"), "Upgrade") && "13".equals(req.get("Sec-WebSocket-Version")) && req.get("Sec-WebSocket-Key") != null; String nonce = req.get("Sec-WebSocket-Key"); if (handshakeComplete) { byte[] nonceBytes = BaseEncoding.base64().decode(nonce); if (nonceBytes.length != HANDSHAKE_NONCE_LENGTH) { handshakeComplete = false; } } // if we have met all the requirements if (handshakeComplete) { outputPeer.write(asUTF8("HTTP/1.1 101 Switching Protocols\r\n")); outputPeer.write(asUTF8("Upgrade: websocket\r\n")); outputPeer.write(asUTF8("Connection: upgrade\r\n")); outputPeer.write(asUTF8("Sec-WebSocket-Accept: ")); HashFunction hf = Hashing.sha1(); HashCode hc = hf.newHasher().putString(nonce, StandardCharsets.UTF_8) .putString(WEBSOCKET_ACCEPT_UUID, StandardCharsets.UTF_8).hash(); String acceptKey = BaseEncoding.base64().encode(hc.asBytes()); outputPeer.write(asUTF8(acceptKey)); outputPeer.write(asUTF8("\r\n\r\n")); } outputPeer.setHandshakeComplete(handshakeComplete); }
From source file:org.fabrician.enabler.DockerContainer.java
public ProcessWrapper getExecCmdProcessWrapper(String execCmd) throws Exception { String command = "docker exec -d " + dockerContainerTag + " " + execCmd; if (useSudo) { command = "sudo " + command; }/*from www.ja va 2 s . c o m*/ File workDir = new File(getWorkDir()); HashFunction hf = Hashing.md5(); HashCode hc = hf.newHasher().putString(command, Charsets.UTF_8).hash(); String cmd_pid = "_cmd_" + BaseEncoding.base64Url().encode(hc.asBytes()) + ".pid"; try { String engineOS = getEngineProperty(EngineProperties.OS); ProcessWrapper p = getProcessWrapper(command, workDir, engineOS + cmd_pid); return p; } catch (Exception ex) { getEngineLogger().log(Level.SEVERE, "while getting a process wrapper for 'docker exec' command [" + execCmd + "]", ex); throw ex; } }