Returns a "complete" S3 specific signer, taking into the S3 bucket, key,
and the current S3 client configuration into account.
509290
protected Signer createSigner(final Request<?> request,
                                  final String bucketName,
                                  final String key,
                                  final boolean isAdditionalHeadRequestToFindRegion) {

        // Instead of using request.getEndpoint() for this parameter, we use endpoint which is because
        // in accelerate mode, the endpoint in request is regionless. We need the client-wide endpoint
        // to fetch the region information and pick the correct signer.
        URI uri = clientOptions.isAccelerateModeEnabled() ? endpoint : request.getEndpoint();
        final Signer signer = getSignerByURI(uri);

        if (!isSignerOverridden()) {

            if ((signer instanceof AWSS3V4Signer) && bucketRegionShouldBeCached(request)) {

                String region = bucketRegionCache.get(bucketName);
                if (region != null) {
                     // If cache contains the region for the bucket, create an endpoint for the region and
                     // update the request with that endpoint.
                     request.addHandlerContext(HandlerContextKey.SIGNING_REGION, region);
                     resolveRequestEndpoint(request, bucketName, key, RuntimeHttpUtils.toUri(RegionUtils.getRegion(region).getServiceEndpoint(S3_SERVICE_NAME), clientConfiguration));
                     return updateSigV4SignerWithRegion((AWSS3V4Signer) signer, region);
                } else if (request.getOriginalRequest() instanceof GeneratePresignedUrlRequest) {
                    String signerRegion = getSignerRegion();
                    if (signerRegion == null) {
                        return createSigV2Signer(request, bucketName, key);
                    }
                    return updateSigV4SignerWithRegion((AWSS3V4Signer) signer, signerRegion);
                } else if (isAdditionalHeadRequestToFindRegion) {
                    return updateSigV4SignerWithRegion((AWSS3V4Signer) signer, "us-east-1");
                }
            }

            String regionOverride = getSignerRegionOverride();
            if (regionOverride != null) {
                return updateSigV4SignerWithRegion(new AWSS3V4Signer(), regionOverride);
            }
        }

        if (signer instanceof S3Signer) {
            // The old S3Signer needs a method and path passed to its
            // constructor; if that's what we should use, getSigner()
            // will return a dummy instance and we need to create a
            // new one with the appropriate values for this request.
            return createSigV2Signer(request, bucketName, key);
        }

        return signer;
    }
651714
def s3_upload_signature
      signature = OpenSSL::HMAC.digest(
        OpenSSL::Digest.new('sha1'),
        config.secret_key,
        s3_upload_policy_document
      )
      encode(signature)
    end
529994
private static Signer lookupAndCreateSigner(String serviceName, String regionName) {
        String signerType = lookUpSignerTypeByServiceAndRegion(serviceName, regionName);
        return createSigner(signerType, serviceName);
    }
521495
def bucket_exists?(bucket_name)
      begin
        s3 = AWS::S3.new
        s3.buckets[bucket_name].exists?

      rescue AWS::S3::Errors::SignatureDoesNotMatch => e
        raise AWSCredentialsInvalidError, 'AWS access credentials are invalid'
      rescue AWS::Errors::Base => s3e
        raise S3AccessError.new(s3e.http_response), s3e.message
      end
    end
103068
def open_s3(self):
        """"""
        conn = boto.connect_s3(
            self.AWS_ACCESS_KEY_ID,
            self.AWS_SECRET_ACCESS_KEY,
            **self.get_s3connection_kwargs())
        try:
            bucket = conn.get_bucket(self.AWS_BUCKET_NAME)
        except boto.exception.S3ResponseError:
            bucket = conn.create_bucket(self.AWS_BUCKET_NAME)
        return bucket, boto.s3.key.Key(bucket)
113738
def sign_s3_upload(self):
        
        AWS_ACCESS_KEY = self.config_('AWS_ACCESS_KEY_ID')
        AWS_SECRET_KEY = self.config_('AWS_SECRET_ACCESS_KEY')
        S3_BUCKET = self.config_('AWS_S3_BUCKET_NAME')

        object_name = request.args.get('s3_object_name')
        mime_type = request.args.get('s3_object_type')
        expires = long(time.time()+10)
        amz_headers = "x-amz-acl:public-read"
        put_request = "PUT\n\n%s\n%d\n%s\n/%s/%s" % (mime_type, expires, amz_headers, S3_BUCKET, object_name)
        signature = base64.encodestring(hmac.new(AWS_SECRET_KEY, put_request, sha1).digest())
        signature = urllib.quote(urllib.quote_plus(signature.strip()))
        url = 'https://s3.amazonaws.com/%s/%s' % (S3_BUCKET, object_name)
        return jsonify({
            'signed_request': '%s?AWSAccessKeyId=%s&Expires=%d&Signature=%s' % (url, AWS_ACCESS_KEY, expires, signature),
             'url': url
          })
31085
def _get_v4_signed_headers(self):
        """"""
        if self.aws_session is None:
            boto_session = session.Session()
            creds = boto_session.get_credentials()
        else:
            creds = self.aws_session.get_credentials()
        if creds is None:
            raise CerberusClientException("Unable to locate AWS credentials")
        readonly_credentials = creds.get_frozen_credentials()

        # hardcode get-caller-identity request
        data = OrderedDict((('Action','GetCallerIdentity'), ('Version', '2011-06-15')))
        url = 'https://sts.{}.amazonaws.com/'.format(self.region)
        request_object = awsrequest.AWSRequest(method='POST', url=url, data=data)

        signer = auth.SigV4Auth(readonly_credentials, 'sts', self.region)
        signer.add_auth(request_object)
        return request_object.headers
