Vom Kunden bereitgestellte Verschlüsselungsschlüssel verwenden

Overview

Auf dieser Seite wird beschrieben, wie Sie in Cloud Storage einen eigenen Verschlüsselungsschlüssel verwenden, der als vom Kunden bereitgestellter Verschlüsselungsschlüssel bezeichnet wird. Weitere Verschlüsselungsoptionen in Cloud Storage finden Sie unter Datenverschlüsselungsoptionen.

Eigenen Verschlüsselungsschlüssel erstellen

Es gibt viele Möglichkeiten, einen base64-codierten AES-256-Verschlüsselungsschlüssel zu generieren. Hier sehen Sie einige Beispiele:

C++

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C++ API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

// Create a pseudo-random number generator (PRNG), this is included for
// demonstration purposes only. You should consult your security team about
// best practices to initialize PRNG. In particular, you should verify that
// the C++ library and operating system provide enough entropy to meet the
// security policies in your organization.

// Use the Mersenne-Twister Engine in this example:
//   https://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
// Any C++ PRNG can be used below, the choice is arbitrary.
using GeneratorType = std::mt19937_64;

// Create the default random device to fetch entropy.
std::random_device rd;

// Compute how much entropy we need to initialize the GeneratorType:
constexpr auto kRequiredEntropyWords =
    GeneratorType::state_size *
    (GeneratorType::word_size / std::numeric_limits<unsigned int>::digits);

// Capture the entropy bits into a vector.
std::vector<std::uint64_t> entropy(kRequiredEntropyWords);
std::generate(entropy.begin(), entropy.end(), [&rd] { return rd(); });

// Create the PRNG with the fetched entropy.
std::seed_seq seed(entropy.begin(), entropy.end());

// initialized with enough entropy such that the encryption keys are not
// predictable. Note that the default constructor for all the generators in
// the C++ standard library produce predictable keys.
std::mt19937_64 gen(seed);

namespace gcs = ::google::cloud::storage;
gcs::EncryptionKeyData data = gcs::CreateKeyFromGenerator(gen);

std::cout << "Base64 encoded key = " << data.key << "\n"
          << "Base64 encoded SHA256 of key = " << data.sha256 << "\n";

C#

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C# API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Storage.V1;
using System;

public class GenerateEncryptionKeySample
{
    public string GenerateEncryptionKey()
    {
        var encryptionKey = EncryptionKey.Generate().Base64Key;
        Console.WriteLine($"Generated Base64-encoded AES-256 encryption key: {encryptionKey}");
        return encryptionKey;
    }
}

Go

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"crypto/rand"
	"encoding/base64"
	"fmt"
	"io"
)

// generateEncryptionKey generates a 256 bit (32 byte) AES encryption key and
// prints the base64 representation.
func generateEncryptionKey(w io.Writer) error {
	// This is included for demonstration purposes. You should generate your own
	// key. Please remember that encryption keys should be handled with a
	// comprehensive security policy.
	key := make([]byte, 32)
	if _, err := rand.Read(key); err != nil {
		return fmt.Errorf("rand.Read: %w", err)
	}
	encryptionKey := base64.StdEncoding.EncodeToString(key)
	fmt.Fprintf(w, "Generated base64-encoded encryption key: %v\n", encryptionKey)
	return nil
}

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.common.io.BaseEncoding;
import java.security.SecureRandom;

public class GenerateEncryptionKey {
  /**
   * Generates a 256 bit (32 byte) AES encryption key and prints the base64 representation. This is
   * included for demonstration purposes only. You should generate your own key, and consult your
   * security team about best practices. Please remember that encryption keys should be handled with
   * a comprehensive security policy.
   */
  public static void generateEncryptionKey() {
    byte[] key = new byte[32];
    new SecureRandom().nextBytes(key);
    String encryptionKey = BaseEncoding.base64().encode(key);

    System.out.println("Generated Base64-encoded AES-256 encryption key: " + encryptionKey);
  }
}

Node.js

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

const crypto = require('crypto');

function generateEncryptionKey() {
  /**
   * Generates a 256 bit (32 byte) AES encryption key and prints the base64
   * representation.
   *
   * This is included for demonstration purposes. You should generate your own
   * key. Please remember that encryption keys should be handled with a
   * comprehensive security policy.
   */
  const buffer = crypto.randomBytes(32);
  const encodedKey = buffer.toString('base64');
  console.log(`Base 64 encoded encryption key: ${encodedKey}`);
}
generateEncryptionKey();

PHP

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage PHP API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


/**
 * Generate a base64 encoded encryption key for Google Cloud Storage.
 */
function generate_encryption_key(): void
{
    $key = random_bytes(32);
    $encodedKey = base64_encode($key);
    printf('Your encryption key: %s' . PHP_EOL, $encodedKey);
}

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import base64
import os


def generate_encryption_key():
    """Generates a 256 bit (32 byte) AES encryption key and prints the
    base64 representation.

    This is included for demonstration purposes. You should generate your own
    key. Please remember that encryption keys should be handled with a
    comprehensive security policy.
    """
    key = os.urandom(32)
    encoded_key = base64.b64encode(key).decode("utf-8")

    print(f"Base 64 encoded encryption key: {encoded_key}")

Ruby

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Ruby API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

def generate_encryption_key
  # Generates a 256 bit (32 byte) AES encryption key and prints the base64 representation.
  #
  # This is included for demonstration purposes. You should generate your own key.
  # Please remember that encryption keys should be handled with a comprehensive security policy.
  require "base64"
  require "openssl"

  encryption_key  = OpenSSL::Cipher.new("aes-256-cfb").encrypt.random_key
  encoded_enc_key = Base64.encode64 encryption_key

  puts "Sample encryption key: #{encoded_enc_key}"
