Start line:  
End line:  

Snippet Preview

Snippet HTML Code

Stack Overflow Questions
  /*
   * Copyright 2010-2015 Amazon.com, Inc. or its affiliates. All Rights Reserved.
   *
   * Licensed under the Apache License, Version 2.0 (the "License").
   * You may not use this file except in compliance with the License.
   * A copy of the License is located at
   *
   *  http://aws.amazon.com/apache2.0
   *
  * or in the "license" file accompanying this file. This file is distributed
  * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either
  * express or implied. See the License for the specific language governing
  * permissions and limitations under the License.
  */
 package com.amazonaws.auth;
 
 import static com.amazonaws.util.StringUtils.UTF8;
 
 import java.net.URI;
 import java.util.Date;
 import java.util.Map;
 
 
Abstract base class for AWS signing protocol implementations. Provides utilities commonly needed by signing protocols such as computing canonicalized host names, query string parameters, etc.

Not intended to be sub-classed by developers.

 
 public abstract class AbstractAWSSigner implements Signer {

    
Computes an RFC 2104-compliant HMAC signature and returns the result as a Base64 encoded string.
 
     protected String signAndBase64Encode(String dataString key,
             SigningAlgorithm algorithmthrows AmazonClientException {
         return signAndBase64Encode(data.getBytes(), keyalgorithm);
     }

    
Computes an RFC 2104-compliant HMAC signature for an array of bytes and returns the result as a Base64 encoded string.
 
     protected String signAndBase64Encode(byte[] dataString key,
             SigningAlgorithm algorithmthrows AmazonClientException {
         try {
             byte[] signature = sign(datakey.getBytes(), algorithm);
             return Base64.encodeAsString(signature);
         } catch (Exception e) {
             throw new AmazonClientException(
                     "Unable to calculate a request signature: "
                             + e.getMessage(), e);
         }
     }
 
     public byte[] sign(String stringDatabyte[] key,
             SigningAlgorithm algorithmthrows AmazonClientException {
         try {
             byte[] data = stringData.getBytes();
             return sign(datakeyalgorithm);
         } catch (Exception e) {
             throw new AmazonClientException(
                     "Unable to calculate a request signature: "
                             + e.getMessage(), e);
         }
     }
 
     protected byte[] sign(byte[] databyte[] key,
             SigningAlgorithm algorithmthrows AmazonClientException {
         try {
             Mac mac = Mac.getInstance(algorithm.toString());
             mac.init(new SecretKeySpec(keyalgorithm.toString()));
             return mac.doFinal(data);
         } catch (Exception e) {
             throw new AmazonClientException(
                     "Unable to calculate a request signature: "
                             + e.getMessage(), e);
         }
     }

    
Hashes the string contents (assumed to be UTF-8) using the SHA-256 algorithm.

Parameters:
text The string to hash.
Returns:
The hashed bytes from the specified string.
Throws:
com.amazonaws.AmazonClientException If the hash cannot be computed.
    public byte[] hash(String textthrows AmazonClientException {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(text.getBytes());
            return md.digest();
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Unable to compute hash while signing request: "
                            + e.getMessage(), e);
        }
    }
    protected byte[] hash(InputStream inputthrows AmazonClientException {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            @SuppressWarnings("resource")
            DigestInputStream digestInputStream = new SdkDigestInputStream(
                    inputmd);
            byte[] buffer = new byte[1024];
            while (digestInputStream.read(buffer) > -1)
                ;
            return digestInputStream.getMessageDigest().digest();
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Unable to compute hash while signing request: "
                            + e.getMessage(), e);
        }
    }

    
Hashes the binary data using the SHA-256 algorithm.

Parameters:
data The binary data to hash.
Returns:
The hashed bytes from the specified data.
Throws:
com.amazonaws.AmazonClientException If the hash cannot be computed.
    public byte[] hash(byte[] datathrows AmazonClientException {
        try {
            MessageDigest md = MessageDigest.getInstance("SHA-256");
            md.update(data);
            return md.digest();
        } catch (Exception e) {
            throw new AmazonClientException(
                    "Unable to compute hash while signing request: "
                            + e.getMessage(), e);
        }
    }
    
Examines the specified query string parameters and returns a canonicalized form.

The canonicalized query string is formed by first sorting all the query string parameters, then URI encoding both the key and value and then joining them, in order, separating key value pairs with an '&'.

Parameters:
parameters The query string parameters to be canonicalized.
Returns:
A canonicalized form for the specified query string parameters.
    protected String getCanonicalizedQueryString(Map<StringStringparameters) {
        SortedMap<StringStringsorted = new TreeMap<StringString>();
        Iterator<Map.Entry<StringString>> pairs = parameters.entrySet().iterator();
        while (pairs.hasNext()) {
            Map.Entry<StringStringpair = pairs.next();
            String key = pair.getKey();
            String value = pair.getValue();
            sorted.put(SdkHttpUtils.urlEncode(keyfalse), SdkHttpUtils.urlEncode(valuefalse));
        }
        StringBuilder builder = new StringBuilder();
        pairs = sorted.entrySet().iterator();
        while (pairs.hasNext()) {
            Map.Entry<StringStringpair = pairs.next();
            builder.append(pair.getKey());
            builder.append("=");
            builder.append(pair.getValue());
            if (pairs.hasNext()) {
                builder.append("&");
            }
        }
        return builder.toString();
    }
    protected String getCanonicalizedQueryString(SignableRequest<?> request) {
        /*
         * If we're using POST and we don't have any request payload content,
         * then any request query parameters will be sent as the payload, and
         * not in the actual query string.
         */
        if (SdkHttpUtils.usePayloadForQueryParameters(request))
            return "";
        return this.getCanonicalizedQueryString(request.getParameters());
    }

    
Returns the request's payload as binary data.

Parameters:
request The request
Returns:
The data from the request's payload, as binary data.
    protected byte[] getBinaryRequestPayload(SignableRequest<?> request) {
        if (SdkHttpUtils.usePayloadForQueryParameters(request)) {
            String encodedParameters = SdkHttpUtils.encodeParameters(request);
            if (encodedParameters == null)
                return new byte[0];
            return encodedParameters.getBytes();
        }
        return getBinaryRequestPayloadWithoutQueryParams(request);
    }

    
Returns the request's payload as a String.

Parameters:
request The request
Returns:
The data from the request's payload, as a string.
    protected String getRequestPayload(SignableRequest<?> request) {
        return newString(getBinaryRequestPayload(request));
    }

    
Returns the request's payload contents as a String, without processing any query string params (i.e. no form encoding for query params).

Parameters:
request The request
Returns:
the request's payload contents as a String, not including any form encoding of query string params.
        return newString(getBinaryRequestPayloadWithoutQueryParams(request));
    }

    
Returns the request's payload contents as binary data, without processing any query string params (i.e. no form encoding for query params).

Parameters:
request The request
Returns:
The request's payload contents as binary data, not including any form encoding of query string params.
    protected byte[] getBinaryRequestPayloadWithoutQueryParams(SignableRequest<?> request) {
        try {
            ReadLimitInfo info = request.getReadLimitInfo();
            content.mark(info == null ? -1 : info.getReadLimit());
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            byte[] buffer = new byte[1024 * 5];
            while (true) {
                int bytesRead = content.read(buffer);
                if (bytesRead == -1) break;
                byteArrayOutputStream.write(buffer, 0, bytesRead);
            }
            byteArrayOutputStream.close();
            content.reset();
            return byteArrayOutputStream.toByteArray();
        } catch (Exception e) {
            throw new AmazonClientException("Unable to read request payload to sign request: " + e.getMessage(), e);
        }
    }
        if (SdkHttpUtils.usePayloadForQueryParameters(request)) {
            String encodedParameters = SdkHttpUtils.encodeParameters(request);
            if (encodedParameters == null)
                return new ByteArrayInputStream(new byte[0]);
            return new ByteArrayInputStream(
                    encodedParameters.getBytes());
        }
        return getBinaryRequestPayloadStreamWithoutQueryParams(request);
    }
        try {
            InputStream is = request.getContentUnwrapped();
            if (is == null)
                return new ByteArrayInputStream(new byte[0]);
            if (!is.markSupported())
                throw new AmazonClientException("Unable to read request payload to sign request.");
            return is;
        } catch (AmazonClientException e) {
            throw e;
        } catch (Exception e) {
            throw new AmazonClientException("Unable to read request payload to sign request: " + e.getMessage(), e);
        }
    }
    protected String getCanonicalizedResourcePath(String resourcePath) {
        return getCanonicalizedResourcePath(resourcePathtrue);
    }
    protected String getCanonicalizedResourcePath(String resourcePathboolean urlEncode) {
        if (resourcePath == null || resourcePath.isEmpty()) {
            return "/";
        } else {
            String value = urlEncode ? SdkHttpUtils.urlEncode(resourcePathtrue) : resourcePath;
            if (value.startsWith("/")) {
                return value;
            } else {
                return "/".concat(value);
            }
        }
    }
    protected String getCanonicalizedEndpoint(URI endpoint) {
        String endpointForStringToSign = endpoint.getHost().toLowerCase();
        /*
         * Apache HttpClient will omit the port in the Host header for default
         * port values (i.e. 80 for HTTP and 443 for HTTPS) even if we
         * explicitly specify it, so we need to be careful that we use the same
         * value here when we calculate the string to sign and in the Host
         * header we send in the HTTP request.
         */
        if (SdkHttpUtils.isUsingNonDefaultPort(endpoint)) {
            endpointForStringToSign += ":" + endpoint.getPort();
        }
        return endpointForStringToSign;
    }

    
Loads the individual access key ID and secret key from the specified credentials, ensuring that access to the credentials is synchronized on the credentials object itself, and trimming any extra whitespace from the credentials.

Returns either a BasicSessionCredentials or a BasicAWSCredentials object, depending on the input type.

Parameters:
credentials
Returns:
A new credentials object with the sanitized credentials.
    protected AWSCredentials sanitizeCredentials(AWSCredentials credentials) {
        String accessKeyId = null;
        String secretKey   = null;
        String token = null;
        synchronized (credentials) {
            accessKeyId = credentials.getAWSAccessKeyId();
            secretKey   = credentials.getAWSSecretKey();
            if ( credentials instanceof AWSSessionCredentials ) {
                token = ((AWSSessionCredentialscredentials).getSessionToken();
            }
        }
        if (secretKey != nullsecretKey = secretKey.trim();
        if (accessKeyId != nullaccessKeyId = accessKeyId.trim();
        if (token != nulltoken = token.trim();
        if (credentials instanceof AWSSessionCredentials) {
            return new BasicSessionCredentials(accessKeyIdsecretKeytoken);
        }
        return new BasicAWSCredentials(accessKeyIdsecretKey);
    }

    
Safely converts a UTF-8 encoded byte array into a String.

Parameters:
bytes UTF-8 encoded binary character data.
Returns:
The converted String object.
    protected String newString(byte[] bytes) {
        return new String(bytes);
    }

    
Returns the current time minus the given offset in seconds. The intent is to adjust the current time in the running JVM to the corresponding wall clock time at AWS for request signing purposes.

Parameters:
offsetInSeconds offset in seconds
    protected Date getSignatureDate(int offsetInSeconds) {
        return new Date(System.currentTimeMillis() - offsetInSeconds*1000);
    }

    
Returns the time offset in seconds.
    @Deprecated
    protected int getTimeOffset(SignableRequest<?> request) {
        final int globleOffset = SDKGlobalTime.getGlobalTimeOffset();
        return globleOffset == 0 ? request.getTimeOffset() : globleOffset;
    }

    
Adds session credentials to the request given.

Parameters:
request The request to add session credentials information to
credentials The session credentials to add to the request
    protected abstract void addSessionCredentials(SignableRequest<?> request,
            AWSSessionCredentials credentials);
New to GrepCode? Check out our FAQ X