使用客戶提供的加密金鑰

本頁說明如何在 Cloud Storage 使用自己的加密金鑰 (亦稱為「客戶提供的加密金鑰」)。如要進一步瞭解此功能,包括其適用的國家/地區,請參閱客戶提供的加密金鑰一文。如要瞭解 Cloud Storage 中的其他加密選項,請參閱資料加密選項一文。

產生自己的加密金鑰

產生 Base64-encoded 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<unsigned long> 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);
}

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

const crypto = require('crypto');

/**
 * 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.
 *
 * @returns {string} The encryption key.
 */
function generateEncryptionKey() {
  const buffer = crypto.randomBytes(32);
  const encodedKey = buffer.toString('base64');

  console.log(`Base 64 encoded encryption key: ${encodedKey}`);

  return encodedKey;
}

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 參考說明文件

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] 是指用於加密已上傳檔案的金鑰。

  2. 使用 gsutil cp 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    gsutil cp [LOCAL_OBJECT_LOCATION] gs://[DESTINATION_BUCKET_NAME]/

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name,
   std::string 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 參考說明文件

obj := client.Bucket(bucket).Object(object)
// Encrypt the object's contents.
wc := obj.Key(secretKey).NewWriter(ctx)
if _, err := wc.Write([]byte("top secret")); err != nil {
	return err
}
if err := wc.Close(); err != nil {
	return err
}

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

byte[] data = "Hello, World!".getBytes(UTF_8);

BlobId blobId = BlobId.of(bucketName, blobName);
BlobInfo blobInfo = BlobInfo.newBuilder(blobId).setContentType("text/plain").build();
Blob blob = storage.create(blobInfo, data, BlobTargetOption.encryptionKey(encryptionKey));

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

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

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