end

Mit Ihrem Verschlüsselungsschlüssel hochladen

So laden Sie ein Objekt mit einem vom Kunden bereitgestellten Verschlüsselungsschlüssel hoch:

Console

Die Google Cloud Console kann nicht verwendet werden, um ein Objekt mit einem vom Kunden bereitgestellten Verschlüsselungsschlüssel hochzuladen. Verwenden Sie stattdessen die Google Cloud CLI oder die Clientbibliotheken.

Befehlszeile

Führen Sie den Befehl gcloud storage cp mit dem Flag --encryption-key aus:

gcloud storage cp SOURCE_DATA gs://BUCKET_NAME/OBJECT_NAME --encryption-key=YOUR_ENCRYPTION_KEY

Wobei:

  • SOURCE_DATA ist der Quellspeicherort der zu verschlüsselnden Daten. Dies kann ein beliebiger Quellspeicherort sein, der vom Befehl cp unterstützt wird. Beispiel: eine lokale Datei wie Desktop/dogs.png oder ein anderes Cloud Storage-Objekt wie gs://my-bucket/pets/old-dog.png.
  • BUCKET_NAME ist der Name des Ziel-Buckets für diesen Kopierbefehl. Beispiel: my-bucket.
  • OBJECT_NAME ist der Name des endgültigen, verschlüsselten Objekts. Beispiel: pets/new-dog.png.
  • YOUR_ENCRYPTION_KEY ist der AES-256-Schlüssel, den Sie zum Verschlüsseln des hochgeladenen Objekts verwenden möchten.

Clientbibliotheken

C++

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C++ API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& base64_aes256_key) {
  StatusOr<gcs::ObjectMetadata> object_metadata = client.InsertObject(
      bucket_name, object_name, "top secret",
      gcs::EncryptionKey::FromBase64Key(base64_aes256_key));
  if (!object_metadata) throw std::move(object_metadata).status();

  std::cout << "The object " << object_metadata->name()
            << " was created in bucket " << object_metadata->bucket()
            << "\nFull metadata: " << *object_metadata << "\n";
}

C#

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C# API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class UploadEncryptedFileSample
{
    public void UploadEncryptedFile(
        string key = "3eFsTXPvqi3BpT2ipFCGirslh1Jgc6ikjoAu2oQ5JcI=",
        string bucketName = "your-unique-bucket-name",
        string localPath = "my-local-path/my-file-name",
        string objectName = "my-file-name")
    {
        var storage = StorageClient.Create();
        using var fileStream = File.OpenRead(localPath);
        storage.UploadObject(bucketName, objectName, null, fileStream, new UploadObjectOptions
        {
            EncryptionKey = EncryptionKey.Create(Convert.FromBase64String(key))
        });
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

Go

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// uploadEncryptedFile writes an object using AES-256 encryption key.
func uploadEncryptedFile(w io.Writer, bucket, object string, secretKey []byte) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// secretKey := []byte("secret-key")
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	o := client.Bucket(bucket).Object(object)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to upload is aborted if the
	// object's generation number does not match your precondition.
	// For an object that does not yet exist, set the DoesNotExist precondition.
	o = o.If(storage.Conditions{DoesNotExist: true})
	// If the live object already exists in your bucket, set instead a
	// generation-match precondition using the live object's generation number.
	// attrs, err := o.Attrs(ctx)
	// if err != nil {
	// 	return fmt.Errorf("object.Attrs: %w", err)
	// }
	// o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})

	// Encrypt the object's contents.
	wc := o.Key(secretKey).NewWriter(ctx)
	if _, err := wc.Write([]byte("top secret")); err != nil {
		return fmt.Errorf("Writer.Write: %w", err)
	}
	if err := wc.Close(); err != nil {
		return fmt.Errorf("Writer.Close: %w", err)
	}
	fmt.Fprintf(w, "Uploaded encrypted object %v.\n", object)
	return nil
}

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.BlobInfo;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class UploadEncryptedObject {
  public static void uploadEncryptedObject(
      String projectId, String bucketName, String objectName, String filePath, String encryptionKey)
      throws IOException {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to your file to upload
    // String filePath = "path/to/your/file"

    // The key to encrypt the object with
    // String encryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    BlobInfo blobInfo = BlobInfo.newBuilder(blobId).build();

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request returns a 412 error if the
    // preconditions are not met.
    Storage.BlobTargetOption precondition;
    if (storage.get(bucketName, objectName) == null) {
      // For a target object that does not yet exist, set the DoesNotExist precondition.
      // This will cause the request to fail if the object is created before the request runs.
      precondition = Storage.BlobTargetOption.doesNotExist();
    } else {
      // If the destination already exists in your bucket, instead set a generation-match
      // precondition. This will cause the request to fail if the existing object's generation
      // changes before the request runs.
      precondition =
          Storage.BlobTargetOption.generationMatch(
              storage.get(bucketName, objectName).getGeneration());
    }

    storage.create(
        blobInfo,
        Files.readAllBytes(Paths.get(filePath)),
        Storage.BlobTargetOption.encryptionKey(encryptionKey),
        precondition);

    System.out.println(
        "File "
            + filePath
            + " uploaded to bucket "
            + bucketName
            + " as "
            + objectName
            + " with supplied encryption key");
  }
}

Node.js

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The path to your file to upload
// const filePath = 'path/to/your/file';

// The new ID for your GCS file
// const destFileName = 'your-new-file-name';

// The key to encrypt the object with
// const key = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function uploadEncryptedFile() {
  const options = {
    destination: destFileName,
    encryptionKey: Buffer.from(key, 'base64'),

    // Optional:
    // Set a generation-match precondition to avoid potential race conditions
    // and data corruptions. The request to upload is aborted if the object's
    // generation number does not match your precondition. For a destination
    // object that does not yet exist, set the ifGenerationMatch precondition to 0
    // If the destination object already exists in your bucket, set instead a
    // generation-match precondition using its generation number.
    preconditionOpts: {ifGenerationMatch: generationMatchPrecondition},
  };

  await storage.bucket(bucketName).upload(filePath, options);

  console.log(
    `File ${filePath} uploaded to gs://${bucketName}/${destFileName}`
  );
}

