def rotate_key(bucket, obj, current_encryption_key, current_key_hash,
               new_encryption_key, new_key_hash):
    service = create_service()

    request = service.objects().rewrite(
            sourceBucket=bucket, sourceObject=obj,
            destinationBucket=bucket, destinationObject=obj,
            body={})

    # For very large objects, calls to rewrite may not complete on the first
    # call and may need to be resumed.
    while True:
        request.headers.update({
            'x-goog-copy-source-encryption-algorithm': 'AES256',
            'x-goog-copy-source-encryption-key': current_encryption_key,
            'x-goog-copy-source-encryption-key-sha256': current_key_hash,
            'x-goog-encryption-algorithm': 'AES256',
            'x-goog-encryption-key': new_encryption_key,
            'x-goog-encryption-key-sha256': new_key_hash})

        rewrite_response = request.execute()

        if rewrite_response['done']:
            break

        print('Continuing rewrite call...')
        request = service.objects().rewrite(
                source_bucket=bucket, source_object=obj,
                destination_bucket=bucket, destination_object=obj,
                rewriteToken=rewrite_response['rewriteToken'])
        rewrite_response.execute()
Changes the encryption key used to store an existing object.
dataset/ETHPy150Open GoogleCloudPlatform/python-docs-samples/storage/api/customer_supplied_keys.py/rotate_key