/**
 * 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';

// See the "Generating your own encryption key" section above.
// const key = 'A base64 encoded customer-supplied key';

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}.`
);

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 參考說明文件

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.get_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 = Blob(destination_blob_name, bucket, 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 參考說明文件

# project_id        = "Your Google Cloud project ID"
# 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 project_id: project_id

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. 將物件的資料新增至要求主體。
  3. 透過 POST 物件要求使用 cURL 呼叫 JSON API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    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://www.googleapis.com/upload/storage/v1/b/[BUCKET_NAME]/o?uploadType=media&name=[OBJECT_NAME]"

如要進一步瞭解特定加密的標頭,請參閱加密要求標頭

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設定為使用您自己的 OAuth 憑證。
  2. 將物件的資料新增至要求主體。
  3. 透過 PUT 物件要求使用 cURL 呼叫 XML API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    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]"

如要進一步瞭解特定加密的標頭,請參閱加密要求標頭

下載您已加密的物件

如何下載儲存在 Cloud Storage 並以客戶提供的加密金鑰進行加密的物件:

gsutil

  1. 將下列選項新增至 boto 設定檔[GSUtil] 區段:

    decryption_key1 = [YOUR_ENCRYPTION_KEY]

    其中的 [YOUR_ENCRYPTION_KEY] 是指上傳物件時用於加密物件的金鑰。

  2. 使用 gsutil cp 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    gsutil cp gs://[BUCKET_NAME]/[OBJECT_NAME] [OBJECT_DESTINATION]

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

namespace gcs = google::cloud::storage;
[](gcs::Client client, std::string bucket_name, std::string object_name,
   std::string 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 參考說明文件

obj := client.Bucket(bucket).Object(object)
rc, err := obj.Key(secretKey).NewReader(ctx)
if err != nil {
	return nil, err
}
defer rc.Close()

data, err := ioutil.ReadAll(rc)
if err != nil {
	return nil, err
}

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

byte[] content =
    storage.readAllBytes(bucketName, blobName, BlobSourceOption.decryptionKey(decryptionKey));

Node.js

詳情請參閱 Cloud Storage Node.js API 參考說明文件

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

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

/**
 * 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';

// See the "Generating your own encryption key" section above.
// const key = 'A base64 encoded customer-supplied key';

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}.`);

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 參考說明文件

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.
    """
    storage_client = storage.Client()
    bucket = storage_client.get_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 = Blob(source_blob_name, bucket, 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 參考說明文件

# project_id     = "Your Google Cloud project ID"
# 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 project_id: project_id

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. 透過 GET 物件要求使用 cURL 呼叫 JSON API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]?alt=media"

如要進一步瞭解特定加密的標頭,請參閱加密要求標頭

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設定為使用您自己的 OAuth 憑證。
  2. 透過 GET 物件要求使用 cURL 呼叫 XML API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    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]"

如要進一步瞭解特定加密的標頭,請參閱加密要求標頭

輪替加密金鑰

如何輪替客戶提供的加密金鑰:

gsutil

  1. 將下列選項新增至 boto 設定檔[GSUtil] 區段,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    encryption_key = [NEW_ENCRYPTION_KEY]
    decryption_key1 = [OLD_ENCRYPTION_KEY]
  2. 使用含有 -k 標記的 gsutil rewrite 指令,並將 [VALUES_IN_BRACKETS] 替換為適當的值:

    gsutil rewrite -k gs://[BUCKET-NAME]/[OBJECT_NAME]

程式碼範例

C++

詳情請參閱 Cloud Storage C++ API 參考說明文件

namespace gcs = google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string bucket_name, std::string object_name,
   std::string old_key_base64, std::string 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 參考說明文件

client, err := storage.NewClient(ctx)
if err != nil {
	return err
}
obj := client.Bucket(bucket).Object(object)
// 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 err
}

Java

詳情請參閱 Cloud Storage Java API 參考說明文件

BlobId blobId = BlobId.of(bucketName, blobName);
CopyRequest request =
    CopyRequest.newBuilder()
        .setSource(blobId)
        .setSourceOptions(BlobSourceOption.decryptionKey(oldEncryptionKey))
        .setTarget(blobId, BlobTargetOption.encryptionKey(newEncryptionKey))
        .build();
Blob blob = storage.copy(request).getResult();

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 參考說明文件

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.get_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 = Blob(
        blob_name, bucket, encryption_key=current_encryption_key)
    destination_blob = Blob(
        blob_name, bucket, 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 參考說明文件

# project_id             = "Your Google Cloud project ID"
# 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 project_id: project_id
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. 透過 POST 物件要求使用 cURL 呼叫 JSON API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    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://www.googleapis.com/storage/v1/b/[BUCKET_NAME]/o/[OBJECT_NAME]/rewriteTo/b/[BUCKET_NAME]/o/[OBJECT_NAME]"

如要進一步瞭解特定加密的標頭,請參閱加密要求標頭

XML API

  1. OAuth 2.0 Playground 取得授權存取憑證。將 Playground 設定為使用您自己的 OAuth 憑證。
  2. 從 Cloud Storage 中移除原始物件。如要進行此操作,請透過 DELETE 物件要求使用 cURL 呼叫 XML API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    curl -X DELETE \
        -H "Authorization: Bearer [OAUTH2_TOKEN]" \
        "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"
  3. 將物件的資料新增至新的要求主體。
  4. 透過 PUT 物件要求使用 cURL 呼叫 XML API,並將 [VALUES_IN_BRACKETS] 替換為適當的值:
    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: [NEW_ENCRYPTION_KEY]" \
        -H "x-goog-encryption-key-sha256: [HASH_OF_NEW_KEY]" \
        "https://storage.googleapis.com/[BUCKET_NAME]/[OBJECT_NAME]"

如要進一步瞭解特定加密的標頭,請參閱加密要求標頭

本頁內容對您是否有任何幫助?請提供意見:

傳送您對下列選項的寶貴意見...

這個網頁
Cloud Storage
需要協助嗎?請前往我們的支援網頁