uploadEncryptedFile().catch(console.error);

PHP

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage PHP API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Storage\StorageClient;

/**
 * Upload an encrypted file.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $source The path to the file to upload.
 *        (e.g. '/path/to/your/file')
 * @param string $base64EncryptionKey The base64 encoded encryption key.
 *        (e.g. 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=')
 */
function upload_encrypted_object(string $bucketName, string $objectName, string $source, string $base64EncryptionKey): void
{
    $storage = new StorageClient();
    $file = fopen($source, 'r');
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->upload($file, [
        'name' => $objectName,
        'encryptionKey' => $base64EncryptionKey,
    ]);
    printf('Uploaded encrypted %s to gs://%s/%s' . PHP_EOL,
        basename($source), $bucketName, $objectName);
}

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import base64

from google.cloud import storage


def upload_encrypted_blob(
    bucket_name,
    source_file_name,
    destination_blob_name,
    base64_encryption_key,
):
    """Uploads a file to a Google Cloud Storage bucket using a custom
    encryption key.

    The file will be encrypted by Google Cloud Storage and only
    retrievable using the provided encryption key.
    """
    # bucket_name = "your-bucket-name"
    # source_file_name = "local/path/to/file"
    # destination_blob_name = "storage-object-name"
    # base64_encryption_key = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g="

    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)

    # Encryption key must be an AES256 key represented as a bytestring with
    # 32 bytes. Since it's passed in as a base64 encoded string, it needs
    # to be decoded.
    encryption_key = base64.b64decode(base64_encryption_key)
    blob = bucket.blob(
        destination_blob_name, encryption_key=encryption_key
    )

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to upload is aborted if the object's
    # generation number does not match your precondition. For a destination
    # object that does not yet exist, set the if_generation_match precondition to 0.
    # If the destination object already exists in your bucket, set instead a
    # generation-match precondition using its generation number.
    generation_match_precondition = 0

    blob.upload_from_filename(source_file_name, if_generation_match=generation_match_precondition)

    print(
        f"File {source_file_name} uploaded to {destination_blob_name}."
    )

Ruby

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Ruby API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

def upload_encrypted_file bucket_name:, local_file_path:, file_name: nil, encryption_key:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The path to your file to upload
  # local_file_path = "/local/path/to/file.txt"

  # The ID of your GCS object
  # file_name = "your-file-name"

  # The key to encrypt the object with
  # encryption_key = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g="

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  bucket = storage.bucket bucket_name, skip_lookup: true

  file = bucket.create_file local_file_path, file_name, encryption_key: encryption_key

  puts "Uploaded #{file.name} with encryption key"
end

REST APIs

JSON API

  1. Rufen Sie ein Zugriffstoken für die Autorisierung aus dem OAuth 2.0 Playground ab. Konfigurieren Sie den Playground so, dass Ihre eigenen OAuth-Anmeldedaten verwendet werden. Eine Anleitung finden Sie unter API-Authentifizierung.
  2. Verwenden Sie cURL, um die JSON API mit einer POST-Objektanfrage aufzurufen:

    curl -X POST --data-binary @OBJECT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: OBJECT_CONTENT_TYPE" \
      -H "x-goog-encryption-algorithm: AES256" \
      -H "x-goog-encryption-key: YOUR_ENCRYPTION_KEY" \
      -H "x-goog-encryption-key-sha256: HASH_OF_YOUR_KEY" \
      "https://storage.googleapis.com/upload/storage/v1/b/BUCKET_NAME/o?uploadType=media&name=OBJECT_NAME"

    Dabei gilt:

    • OBJECT ist der Pfad zum Objekt, das Sie hochladen. Beispiel: Desktop/dogs.png.
    • OAUTH2_TOKEN ist das Zugriffstoken, das Sie in Schritt 1 generiert haben.
    • OBJECT_CONTENT_TYPE ist der Inhaltstyp des Objekts. Beispiel: image/png.
    • YOUR_ENCRYPTION_KEY ist der AES-256-Schlüssel, der zum Verschlüsseln des hochgeladenen Objekts verwendet wird.
    • HASH_OF_YOUR_KEY ist der SHA-256-Hash für den AES-256-Schlüssel.
    • BUCKET_NAME ist der Name des Buckets, in den Sie das Objekt hochladen. Beispiel: my-bucket.
    • OBJECT_NAME ist der URL-codierte Name des Objekts, das Sie hochladen. Beispiel: pets/dog.png, URL-codiert als pets%2Fdog.png.

Weitere Informationen zu verschlüsselungsspezifischen Headern finden Sie unter Anfrageheader.

