使用客户提供的加密密钥

转到概念

本页面介绍如何将自己的加密密钥(称为 CSEK)用于 Cloud Storage。如需了解 Cloud Storage 中的其他加密选项,请参阅数据加密选项

生成您自己的加密密钥

您可以通过许多方法来生成 Base64 编码的 AES-256 加密密钥。以下是一些示例:

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

// 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#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

void GenerateEncryptionKey()
{
    Console.Write(EncryptionKey.Generate().Base64Key);
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

import com.google.common.io.BaseEncoding;
import java.util.Random;

public class GenerateEncryptionKey {
  public static void generateEncryptionKey() {
    byte[] key = new byte[32];
    new Random().nextBytes(key);
    String encryptionKey = BaseEncoding.base64().encode(key);

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

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档


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.
   *
   */
  try {
    const buffer = crypto.randomBytes(32);
    const encodedKey = buffer.toString('base64');
    console.log(`Base 64 encoded encryption key: ${encodedKey}`);

    return encodedKey;
  } catch (err) {
    console.error(err);
  }
}
generateEncryptionKey();

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档


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

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

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("Base 64 encoded encryption key: {}".format(encoded_key))

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

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}"

使用加密密钥执行上传

要使用客户提供的加密密钥上传对象,请执行以下操作:

gsutil

  1. 将以下选项添加到 boto 配置文件[GSUtil] 部分:

    encryption_key = YOUR_ENCRYPTION_KEY

    其中 YOUR_ENCRYPTION_KEY 是用于加密对象的 AES-256 加密密钥

  2. 使用 gsutil cp 命令:

    gsutil cp LOCAL_OBJECT_LOCATION gs://DESTINATION_BUCKET_NAME

    其中:

    • LOCAL_OBJECT_LOCATION 是要上传的对象的路径,例如 Desktop/dogs.png
    • DESTINATION_BUCKET_NAME 是对象要上传到的目标存储分区的名称。例如 my-bucket

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

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::runtime_error(object_metadata.status().message());
  }

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

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

private void UploadEncryptedFile(string key, string bucketName,
    string localPath, string objectName = null)
{
    var storage = StorageClient.Create();
    using (var f = File.OpenRead(localPath))
    {
        objectName = objectName ?? Path.GetFileName(localPath);
        storage.UploadObject(bucketName, objectName, null, f,
            new UploadObjectOptions()
            {
                EncryptionKey = EncryptionKey.Create(
                Convert.FromBase64String(key))
            });
        Console.WriteLine($"Uploaded {objectName}.");
    }
}

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

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: %v", err)
	}
	defer client.Close()

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

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

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

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

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();
    storage.create(
        blobInfo,
        Files.readAllBytes(Paths.get(filePath)),
        Storage.BlobTargetOption.encryptionKey(encryptionKey));

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

Node.js

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const srcFilename = 'Local file to upload, e.g. ./local/path/to/file.txt';
// const destFilename = 'Remote destination for file, e.g. file_encrypted.txt';

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

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

