List of usage examples for com.amazonaws.util BinaryUtils toHex
public static String toHex(byte[] data)
From source file:com.comcast.cmb.common.util.AuthUtil.java
License:Apache License
public static String generateSignatureV4(HttpServletRequest request, URL url, Map<String, String> parameters, Map<String, String> headers, String version, String algorithm, String accessSecret) throws Exception { /* Example of authorization header value * AWS4-HMAC-SHA256 Credential=XK1MWJAYYGQ41ECH06WG/20131126/us-east-1/us-east-1/aws4_request, SignedHeaders=host;user-agent;x-amz-date, Signature=18541c4db00d098414c0bae7394450d1deada902699a45de02849dbcb336f9e3 *///from ww w .j ava 2 s . c o m String authorizationHeader = request.getHeader("authorization"); String credentialPart = authorizationHeader .substring(authorizationHeader.indexOf("Credential=") + "Credential=".length()); String[] credentialPartArray = credentialPart.split("/"); String regionName = credentialPartArray[2]; String serviceName = credentialPartArray[3]; String dateTime = request.getHeader("X-Amz-Date"); String dateStamp = credentialPartArray[1]; String scope = credentialPart.substring(credentialPart.indexOf("/") + 1, credentialPart.indexOf(",")); String payloadString = getPayload(request); String contentSha256 = BinaryUtils.toHex(hash(payloadString)); Map<String, String> filteredHeaders = filterHeader(headers); String stringToSign = getStringToSign("AWS4-" + algorithm, dateTime, scope, getCanonicalRequest(request, contentSha256, parameters, filteredHeaders)); byte[] secret = ("AWS4" + accessSecret).getBytes(); byte[] date = sign(dateStamp, secret, SigningAlgorithm.HmacSHA256); byte[] region = sign(regionName, date, SigningAlgorithm.HmacSHA256); byte[] service = sign(serviceName, region, SigningAlgorithm.HmacSHA256); byte[] signing = sign("aws4_request", service, SigningAlgorithm.HmacSHA256); byte[] signatureBytes = sign(stringToSign.getBytes(), signing, SigningAlgorithm.HmacSHA256); String signature = BinaryUtils.toHex(signatureBytes); return signature; }
From source file:com.comcast.cmb.common.util.AuthUtil.java
License:Apache License
protected static String getStringToSign(String algorithm, String dateTime, String scope, String canonicalRequest) { String stringToSign = algorithm + "\n" + dateTime + "\n" + scope + "\n" + BinaryUtils.toHex(hash(canonicalRequest)); logger.debug("AWS4 String to Sign: '\"" + stringToSign + "\""); return stringToSign; }
From source file:com.eucalyptus.simplequeue.SimpleQueueService.java
License:Open Source License
private static String calculateMessageBodyMd5(String messageBody) throws EucalyptusCloudException { if (LOG.isTraceEnabled()) { LOG.trace("Message body: " + messageBody); }/*from w w w . jav a2 s. c om*/ byte[] expectedMd5; try { expectedMd5 = Md5Utils.computeMD5Hash(messageBody.getBytes(UTF8)); } catch (Exception e) { throw new EucalyptusCloudException( "Unable to calculate the MD5 hash of the message body. " + e.getMessage(), e); } String expectedMd5Hex = BinaryUtils.toHex(expectedMd5); if (LOG.isTraceEnabled()) { LOG.trace("Expected MD5 of message body: " + expectedMd5Hex); } return expectedMd5Hex; }
From source file:com.eucalyptus.simplequeue.SimpleQueueService.java
License:Open Source License
/** * Returns the hex-encoded MD5 hash String of the given message attributes. *///from ww w.j av a 2s. co m private static String calculateMessageAttributesMd5(final Map<String, MessageAttributeValue> messageAttributes) throws EucalyptusCloudException { if (LOG.isTraceEnabled()) { LOG.trace("Message attribtues: " + messageAttributes); } List<String> sortedAttributeNames = new ArrayList<String>(messageAttributes.keySet()); Collections.sort(sortedAttributeNames); MessageDigest md5Digest = null; try { md5Digest = MessageDigest.getInstance("MD5"); for (String attrName : sortedAttributeNames) { MessageAttributeValue attrValue = messageAttributes.get(attrName); // Encoded Name updateLengthAndBytes(md5Digest, attrName); // Encoded Type updateLengthAndBytes(md5Digest, attrValue.getDataType()); // Encoded Value if (attrValue.getStringValue() != null) { md5Digest.update(STRING_TYPE_FIELD_INDEX); updateLengthAndBytes(md5Digest, attrValue.getStringValue()); } else if (attrValue.getBinaryValue() != null) { md5Digest.update(BINARY_TYPE_FIELD_INDEX); // Eucalyptus stores the value as a Base 64 encoded string. Convert to byte buffer ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.decode(attrValue.getBinaryValue())); updateLengthAndBytes(md5Digest, byteBuffer); } else if (attrValue.getStringListValue() != null && attrValue.getStringListValue().size() > 0) { md5Digest.update(STRING_LIST_TYPE_FIELD_INDEX); for (String strListMember : attrValue.getStringListValue()) { updateLengthAndBytes(md5Digest, strListMember); } } else if (attrValue.getBinaryListValue() != null && attrValue.getBinaryListValue().size() > 0) { md5Digest.update(BINARY_LIST_TYPE_FIELD_INDEX); for (String byteListMember : attrValue.getBinaryListValue()) { // Eucalyptus stores the value as a Base 64 encoded string. Convert to byte buffer ByteBuffer byteBuffer = ByteBuffer.wrap(Base64.decode(byteListMember)); updateLengthAndBytes(md5Digest, byteBuffer); } } } } catch (Exception e) { throw new EucalyptusCloudException( "Unable to calculate the MD5 hash of the message attributes. " + e.getMessage(), e); } String expectedMd5Hex = BinaryUtils.toHex(md5Digest.digest()); if (LOG.isTraceEnabled()) { LOG.trace("Expected MD5 of message attributes: " + expectedMd5Hex); } return expectedMd5Hex; }
From source file:com.github.rholder.esthree.command.Get.java
License:Apache License
@Override public Integer call() throws Exception { // this is the most up to date digest, it's initialized here but later holds the most up to date valid digest currentDigest = MessageDigest.getInstance("MD5"); currentDigest = retryingGet();//from www. ja v a2s .c om if (progressListener != null) { progressListener.progressChanged(new ProgressEvent(ProgressEventType.TRANSFER_STARTED_EVENT)); } if (!fullETag.contains("-")) { byte[] expected = BinaryUtils.fromHex(fullETag); byte[] current = currentDigest.digest(); if (!Arrays.equals(expected, current)) { throw new AmazonClientException("Unable to verify integrity of data download. " + "Client calculated content hash didn't match hash calculated by Amazon S3. " + "The data may be corrupt."); } } else { // TODO log warning that we can't validate the MD5 if (verbose) { System.err.println("\nMD5 does not exist on AWS for file, calculated value: " + BinaryUtils.toHex(currentDigest.digest())); } } // TODO add ability to resume from previously downloaded chunks // TODO add rate limiter return 0; }
From source file:com.github.rholder.esthree.command.GetMultipart.java
License:Apache License
@Override public Integer call() throws Exception { ObjectMetadata om = amazonS3Client.getObjectMetadata(bucket, key); contentLength = om.getContentLength(); // this is the most up to date digest, it's initialized here but later holds the most up to date valid digest currentDigest = MessageDigest.getInstance("MD5"); chunkSize = chunkSize == null ? DEFAULT_CHUNK_SIZE : chunkSize; fileParts = Parts.among(contentLength, chunkSize); for (Part fp : fileParts) { /*// w ww . j a v a2 s . c om * We'll need to compute the digest on the full incoming stream for * each valid chunk that comes in. Invalid chunks will need to be * recomputed and fed through a copy of the MD5 that was valid up * until the latest chunk. */ currentDigest = retryingGetWithRange(fp.start, fp.end); } // TODO fix total content length progress bar if (progressListener != null) { progressListener.progressChanged(new ProgressEvent(ProgressEventType.TRANSFER_STARTED_EVENT)); } String fullETag = om.getETag(); if (!fullETag.contains("-")) { byte[] expected = BinaryUtils.fromHex(fullETag); byte[] current = currentDigest.digest(); if (!Arrays.equals(expected, current)) { throw new AmazonClientException("Unable to verify integrity of data download. " + "Client calculated content hash didn't match hash calculated by Amazon S3. " + "The data may be corrupt."); } } else { // TODO log warning that we can't validate the MD5 if (verbose) { System.err.println("\nMD5 does not exist on AWS for file, calculated value: " + BinaryUtils.toHex(currentDigest.digest())); } } // TODO add ability to resume from previously downloaded chunks // TODO add rate limiter return 0; }
From source file:com.google.crypto.tink.integration.awskms.AwsKmsAead.java
License:Apache License
@Override public byte[] encrypt(final byte[] plaintext, final byte[] associatedData) throws GeneralSecurityException { try {//from www .j a v a 2s . c om EncryptRequest req = new EncryptRequest().withKeyId(keyArn).withPlaintext(ByteBuffer.wrap(plaintext)); if (associatedData != null && associatedData.length != 0) { req = req.addEncryptionContextEntry("associatedData", BinaryUtils.toHex(associatedData)); } return kmsClient.encrypt(req).getCiphertextBlob().array(); } catch (AmazonServiceException e) { throw new GeneralSecurityException("encryption failed", e); } }
From source file:com.google.crypto.tink.integration.awskms.AwsKmsAead.java
License:Apache License
@Override public byte[] decrypt(final byte[] ciphertext, final byte[] associatedData) throws GeneralSecurityException { try {/*from w w w . j ava 2 s. c o m*/ DecryptRequest req = new DecryptRequest().withCiphertextBlob(ByteBuffer.wrap(ciphertext)); if (associatedData != null && associatedData.length != 0) { req = req.addEncryptionContextEntry("associatedData", BinaryUtils.toHex(associatedData)); } DecryptResult result = kmsClient.decrypt(req); if (!result.getKeyId().equals(keyArn)) { throw new GeneralSecurityException("decryption failed: wrong key id"); } return result.getPlaintext().array(); } catch (AmazonServiceException e) { throw new GeneralSecurityException("decryption failed", e); } }
From source file:com.ibm.og.s3.v4.AwsChunkedEncodingInputStream.java
License:Open Source License
private byte[] createSignedChunk(final byte[] chunkData) { final StringBuilder chunkHeader = new StringBuilder(); // chunk-size chunkHeader.append(Integer.toHexString(chunkData.length)); byte[] chunkDigest; if (this.digestCache != null) { try {//www. ja v a2 s . c om chunkDigest = this.digestCache.get((long) chunkData.length); } catch (final ExecutionException e) { throw new RuntimeException(e); } } else { chunkDigest = this.sha256.digest(chunkData); } // sig-extension final String chunkStringToSign = CHUNK_STRING_TO_SIGN_PREFIX + "\n" + this.dateTime + "\n" + this.keyPath + "\n" + this.priorChunkSignature + "\n" + AbstractAWSSigner.EMPTY_STRING_SHA256_HEX + "\n" + BinaryUtils.toHex(chunkDigest); final String chunkSignature = BinaryUtils .toHex(this.aws4Signer.signWithMac(chunkStringToSign, this.hmacSha256)); this.priorChunkSignature = chunkSignature; chunkHeader.append(CHUNK_SIGNATURE_HEADER).append(chunkSignature).append(CRLF); try { final byte[] header = chunkHeader.toString().getBytes(UTF8); final byte[] trailer = CRLF.getBytes(UTF8); final byte[] signedChunk = new byte[header.length + chunkData.length + trailer.length]; System.arraycopy(header, 0, signedChunk, 0, header.length); System.arraycopy(chunkData, 0, signedChunk, header.length, chunkData.length); System.arraycopy(trailer, 0, signedChunk, header.length + chunkData.length, trailer.length); return signedChunk; } catch (final Exception e) { throw new AmazonClientException("Unable to sign the chunked data. " + e.getMessage(), e); } }
From source file:com.ibm.og.s3.v4.AWSS3V4Signer.java
License:Open Source License
/** * If necessary, creates a chunk-encoding wrapper on the request payload. *///from w ww . j a v a 2 s . c om @Override protected void processRequestPayload(final SignableRequest<?> request, final byte[] signature, final byte[] signingKey, final AWS4SignerRequestParams signerRequestParams) { if (useChunkEncoding(request)) { final AwsChunkedEncodingInputStream chunkEncodededStream = new AwsChunkedEncodingInputStream( request.getContent(), signingKey, signerRequestParams.getFormattedSigningDateTime(), signerRequestParams.getScope(), BinaryUtils.toHex(signature), this, this.digestCache); request.setContent(chunkEncodededStream); } }