XML API

  1. Rufen Sie ein Zugriffstoken für die Autorisierung aus dem OAuth 2.0 Playground ab. Konfigurieren Sie den Playground so, dass Ihre eigenen OAuth-Anmeldedaten verwendet werden. Eine Anleitung finden Sie unter API-Authentifizierung.
  2. Verwenden Sie cURL, um die XML API mit einer PUT-Objektanfrage aufzurufen:

    curl -X -i PUT --data-binary @OBJECT \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Type: OBJECT_CONTENT_TYPE" \
      -H "x-goog-encryption-algorithm: AES256" \
      -H "x-goog-encryption-key: YOUR_ENCRYPTION_KEY" \
      -H "x-goog-encryption-key-sha256: HASH_OF_YOUR_KEY" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Hierbei gilt:

    • OBJECT ist der Pfad zum Objekt, das Sie hochladen. Beispiel: Desktop/dogs.png.
    • OAUTH2_TOKEN ist das Zugriffstoken, das Sie in Schritt 1 generiert haben.
    • OBJECT_CONTENT_TYPE ist der Inhaltstyp des Objekts. Beispiel: image/png.
    • YOUR_ENCRYPTION_KEY ist der AES-256-Schlüssel, der zum Verschlüsseln des hochgeladenen Objekts verwendet wird.
    • HASH_OF_YOUR_KEY ist der SHA-256-Hash für den AES-256-Schlüssel.
    • BUCKET_NAME ist der Name des Buckets, in den Sie das Objekt hochladen. Beispiel: my-bucket.
    • OBJECT_NAME ist der URL-codierte Name des Objekts, das Sie hochladen. Beispiel: pets/dog.png, URL-codiert als pets%2Fdog.png.

Weitere Informationen zu verschlüsselungsspezifischen Headern finden Sie unter Anfrageheader.

Verschlüsselte Objekte herunterladen

So laden Sie ein in Cloud Storage gespeichertes Objekt herunter, das mit einem vom Kunden bereitgestellten Verschlüsselungsschlüssel verschlüsselt ist:

Console

Die Google Cloud Console kann nicht zum Herunterladen von Objekten verwendet werden, die mit vom Kunden bereitgestellten Verschlüsselungsschlüsseln verschlüsselt wurden. Verwenden Sie stattdessen die Google Cloud CLI oder die Clientbibliotheken.

Befehlszeile

Führen Sie den Befehl gcloud storage cp mit dem Flag --decryption-keys aus:

gcloud storage cp gs://BUCKET_NAME/OBJECT_NAME OBJECT_DESTINATION --decryption-keys=YOUR_ENCRYPTION_KEY

Wobei:

  • BUCKET_NAME ist der Name des Buckets mit dem Objekt, das Sie herunterladen. Beispiel: my-bucket.
  • OBJECT_NAME ist der Name des Objekts, das Sie herunterladen. Beispiel: pets/dog.png.
  • OBJECT_DESTINATION ist der Standort, an dem Sie Ihr Objekt speichern möchten. Beispiel: Desktop.
  • YOUR_ENCRYPTION_KEY ist der AES-256-Schlüssel, der zum Verschlüsseln des Objekts beim Hochladen verwendet wird.

Clientbibliotheken

C++

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C++ API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

namespace gcs = ::google::cloud::storage;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& base64_aes256_key) {
  gcs::ObjectReadStream stream =
      client.ReadObject(bucket_name, object_name,
                        gcs::EncryptionKey::FromBase64Key(base64_aes256_key));

  std::string data(std::istreambuf_iterator<char>{stream}, {});
  if (stream.bad()) throw google::cloud::Status(stream.status());
  std::cout << "The object contents are: " << data << "\n";
}

C#

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C# API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class DownloadEncryptedFileSample
{
    public void DownloadEncryptedFile(
        string key = "3eFsTXPvqi3BpT2ipFCGirslh1Jgc6ikjoAu2oQ5JcI=",
        string bucketName = "your-unique-bucket-name",
        string objectName = "my-file-name",
        string localPath = "my-local-path/my-file-name")
    {
        var storage = StorageClient.Create();
        using var outputFile = File.OpenWrite(localPath);
        storage.DownloadObject(bucketName, objectName, outputFile, new DownloadObjectOptions
        {
            EncryptionKey = EncryptionKey.Create(Convert.FromBase64String(key))
        });
        Console.WriteLine($"Downloaded {objectName} to {localPath}.");
    }
}

Go

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"
	"io/ioutil"
	"time"

	"cloud.google.com/go/storage"
)

// downloadEncryptedFile reads an encrypted object.
func downloadEncryptedFile(w io.Writer, bucket, object string, secretKey []byte) ([]byte, error) {
	// bucket := "bucket-name"
	// object := "object-name"
	// key := []byte("secret-encryption-key")
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return nil, fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	obj := client.Bucket(bucket).Object(object)

	ctx, cancel := context.WithTimeout(ctx, time.Second*50)
	defer cancel()

	rc, err := obj.Key(secretKey).NewReader(ctx)
	if err != nil {
		return nil, fmt.Errorf("Object(%q).Key(%q).NewReader: %w", object, secretKey, err)
	}
	defer rc.Close()

	data, err := ioutil.ReadAll(rc)
	if err != nil {
		return nil, fmt.Errorf("ioutil.ReadAll: %w", err)
	}
	fmt.Fprintf(w, "File %v downloaded with encryption key.\n", object)
	return data, nil
}

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


import com.google.cloud.storage.Blob;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;
import java.io.IOException;
import java.nio.file.Path;