async function uploadEncryptedFile() {
  const options = {
    // The path to which the file should be uploaded, e.g. "file_encrypted.txt"
    destination: destFilename,
    // Encrypt the file with a customer-supplied key.
    // See the "Generating your own encryption key" section above.
    encryptionKey: Buffer.from(key, 'base64'),
  };

  // Encrypts and uploads a local file, e.g. "./local/path/to/file.txt".
  // The file will only be retrievable using the key used to upload it.
  await storage.bucket(bucketName).upload(srcFilename, options);

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

uploadEncryptedFile().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Upload an encrypted file.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 * @param resource $source the path to the file to upload.
 * @param string $base64EncryptionKey the base64 encoded encryption key.
 *
 * @return void
 */
function upload_encrypted_object($bucketName, $objectName, $source, $base64EncryptionKey)
{
    $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

如需了解详情,请参阅 Cloud Storage Python API 参考文档

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.
    """

    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
    )

    blob.upload_from_filename(source_file_name)

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

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name       = "Your Google Cloud Storage bucket name"
# local_file_path   = "Path to local file to upload"
# storage_file_path = "Path to store the file in Google Cloud Storage"
# encryption_key    = "AES-256 encryption key"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new

bucket = storage.bucket bucket_name

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

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

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 POST Object 请求调用 JSON API

    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"

    其中:

    • OBJECT 是要上传的对象的路径,例如 Desktop/dogs.png
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • OBJECT_CONTENT_TYPE 是该对象的内容类型,例如 image/png
    • YOUR_ENCRYPTION_KEY 是用于加密上传对象的 AES-256 密钥
    • HASH_OF_YOUR_KEY 是 AES-256 密钥的 SHA-256 哈希值。
    • BUCKET_NAME 是对象要上传到的目标存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是要上传的对象的名称,例如 pets/dogs.png

如需详细了解特定于加密的标头,请参阅加密请求标头

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 PUT OBJECT 请求调用 XML API

    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"

    其中:

    • OBJECT 是要上传的对象的路径,例如 Desktop/dogs.png
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • OBJECT_CONTENT_TYPE 是该对象的内容类型,例如 image/png
    • YOUR_ENCRYPTION_KEY 是用于加密上传对象的 AES-256 密钥
    • HASH_OF_YOUR_KEY 是 AES-256 密钥的 SHA-256 哈希值。
    • BUCKET_NAME 是对象要上传到的目标存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是要上传的对象的名称,例如 pets/dogs.png

如需详细了解特定于加密的标头,请参阅加密请求标头

下载已加密的对象

要下载存储在 Cloud Storage 中的加密对象(使用客户提供的加密密钥加密),请执行以下操作:

gsutil

  1. 将以下选项添加到 boto 配置文件[GSUtil] 部分:

    decryption_key1 = YOUR_ENCRYPTION_KEY

    其中,YOUR_ENCRYPTION_KEY 是上传对象时用于加密对象的密钥。

  2. 使用 gsutil cp 命令:

    gsutil cp gs://BUCKET_NAME/OBJECT_NAME OBJECT_DESTINATION

    其中:

    • BUCKET_NAME 是包含要下载的对象的存储分区名称,例如 my-bucket
    • OBJECT_NAME 是要下载的对象的名称。例如 pets/dog.png
    • OBJECT_DESTINATION 是您要保存您的对象的位置。例如 Desktop

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

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}, {});
  std::cout << "The object contents are: " << data << "\n";
}

C#

如需了解详情,请参阅 Cloud Storage C# API 参考文档

private void DownloadEncryptedObject(string key, string bucketName,
    string objectName, string localPath = null)
{
    var storage = StorageClient.Create();
    localPath = localPath ?? Path.GetFileName(objectName);
    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

如需了解详情,请参阅 Cloud Storage Go API 参考文档

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: %v", 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: %v", object, secretKey, err)
	}
	defer rc.Close()

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

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

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

如需了解详情,请参阅 Cloud Storage Node.js API 参考文档

/**
 * TODO(developer): Uncomment the following lines before running the sample.
 */
// const bucketName = 'Name of a bucket, e.g. my-bucket';
// const srcFilename = 'File to download, e.g. file_encrypted.txt';
// const destFilename = 'Local destination for file, e.g. ./file.txt';

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

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

async function downloadEncryptedFile() {
  const options = {
    // The path to which the file should be downloaded, e.g. "./file.txt"
    destination: destFilename,
  };

  // Descrypts 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(key, 'base64'))
    .download(options);

  console.log(`File ${srcFilename} downloaded to ${destFilename}.`);
}

downloadEncryptedFile().catch(console.error);

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Download an encrypted file
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 * @param string $destination the local destination to save the encrypted file.
 * @param string $base64EncryptionKey the base64 encoded encryption key.
 *
 * @return void
 */
function download_encrypted_object($bucketName, $objectName, $destination, $base64EncryptionKey)
{
    $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

如需了解详情,请参阅 Cloud Storage Python API 参考文档

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(
        "Blob {} downloaded to {}.".format(
            source_blob_name, destination_file_name
        )
    )

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name    = "Your Google Cloud Storage bucket name"
# file_name      = "Name of file in Google Cloud Storage to download locally"
# local_path     = "Destination path for downloaded file"
# encryption_key = "AES-256 encryption key"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new

bucket = storage.bucket bucket_name

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

puts "Downloaded encrypted #{file.name}"

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET Object 请求调用 JSON API

    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"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • YOUR_ENCRYPTION_KEY 是您用于加密对象的 AES-256 密钥
    • HASH_OF_YOUR_KEY 是 AES-256 密钥的 SHA-256 哈希值。
    • SAVE_TO_LOCATION 是您要保存您的对象的位置。例如 Desktop/dog.png
    • BUCKET_NAME 是您要从中下载对象的存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是要下载的对象的名称。例如 pets/dogs.png

如需详细了解特定于加密的标头,请参阅加密请求标头

XML API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 GET OBJECT 请求调用 XML API

    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"

    其中:

    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • YOUR_ENCRYPTION_KEY 是您用于加密对象的 AES-256 密钥
    • HASH_OF_YOUR_KEY 是 AES-256 密钥的 SHA-256 哈希值。
    • SAVE_TO_LOCATION 是您要保存您的对象的位置。例如 Desktop/dog.png
    • BUCKET_NAME 是您要从中下载对象的存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是要下载的对象的名称。例如 pets/dogs.png

如需详细了解特定于加密的标头,请参阅加密请求标头

轮替加密密钥

要轮替客户提供的加密密钥,请执行以下操作:

gsutil

  1. 将以下选项添加到 boto 配置文件[GSUtil] 部分:

    encryption_key = NEW_ENCRYPTION_KEY
    decryption_key1 = OLD_ENCRYPTION_KEY

    其中:

    • NEW_ENCRYPTION_KEY 是对象的新加密密钥。
    • OLD_ENCRYPTION_KEY 是对象的当前加密密钥。
  2. 使用带有 -k 标志的 gsutil rewrite 命令:

    gsutil rewrite -k gs://BUCKET_NAME/OBJECT_NAME

    其中:

    • BUCKET_NAME 是包含相关对象的存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是相关对象的名称,例如 pets/dog.png

代码示例

C++

如需了解详情,请参阅 Cloud Storage C++ API 参考文档

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::runtime_error(object_metadata.status().message());
  }

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

Go

如需了解详情,请参阅 Cloud Storage Go API 参考文档

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: %v", err)
	}
	defer client.Close()

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

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

	// obj is encrypted with key, we are encrypting it with the newKey.
	_, err = obj.Key(newKey).CopierFrom(obj.Key(key)).Run(ctx)
	if err != nil {
		return fmt.Errorf("Key(%q).CopierFrom(%q).Run: %v", newKey, key, err)
	}
	fmt.Fprintf(w, "Key rotation complete for blob %v.\n", object)
	return nil
}

Java

如需了解详情,请参阅 Cloud Storage Java API 参考文档

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);
    // 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))
            .setTarget(blobId, Storage.BlobTargetOption.encryptionKey(newEncryptionKey))
            .build();
    storage.copy(request);

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

PHP

如需了解详情,请参阅 Cloud Storage PHP API 参考文档

use Google\Cloud\Storage\StorageClient;

/**
 * Change the encryption key used to store an existing object.
 *
 * @param string $bucketName the name of your Google Cloud bucket.
 * @param string $objectName the name of your Google Cloud object.
 * @param string $base64EncryptionKey the base64 encoded encryption key.
 * @param string $newBase64EncryptionKey the new base64 encoded encryption key.
 *
 * @return void
 */
function rotate_encryption_key(
    $bucketName,
    $objectName,
    $base64EncryptionKey,
    $newBase64EncryptionKey
) {
    $storage = new StorageClient();
    $object = $storage->bucket($bucketName)->object($objectName);

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

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

Python

如需了解详情,请参阅 Cloud Storage Python API 参考文档

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
    )

    token = None

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

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

Ruby

如需了解详情,请参阅 Cloud Storage Ruby API 参考文档

# bucket_name            = "Your Google Cloud Storage bucket name"
# file_name              = "Name of a file in the Cloud Storage bucket"
# current_encryption_key = "Encryption key currently being used"
# new_encryption_key     = "New encryption key to use"

require "google/cloud/storage"

storage = Google::Cloud::Storage.new
bucket  = storage.bucket bucket_name
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."

REST API

JSON API

  1. OAuth 2.0 Playground 获取授权访问令牌。将 Playground 配置为使用您自己的 OAuth 凭据。
  2. 使用 cURL,通过 POST Object 请求调用 JSON API

    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: 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"

    其中:

    • OBJECT 是要上传的对象的路径,例如 Desktop/dogs.png
    • OAUTH2_TOKEN 是您在第 1 步中生成的访问令牌。
    • OBJECT_CONTENT_TYPE 是该对象的内容类型,例如 image/png
    • NEW_ENCRYPTION_KEY 是用于加密对象的新 AES-256 密钥。
    • HASH_OF_NEW_KEY 是新 AES-256 密钥的 SHA-256 哈希值。
    • OLD_ENCRYPTION_KEY 是用于加密对象的当前 AES-256 密钥。
    • HASH_OF_OLD_KEY 是 AES-256 密钥的当前 SHA-256 哈希值。
    • BUCKET_NAME 是包含相关对象的存储分区的名称。例如 my-bucket
    • OBJECT_NAME 是您要轮替其密钥的对象的名称。例如 Desktop/dogs.png

如需详细了解特定于加密的标头,请参阅加密请求标头

XML API

XML API 不支持通过重写对象轮替客户提供的加密密钥。如需使用 XML API 将新的客户提供的密钥应用到对象,您应该:

  1. 下载现有对象
  2. 使用新密钥重新上传对象

后续步骤

  • 详细了解 CSEK