504103
def finalize(self):
        
        signature = self.signer.finalize()
        sig_r, sig_s = decode_dss_signature(signature)
        sig_b64 = encode_signature(sig_r, sig_s)
        return sig_b64
235148
public static String credential(String accessKey, DateTime date, String region) {
    return accessKey + "/" + date.toString(DateFormat.SIGNER_DATE_FORMAT) + "/" + region + "/s3/aws4_request";
  }
108197
def get_instance_signature(instance):
    
    with suppress(AttributeError):
        return instance._getsate_bucketcache_()

    with suppress(AttributeError):
        return instance.__getstate__()

    return instance.__dict__
1151822
def get_s3_bucket_keys(api_client, bucket_name, bucket, check_encryption, check_acls):
    
    bucket['keys'] = []
    keys = handle_truncated_response(api_client.list_objects, {'Bucket': bucket_name}, ['Contents'])
    bucket['keys_count'] = len(keys['Contents'])
    key_count = 0
    update_status(key_count, bucket['keys_count'], 'keys')
    for key in keys['Contents']:
        key_count += 1
        key['name'] = key.pop('Key')
        key['LastModified'] = str(key['LastModified'])
        if check_encryption:
            try:
                # The encryption configuration is only accessible via an HTTP header, only returned when requesting one object at a time...
                k = api_client.get_object(Bucket = bucket_name, Key = key['name'])
                key['ServerSideEncryption'] = k['ServerSideEncryption'] if 'ServerSideEncryption' in k else None
                key['SSEKMSKeyId'] = k['SSEKMSKeyId'] if 'SSEKMSKeyId' in k else None
            except Exception as e:
                printException(e)
                continue
        if check_acls:
            try:
                key['grantees'] = get_s3_acls(api_client, bucket_name, bucket, key_name = key['name'])
            except Exception as e:
                continue
        # Save it
        bucket['keys'].append(key)
        update_status(key_count, bucket['keys_count'], 'keys')
1271181
def s3_connect(bucket_name, s3_access_key_id, s3_secret_key):
    
    conn = connect_s3(s3_access_key_id, s3_secret_key)
    try:
        return conn.get_bucket(bucket_name)
    except S3ResponseError as e:
        if e.status == 403:
            raise Exception("Bad Amazon S3 credentials.")
        raise
1062777
def s3(ctx, bucket_name, data_file, region):
    """"""
    if not ctx.data_file:
        ctx.data_file = data_file

    if not ctx.bucket_name:
        ctx.bucket_name = bucket_name

    if not ctx.region:
        ctx.region = region

    ctx.type = 's3'
398349
def get(self, bucket: str, key: str) -> bytes:
        
        try:
            response = self.s3_client.get_object(
                Bucket=bucket,
                Key=key
            )
            return response['Body'].read()
        except botocore.exceptions.ClientError as ex:
            if ex.response['Error']['Code'] == "NoSuchKey":
                raise BlobNotFoundError(f"Could not find s3://{bucket}/{key}") from ex
            raise BlobStoreUnknownError(ex)
876863
def signers(self):
        
        signerlist = libcrypto.CMS_get0_signers(self.ptr)
        if signerlist is None:
            raise CMSError("Cannot get signers")
        return StackOfX509(ptr=signerlist, disposable=False)
742179
def expected_signature(self):
        
        k_secret = b"AWS4" + self.key_mapping[self.access_key].encode("utf-8")
        k_date = hmac.new(k_secret, self.request_date.encode("utf-8"),
                          sha256).digest()
        k_region = hmac.new(k_date, self.region.encode("utf-8"),
                            sha256).digest()
        k_service = hmac.new(k_region, self.service.encode("utf-8"),
                             sha256).digest()
        k_signing = hmac.new(k_service, _aws4_request_bytes, sha256).digest()

        return hmac.new(k_signing, self.string_to_sign.encode("utf-8"),
                        sha256).hexdigest()
534541
def _get_key(key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable):
    '''
    
    '''
    if not key and __salt__['config.option']('s3.key'):
        key = __salt__['config.option']('s3.key')

    if not keyid and __salt__['config.option']('s3.keyid'):
        keyid = __salt__['config.option']('s3.keyid')

    if not kms_keyid and __salt__['config.option']('aws.kms.keyid'):
        kms_keyid = __salt__['config.option']('aws.kms.keyid')

    if not service_url and __salt__['config.option']('s3.service_url'):
        service_url = __salt__['config.option']('s3.service_url')

    if not service_url:
        service_url = 's3.amazonaws.com'

    if verify_ssl is None and __salt__['config.option']('s3.verify_ssl') is not None:
        verify_ssl = __salt__['config.option']('s3.verify_ssl')

    if verify_ssl is None:
        verify_ssl = True

    if location is None and __salt__['config.option']('s3.location') is not None:
        location = __salt__['config.option']('s3.location')

    if role_arn is None and __salt__['config.option']('s3.role_arn'):
        role_arn = __salt__['config.option']('s3.role_arn')

    if path_style is None and __salt__['config.option']('s3.path_style') is not None:
        path_style = __salt__['config.option']('s3.path_style')

    if path_style is None:
        path_style = False

    if https_enable is None and __salt__['config.option']('s3.https_enable') is not None:
        https_enable = __salt__['config.option']('s3.https_enable')

    if https_enable is None:
        https_enable = True

    return key, keyid, service_url, verify_ssl, kms_keyid, location, role_arn, path_style, https_enable