public class DownloadEncryptedObject {
  public static void downloadEncryptedObject(
      String projectId,
      String bucketName,
      String objectName,
      Path destFilePath,
      String decryptionKey)
      throws IOException {

    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The path to which the file should be downloaded
    // Path destFilePath = Paths.get("/local/path/to/file.txt");

    // The Base64 encoded decryption key, which should be the same key originally used to encrypt
    // the object
    // String decryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=";

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();

    Blob blob = storage.get(bucketName, objectName);
    blob.downloadTo(destFilePath, Blob.BlobSourceOption.decryptionKey(decryptionKey));

    System.out.println(
        "Downloaded object "
            + objectName
            + " from bucket name "
            + bucketName
            + " to "
            + destFilePath
            + " using customer-supplied encryption key");
  }
}

Node.js

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const srcFileName = 'your-file-name';

// The path to which the file should be downloaded
// const destFileName = '/local/path/to/file.txt';

// The Base64 encoded decryption key, which should be the same key originally
// used to encrypt the file
// const encryptionKey = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function downloadEncryptedFile() {
  const options = {
    destination: destFileName,
  };

  // Decrypts and downloads the file. This can only be done with the key used
  // to encrypt and upload the file.
  await storage
    .bucket(bucketName)
    .file(srcFileName)
    .setEncryptionKey(Buffer.from(encryptionKey, 'base64'))
    .download(options);

  console.log(`File ${srcFileName} downloaded to ${destFileName}`);
}

downloadEncryptedFile().catch(console.error);

PHP

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage PHP API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Storage\StorageClient;

/**
 * Download an encrypted file
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $destination The local destination to save the encrypted file.
 *        (e.g. '/path/to/your/file')
 * @param string $base64EncryptionKey The base64 encoded encryption key. Should
 *        (e.g. 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=')
 *     be the same key originally used to encrypt the object.
 */
function download_encrypted_object(string $bucketName, string $objectName, string $destination, string $base64EncryptionKey): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);
    $object = $bucket->object($objectName);
    $object->downloadToFile($destination, [
        'encryptionKey' => $base64EncryptionKey,
    ]);
    printf('Encrypted object gs://%s/%s downloaded to %s' . PHP_EOL,
        $bucketName, $objectName, basename($destination));
}

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import base64

from google.cloud import storage


def download_encrypted_blob(
    bucket_name,
    source_blob_name,
    destination_file_name,
    base64_encryption_key,
):
    """Downloads a previously-encrypted blob from Google Cloud Storage.

    The encryption key provided must be the same key provided when uploading
    the blob.
    """
    # bucket_name = "your-bucket-name"
    # source_blob_name = "storage-object-name"
    # destination_file_name = "local/path/to/file"
    # base64_encryption_key = "base64-encoded-encryption-key"

    storage_client = storage.Client()

    bucket = storage_client.bucket(bucket_name)

    # Encryption key must be an AES256 key represented as a bytestring with
    # 32 bytes. Since it's passed in as a base64 encoded string, it needs
    # to be decoded.
    encryption_key = base64.b64decode(base64_encryption_key)
    blob = bucket.blob(source_blob_name, encryption_key=encryption_key)

    blob.download_to_filename(destination_file_name)

    print(
        f"Blob {source_blob_name} downloaded to {destination_file_name}."
    )

Ruby

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Ruby API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

def download_encrypted_file bucket_name:, file_name:, local_file_path:, encryption_key:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  # The path to which the file should be downloaded
  # local_file_path = "/local/path/to/file.txt"

  # The Base64 encoded decryption key, which should be the same key originally used to encrypt the object
  # encryption_key = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g="

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  bucket = storage.bucket bucket_name, skip_lookup: true

  file = bucket.file file_name, encryption_key: encryption_key
  file.download local_file_path, encryption_key: encryption_key

  puts "Downloaded encrypted #{file.name} to #{local_file_path}"
end

REST APIs

JSON API

  1. Rufen Sie ein Zugriffstoken für die Autorisierung aus dem OAuth 2.0 Playground ab. Konfigurieren Sie den Playground so, dass Ihre eigenen OAuth-Anmeldedaten verwendet werden. Eine Anleitung finden Sie unter API-Authentifizierung.
  2. Verwenden Sie cURL, um die JSON API mit einer GET-Objektanfrage aufzurufen:

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-encryption-algorithm: AES256" \
      -H "x-goog-encryption-key: YOUR_ENCRYPTION_KEY" \
      -H "x-goog-encryption-key-sha256: HASH_OF_YOUR_KEY" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME?alt=media"

    Wobei:

    • OAUTH2_TOKEN ist das Zugriffstoken, das Sie in Schritt 1 generiert haben.
    • YOUR_ENCRYPTION_KEY ist der AES-256-Schlüssel, den Sie zum Verschlüsseln des Objekts verwendet haben.
    • HASH_OF_YOUR_KEY ist der SHA-256-Hash für den AES-256-Schlüssel.
    • SAVE_TO_LOCATION ist der Standort, an dem Sie Ihr Objekt speichern möchten. Beispiel: Desktop/dog.png.
    • BUCKET_NAME ist der Name des Buckets, von dem Sie das Objekt herunterladen. Beispiel: my-bucket.
    • OBJECT_NAME ist der URL-codierte Name des Objekts, das Sie herunterladen. Beispiel: pets/dog.png, URL-codiert als pets%2Fdog.png.

Weitere Informationen zu verschlüsselungsspezifischen Headern finden Sie unter Anfrageheader.

XML API

  1. Rufen Sie ein Zugriffstoken für die Autorisierung aus dem OAuth 2.0 Playground ab. Konfigurieren Sie den Playground so, dass Ihre eigenen OAuth-Anmeldedaten verwendet werden. Eine Anleitung finden Sie unter API-Authentifizierung.
  2. Verwenden Sie cURL, um die XML API mit einer GET-Objektanfrage aufzurufen:

    curl -X GET \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "x-goog-encryption-algorithm: AES256" \
      -H "x-goog-encryption-key: YOUR_ENCRYPTION_KEY" \
      -H "x-goog-encryption-key-sha256: HASH_OF_YOUR_KEY" \
      -o "SAVE_TO_LOCATION" \
      "https://storage.googleapis.com/BUCKET_NAME/OBJECT_NAME"

    Hierbei gilt:

    • OAUTH2_TOKEN ist das Zugriffstoken, das Sie in Schritt 1 generiert haben.
    • YOUR_ENCRYPTION_KEY ist der AES-256-Schlüssel, den Sie zum Verschlüsseln des Objekts verwendet haben.
    • HASH_OF_YOUR_KEY ist der SHA-256-Hash für den AES-256-Schlüssel.
    • SAVE_TO_LOCATION ist der Standort, an dem Sie Ihr Objekt speichern möchten. Beispiel: Desktop/dog.png.
    • BUCKET_NAME ist der Name des Buckets, von dem Sie das Objekt herunterladen. Beispiel: my-bucket.
    • OBJECT_NAME ist der URL-codierte Name des Objekts, das Sie herunterladen. Beispiel: pets/dog.png, URL-codiert als pets%2Fdog.png.

Weitere Informationen zu verschlüsselungsspezifischen Headern finden Sie unter Anfrageheader.

Verschlüsselungsschlüssel rotieren

So rotieren Sie einen vom Kunden bereitgestellten Verschlüsselungsschlüssel:

Console

Die Google Cloud Console kann nicht zum Rotieren von vom Kunden bereitgestellten Verschlüsselungsschlüsseln verwendet werden. Verwenden Sie stattdessen die Google Cloud CLI oder die Clientbibliotheken.

Befehlszeile

Verwenden Sie den gcloud storage objects update-Befehl mit den entsprechenden Flags:

gcloud storage objects update gs://BUCKET_NAME/OBJECT_NAME --encryption-key=NEW_KEY --decryption-keys=OLD_KEY

Wobei:

  • BUCKET_NAME ist der Name des Buckets, der das Objekt enthält, dessen Schlüssel Sie rotieren. Beispiel: my-bucket
  • OBJECT_NAME ist der Name des Objekts, dessen Schlüssel Sie rotieren. Beispiel: pets/dog.png.
  • NEW_KEY ist der neue vom Kunden bereitgestellte Verschlüsselungsschlüssel, mit dem Sie das Objekt verschlüsseln möchten.
  • OLD_KEY ist der aktuelle vom Kunden bereitgestellte Verschlüsselungsschlüssel, mit dem das Objekt verschlüsselt wird.

Clientbibliotheken

C++

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C++ API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name,
   std::string const& object_name, std::string const& old_key_base64,
   std::string const& new_key_base64) {
  StatusOr<gcs::ObjectMetadata> object_metadata =
      client.RewriteObjectBlocking(
          bucket_name, object_name, bucket_name, object_name,
          gcs::SourceEncryptionKey::FromBase64Key(old_key_base64),
          gcs::EncryptionKey::FromBase64Key(new_key_base64));
  if (!object_metadata) throw std::move(object_metadata).status();

  std::cout << "Rotated key on object " << object_metadata->name()
            << " in bucket " << object_metadata->bucket()
            << "\nFull Metadata: " << *object_metadata << "\n";
}

C#

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage C# API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.


using Google.Cloud.Storage.V1;
using System;
using System.IO;

public class ObjectRotateEncryptionKeySample
{
    public void ObjectRotateEncryptionKey(
        string bucketName = "your-unique-bucket-name",
        string objectName = "your-object-name",
        string currrentEncryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=",
        string newEncryptionKey = "ARbt/judaq+VmtXzAsc83J4z5kFmWJ6NdAPQuleuB7g=")
    {
        var storage = StorageClient.Create();

        using var outputStream = new MemoryStream();
        storage.DownloadObject(bucketName, objectName, outputStream, new DownloadObjectOptions()
        {
            EncryptionKey = EncryptionKey.Create(Convert.FromBase64String(currrentEncryptionKey))
        });

        outputStream.Position = 0;

        storage.UploadObject(bucketName, objectName, null, outputStream, new UploadObjectOptions()
        {
            EncryptionKey = EncryptionKey.Create(Convert.FromBase64String(newEncryptionKey))
        });

        Console.WriteLine($"Rotated encryption key for object  {objectName} in bucket {bucketName}");
    }
}

Go

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Go API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import (
	"context"
	"fmt"
	"io"
	"time"

	"cloud.google.com/go/storage"
)

// rotateEncryptionKey encrypts an object with the newKey.
func rotateEncryptionKey(w io.Writer, bucket, object string, key, newKey []byte) error {
	// bucket := "bucket-name"
	// object := "object-name"
	// key := []byte("encryption-key")
	// newKey := []byte("new-encryption-key")
	ctx := context.Background()
	client, err := storage.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("storage.NewClient: %w", err)
	}
	defer client.Close()

	ctx, cancel := context.WithTimeout(ctx, time.Second*10)
	defer cancel()

	o := client.Bucket(bucket).Object(object)

	// Optional: set a generation-match precondition to avoid potential race
	// conditions and data corruptions. The request to copy is aborted if the
	// object's generation number does not match your precondition.
	attrs, err := o.Attrs(ctx)
	if err != nil {
		return fmt.Errorf("object.Attrs: %w", err)
	}
	o = o.If(storage.Conditions{GenerationMatch: attrs.Generation})

	// You can't change an object's encryption key directly, you must rewrite the
	// object using the new key.
	_, err = o.Key(newKey).CopierFrom(o.Key(key)).Run(ctx)
	if err != nil {
		return fmt.Errorf("Key(%q).CopierFrom(%q).Run: %w", newKey, key, err)
	}
	fmt.Fprintf(w, "Key rotation complete for blob %v.\n", object)
	return nil
}

Java

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Java API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import com.google.cloud.storage.Blob;
import com.google.cloud.storage.BlobId;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class RotateObjectEncryptionKey {
  public static void rotateObjectEncryptionKey(
      String projectId,
      String bucketName,
      String objectName,
      String oldEncryptionKey,
      String newEncryptionKey) {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket
    // String bucketName = "your-unique-bucket-name";

    // The ID of your GCS object
    // String objectName = "your-object-name";

    // The Base64 encoded AES-256 encryption key originally used to encrypt the object. See the
    // documentation
    // on Customer-Supplied Encryption keys for more info:
    // https://cloud.google.com/storage/docs/encryption/using-customer-supplied-keys
    // String oldEncryptionKey = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g="

    // The new encryption key to use
    // String newEncryptionKey = "0mMWhFvQOdS4AmxRpo8SJxXn5MjFhbz7DkKBUdUIef8="

    Storage storage = StorageOptions.newBuilder().setProjectId(projectId).build().getService();
    BlobId blobId = BlobId.of(bucketName, objectName);
    Blob blob = storage.get(blobId);
    if (blob == null) {
      System.out.println("The object " + objectName + " wasn't found in " + bucketName);
      return;
    }

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request to upload returns a 412 error if
    // the object's generation number does not match your precondition.
    Storage.BlobSourceOption precondition =
        Storage.BlobSourceOption.generationMatch(blob.getGeneration());

    // You can't change an object's encryption key directly, the only way is to overwrite the object
    Storage.CopyRequest request =
        Storage.CopyRequest.newBuilder()
            .setSource(blobId)
            .setSourceOptions(
                Storage.BlobSourceOption.decryptionKey(oldEncryptionKey), precondition)
            .setTarget(blobId, Storage.BlobTargetOption.encryptionKey(newEncryptionKey))
            .build();
    storage.copy(request);

    System.out.println(
        "Rotated encryption key for object " + objectName + "in bucket " + bucketName);
  }
}

Node.js

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Node.js API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// The ID of your GCS bucket
// const bucketName = 'your-unique-bucket-name';

// The ID of your GCS file
// const fileName = 'your-file-name';

// The Base64 encoded AES-256 encryption key originally used to encrypt the
// object. See the documentation on Customer-Supplied Encryption keys for
// more info:
// https://cloud.google.com/storage/docs/encryption/using-customer-supplied-keys
// The Base64 encoded AES-256 encryption key originally used to encrypt the
// const oldKey = 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=';

// The new encryption key to use
// const newKey = '0mMWhFvQOdS4AmxRpo8SJxXn5MjFhbz7DkKBUdUIef8=';

// Imports the Google Cloud client library
const {Storage} = require('@google-cloud/storage');

// Creates a client
const storage = new Storage();

async function rotateEncryptionKey() {
  const rotateEncryptionKeyOptions = {
    encryptionKey: Buffer.from(newKey, 'base64'),

    // Optional: set a generation-match precondition to avoid potential race
    // conditions and data corruptions. The request to copy is aborted if the
    // object's generation number does not match your precondition.
    preconditionOpts: {
      ifGenerationMatch: generationMatchPrecondition,
    },
  };
  await storage
    .bucket(bucketName)
    .file(fileName, {
      encryptionKey: Buffer.from(oldKey, 'base64'),
    })
    .rotateEncryptionKey({
      rotateEncryptionKeyOptions,
    });

  console.log('Encryption key rotated successfully');
}

rotateEncryptionKey().catch(console.error);

PHP

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage PHP API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

use Google\Cloud\Storage\StorageClient;

/**
 * Change the encryption key used to store an existing object.
 *
 * @param string $bucketName The name of your Cloud Storage bucket.
 *        (e.g. 'my-bucket')
 * @param string $objectName The name of your Cloud Storage object.
 *        (e.g. 'my-object')
 * @param string $oldBase64EncryptionKey The Base64 encoded AES-256 encryption
 *     key originally used to encrypt the object. See the documentation on
 *     Customer-Supplied Encryption keys for more info:
 *     https://cloud.google.com/storage/docs/encryption/using-customer-supplied-keys
 *        (e.g. 'TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g=')
 * @param string $newBase64EncryptionKey The new base64 encoded encryption key.
 *        (e.g. '0mMWhFvQOdS4AmxRpo8SJxXn5MjFhbz7DkKBUdUIef8=')
 */
function rotate_encryption_key(
    string $bucketName,
    string $objectName,
    string $oldBase64EncryptionKey,
    string $newBase64EncryptionKey
): void {
    $storage = new StorageClient();
    $object = $storage->bucket($bucketName)->object($objectName);

    $rewrittenObject = $object->rewrite($bucketName, [
        'encryptionKey' => $oldBase64EncryptionKey,
        'destinationEncryptionKey' => $newBase64EncryptionKey,
    ]);

    printf('Rotated encryption key for object gs://%s/%s' . PHP_EOL,
        $bucketName, $objectName);
}

Python

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Python API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

import base64

from google.cloud import storage


def rotate_encryption_key(
    bucket_name, blob_name, base64_encryption_key, base64_new_encryption_key
):
    """Performs a key rotation by re-writing an encrypted blob with a new
    encryption key."""
    storage_client = storage.Client()
    bucket = storage_client.bucket(bucket_name)
    current_encryption_key = base64.b64decode(base64_encryption_key)
    new_encryption_key = base64.b64decode(base64_new_encryption_key)

    # Both source_blob and destination_blob refer to the same storage object,
    # but destination_blob has the new encryption key.
    source_blob = bucket.blob(
        blob_name, encryption_key=current_encryption_key
    )
    destination_blob = bucket.blob(
        blob_name, encryption_key=new_encryption_key
    )
    generation_match_precondition = None
    token = None

    # Optional: set a generation-match precondition to avoid potential race conditions
    # and data corruptions. The request to rewrite is aborted if the object's
    # generation number does not match your precondition.
    source_blob.reload()  # Fetch blob metadata to use in generation_match_precondition.
    generation_match_precondition = source_blob.generation

    while True:
        token, bytes_rewritten, total_bytes = destination_blob.rewrite(
            source_blob, token=token, if_generation_match=generation_match_precondition
        )
        if token is None:
            break

    print(f"Key rotation complete for Blob {blob_name}")

Ruby

Weitere Informationen finden Sie in der Referenzdokumentation zur Cloud Storage Ruby API.

Richten Sie die Standardanmeldedaten für Anwendungen ein, um sich bei Cloud Storage zu authentifizieren. Weitere Informationen finden Sie unter Authentifizierung für eine lokale Entwicklungsumgebung einrichten.

def rotate_encryption_key bucket_name:, file_name:, current_encryption_key:, new_encryption_key:
  # The ID of your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  # The ID of your GCS object
  # file_name = "your-file-name"

  # The Base64 encoded AES-256 encryption key originally used to encrypt the object.
  # See the documentation on Customer-Supplied Encryption keys for more info:
  # https://cloud.google.com/storage/docs/encryption/using-customer-supplied-keys
  # current_encryption_key = "TIbv/fjexq+VmtXzAlc63J4z5kFmWJ6NdAPQulQBT7g="

  # The new encryption key to use
  # new_encryption_key = "0mMWhFvQOdS4AmxRpo8SJxXn5MjFhbz7DkKBUdUIef8="

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new
  bucket  = storage.bucket bucket_name, skip_lookup: true
  file    = bucket.file file_name, encryption_key: current_encryption_key

  file.rotate encryption_key:     current_encryption_key,
              new_encryption_key: new_encryption_key

  puts "The encryption key for #{file.name} in #{bucket.name} was rotated."
end

REST APIs

JSON API

  1. Rufen Sie ein Zugriffstoken für die Autorisierung aus dem OAuth 2.0 Playground ab. Konfigurieren Sie den Playground so, dass Ihre eigenen OAuth-Anmeldedaten verwendet werden. Eine Anleitung finden Sie unter API-Authentifizierung.
  2. Verwenden Sie cURL, um die JSON API mit einer POST-Objektanfrage aufzurufen:

    curl -X POST \
      -H "Authorization: Bearer OAUTH2_TOKEN" \
      -H "Content-Length: 0" \
      -H "x-goog-encryption-algorithm: AES256" \
      -H "x-goog-encryption-key: NEW_ENCRYPTION_KEY" \
      -H "x-goog-encryption-key-sha256: HASH_OF_NEW_KEY" \
      -H "x-goog-copy-source-encryption-algorithm: AES256" \
      -H "x-goog-copy-source-encryption-key: OLD_ENCRYPTION_KEY" \
      -H "x-goog-copy-source-encryption-key-sha256: HASH_OF_OLD_KEY" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME/o/OBJECT_NAME/rewriteTo/b/BUCKET_NAME/o/OBJECT_NAME"

    Wobei:

    • OAUTH2_TOKEN ist das Zugriffstoken, das Sie in Schritt 1 generiert haben.
    • NEW_ENCRYPTION_KEY ist der neue AES-256-Schlüssel, der zum Verschlüsseln des Objekts verwendet wird.
    • HASH_OF_NEW_KEY ist der SHA-256-Hash für den neuen AES-256-Schlüssel.
    • OLD_ENCRYPTION_KEY ist der aktuelle AES-256-Schlüssel, der zum Verschlüsseln des Objekts verwendet wird.
    • HASH_OF_OLD_KEY ist der aktuelle SHA-256-Hash für den AES-256-Schlüssel.
    • BUCKET_NAME ist der Name des Buckets, der das relevante Objekt enthält. Beispiel: my-bucket.
    • OBJECT_NAME ist der URL-codierte Name des Objekts, dessen Schlüssel Sie rotieren. Beispiel: pets/dog.png, URL-codiert als pets%2Fdog.png.

Weitere Informationen zu verschlüsselungsspezifischen Headern finden Sie unter Anfrageheader.

XML API

Die XML API unterstützt die Rotation eines vom Kunden bereitgestellten Verschlüsselungsschlüssels durch das Umschreiben von Objekten nicht. So wenden Sie einen neuen vom Kunden bereitgestellten Schlüssel mithilfe der XML API auf ein Objekt an:

  1. Laden Sie das vorhandene Objekt herunter.
  2. Laden Sie das Objekt mit einem neuen Schlüssel noch einmal hoch.

Nächste Schritte