אכיפה או הגבלה של סוגי ההצפנה לקטגוריה

במאמר הזה מוסבר איך להגדיר אילו שיטות הצפנה מותרות או מוגבלות לאובייקטים חדשים בקטגוריה של Cloud Storage. אפשר להגדיר קטגוריה כדי לאכוף או להגביל את השימוש בהצפנה רגילה (הצפנת ברירת המחדל של Google), במפתחות הצפנה בניהול הלקוח (CMEK) או במפתחות הצפנה באספקת הלקוח (CSEK) לכל האובייקטים החדשים שנוצרים בקטגוריה.

לדוגמה, כדי לעמוד בדרישות התאימות בנוגע לניהול מפתחות הצפנה, אתם יכולים לדרוש שכל האובייקטים החדשים יוצפנו באמצעות הצפנה רגילה או CMEK, ולהגביל את השימוש במפתחות הצפנה באספקת הלקוח.

מידע נוסף על שיטות ההצפנה הזמינות מופיע במאמר אפשרויות להצפנת נתונים.

‫Cloud Storage אוכף את הגדרות ההצפנה לכל הפעולות שיוצרות אובייקט חדש, כמו העלאת אובייקט, העתקת אובייקט, יצירת אובייקט מרובה חלקים ושחזור אובייקט שנמחק זמנית.

לפני שמתחילים

כדי לקבל את ההרשאות שנדרשות להגדרת אכיפת ההצפנה בקטגוריה, צריך לבקש מהאדמין להקצות לכם את תפקיד ה-IAM אדמין לניהול אחסון (roles/storage.admin) בקטגוריה. כדי לקרוא הסבר על מתן תפקידים, ראו איך מנהלים את הגישה ברמת הפרויקט, התיקייה והארגון.

התפקיד המוגדר מראש הזה כולל את ההרשאות שנדרשות להגדרת אכיפת הצפנה בקטגוריה. כדי לראות בדיוק אילו הרשאות נדרשות, אפשר להרחיב את הקטע ההרשאות הנדרשות:

ההרשאות הנדרשות

כדי להגדיר אכיפת הצפנה לקטגוריה, נדרשות ההרשאות הבאות:

  • מגדירים את ההגדרה כשיוצרים קטגוריה חדשה: storage.buckets.create
  • עדכון ההגדרה של קטגוריה קיימת: storage.buckets.update
  • אם משתמשים במסוף Google Cloud כדי לבצע את השלבים בדף הזה:
    • storage.buckets.get
    • storage.buckets.list

יכול להיות שתקבלו את ההרשאות האלה באמצעות תפקידים בהתאמה אישית או תפקידים מוגדרים מראש אחרים.

יצירת קטגוריית אחסון שבה נאכפים סוגי הצפנה

כשיוצרים קטגוריה חדשה, אפשר לציין את שיטות ההצפנה שמותרות או מוגבלות לאובייקטים בקטגוריה.

אם מגדירים מפתח Cloud KMS כברירת מחדל לקטגוריה, צריך גם לאפשר הצפנה באמצעות מפתחות CMEK או מפתחות הצפנה באספקת הלקוח.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. לוחצים על יצירה.
  3. ממלאים את פרטי הקטגוריה בדף Create a bucket. אחרי כל אחד מהשלבים הבאים, לוחצים על המשך כדי לעבור לשלב הבא:

    1. בקטע Get started (תחילת העבודה), מבצעים את הפעולות הבאות:

      • מזינים שם ייחודי בהיקף גלובלי שעומד בקריטריונים לשמות של קטגוריות.

      • כדי להוסיף תווית של דלי, לוחצים על חץ ההרחבה כדי להרחיב את הקטע Labels (תוויות), לוחצים על Add label (הוספת תווית) ומציינים key ו-value בשביל התווית.

    2. בקטע Choose where to store your data, מבצעים את הפעולות הבאות:

      1. בוחרים סוג מיקום.

      2. בתפריט הנפתח של סוג המיקום, בוחרים Location שבו נתוני האובייקטים בקטגוריה יישמרו באופן קבוע.

      3. כדי להגדיר שכפול בין מאגרי מידע, בוחרים באפשרות הוספת שכפול בין מאגרי מידע באמצעות Storage Transfer Service ופועלים לפי השלבים:

        הגדרה של רפליקציה בין מאגרי מידע

        1. בתפריט Bucket, בוחרים באפשרות הרצויה.
        2. בקטע הגדרות השכפול, לוחצים על הגדרה כדי להגדיר את ההגדרות של משימת השכפול.

          מופיעה החלונית Configure cross-bucket replication.

          • כדי לסנן אובייקטים לשכפול לפי קידומת של שם האובייקט, מזינים קידומת שרוצים לכלול או להחריג אובייקטים שלה, ואז לוחצים על הוספת קידומת.
          • כדי להגדיר סוג אחסון לאובייקטים המשוכפלים, בוחרים סוג אחסון בתפריט סוג אחסון. אם מדלגים על השלב הזה, האובייקטים המשוכפלים ישתמשו בסוג האחסון של קטגוריית היעד כברירת מחדל.
          • לוחצים על סיום.
    3. בקטע Choose how to store your data מבצעים את הפעולות הבאות:

      1. בוחרים default storage class לקטגוריה או Autoclass לניהול אוטומטי של סוג האחסון (storage class) של נתוני הקטגוריה.

      2. בקטע Optimize storage for data-intensive workloads: מבצעים את הפעולות הבאות:

        • כדי להפעיל מרחב שמות היררכי, בוחרים באפשרות הפעלת מרחב שמות היררכי בקטגוריה הזו.

        • כדי להפעיל את Rapid Cache, בוחרים באפשרות Enable Rapid Cache ופועלים לפי השלבים:
          1. כדי ליצור מטמונים, לוחצים על Configure (הגדרה).

          2. בתיבת הדו-שיח הגדרת הגדרות מטמון שמופיעה, לוחצים על החץ לתפריט הנפתח לצד האזורים שמופיעים ברשימה ובוחרים את האזורים שבהם רוצים ליצור מטמונים.

          3. לוחצים על סיום.

    4. בקטע Choose how to control access to objects, בוחרים אם הקטגוריה אוכפת public access prevention או לא, ואז בוחרים גישה אחידה ברמת הקטגוריה לאובייקטים של הקטגוריה.

    5. בקטע Choose how to protect object data:

      • בוחרים באחת מהאפשרויות בקטע הגנה על נתונים שרוצים להגדיר לקטגוריה.

      • כדי לשנות את משך הזמן שבו מחיקה רכה שומרת אובייקטים אחרי המחיקה, מסמנים את התיבה Soft delete policy (מדיניות מחיקה רכה) ואז בוחרים באפשרות Set custom retention duration (הגדרת משך שמירה מותאם אישית). לאחר מכן, מציינים כמה זמן רוצים לשמור את האובייקטים שנמחקו.

        כדי להשבית את המחיקה הרכה, למשל אם המאגר יכיל בעיקר נתונים זמניים לזמן קצר, מבטלים את הסימון בתיבת הסימון Soft delete policy (מדיניות מחיקה רכה).

      • כדי לבחור איך להצפין את נתוני האובייקט, לוחצים על החץ להרחבה עם התווית Data encryption (הצפנת נתונים) ופועלים לפי השלבים הבאים:

  4. לוחצים על יצירה.

gcloud

  1. יוצרים קובץ JSON שמכיל את הפרטים הבאים:

    {
      "gmekEnforcement": {"restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"},
      "cmekEnforcement": {"restrictionMode": "CMEK_RESTRICTION_MODE"},
      "csekEnforcement": {"restrictionMode": "CSEK_RESTRICTION_MODE"}
    }

    מחליפים את מה שכתוב בשדות הבאים:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: האם מותר להשתמש בהצפנה רגילה (הצפנה שמוגדרת כברירת מחדל ב-Google) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש בהצפנה רגילה.
      • FullyRestricted: אי אפשר להשתמש בהצפנה רגילה לאובייקטים חדשים.
    • CMEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות CMEK כשיוצרים אובייקטים בקטגוריה הזו. הערכים הנתמכים:
      • NotRestricted: אפשר להשתמש במפתחות CMEK לאובייקטים חדשים.
      • FullyRestricted: אי אפשר להשתמש במפתחות CMEK באובייקטים חדשים.
    • CSEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות מפתחות הצפנה באספקת הלקוח (CSEK) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש במפתחות הצפנה באספקת הלקוח (CSEK).
      • FullyRestricted: אי אפשר להשתמש במפתחות הצפנה באספקת הלקוח (CSEK) לאובייקטים חדשים.

    חובה לאפשר לפחות סוג הצפנה אחד. אם לא מציינים את הגדרת האכיפה לסוג הצפנה מסוים, סוג ההצפנה הזה מותר כברירת מחדל.

  2. משתמשים בפקודה gcloud storage buckets create עם הדגל --encryption-enforcement-file:

    gcloud storage buckets create gs://BUCKET_NAME \
      --encryption-enforcement-file=ENCRYPTION_ENFORCEMENT_FILE

    מחליפים את מה שכתוב בשדות הבאים:

    • BUCKET_NAME: שם הקטגוריה.
    • ENCRYPTION_ENFORCEMENT_FILE: הנתיב לקובץ JSON שיצרתם בשלב הקודם.

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& project_id,
   std::string const& bucket_name) {
  auto create_bucket = [&](std::string const& name,
                           gcs::BucketEncryption encryption) {
    StatusOr<gcs::BucketMetadata> bucket = client.CreateBucketForProject(
        name, project_id, gcs::BucketMetadata().set_encryption(encryption));
    if (!bucket) throw std::move(bucket).status();
    return bucket;
  };

  // Example 1: Enforce GMEK Only
  gcs::BucketEncryption gmek_encryption;
  gmek_encryption.google_managed_encryption_enforcement_config
      .restriction_mode = "NotRestricted";
  gmek_encryption.customer_managed_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  gmek_encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  std::cout << "Bucket "
            << create_bucket("g-" + bucket_name, gmek_encryption)->name()
            << " created with GMEK-only enforcement policy.\n";

  // In GCS, a single project cannot create or delete buckets more often than
  // once every two seconds. We pause to avoid rate limiting.
  std::this_thread::sleep_for(std::chrono::seconds(2));

  // Example 2: Enforce CMEK Only
  gcs::BucketEncryption cmek_encryption;
  cmek_encryption.google_managed_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  cmek_encryption.customer_managed_encryption_enforcement_config
      .restriction_mode = "NotRestricted";
  cmek_encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  std::cout << "Bucket "
            << create_bucket("c-" + bucket_name, cmek_encryption)->name()
            << " created with CMEK-only enforcement policy.\n";

  // In GCS, a single project cannot create or delete buckets more often than
  // once every two seconds. We pause to avoid rate limiting.
  std::this_thread::sleep_for(std::chrono::seconds(2));

  // Example 3: Restrict CSEK (Ransomware Protection)
  gcs::BucketEncryption csek_encryption;
  csek_encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";
  std::cout << "Bucket "
            << create_bucket("rc-" + bucket_name, csek_encryption)->name()
            << " created with a policy to restrict CSEK.\n";
}

C#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketSetEncryptionEnforcementConfigSample
{
    /// <summary>
    /// Set the encryption enforcement configuration for a bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="kmsKeyName">
    /// The full resource name of the Cloud KMS key (CMEK). 
    /// Required if <paramref name="enforceCmek"/> is true.
    /// </param>
    /// <param name="enforceCmek">If true, enforces Customer-Managed Encryption Key.</param>
    /// <param name="enforceGmek">If true, enforces Google-Managed Encryption Key.</param>
    /// <param name="enforceCsek">If true, enforces Customer-Supplied Encryption Key.</param>
    public Bucket.EncryptionData SetBucketEncryptionEnforcementConfig(
        string bucketName = "your-unique-bucket-name",
        string kmsKeyName = null,
        bool enforceCmek = false,
        bool enforceGmek = false,
        bool enforceCsek = false)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Encryption == null)
        {
            bucket.Encryption = new Bucket.EncryptionData();
        }

        if (!string.IsNullOrEmpty(kmsKeyName))
        {
            bucket.Encryption.DefaultKmsKeyName = kmsKeyName;
            Console.WriteLine($"Default Key Set: {kmsKeyName}");
        }
        else
        {
            bucket.Encryption.DefaultKmsKeyName = null;
            Console.WriteLine("Default Key Set: None");
        }

        string cmek = (enforceGmek || enforceCsek) ? "FullyRestricted" : "NotRestricted";
        string gmek = (enforceCmek || enforceCsek) ? "FullyRestricted" : "NotRestricted";
        string csek = (enforceCmek || enforceGmek) ? "FullyRestricted" : "NotRestricted";

        string message = enforceCmek ? "CMEK-only enforcement policy"
            : enforceGmek ? "GMEK-only enforcement policy"
            : enforceCsek ? "CSEK-only enforcement policy"
            : "no encryption enforcement policy";

        bucket.Encryption.CustomerManagedEncryptionEnforcementConfig = new Bucket.EncryptionData.CustomerManagedEncryptionEnforcementConfigData { RestrictionMode = cmek };
        bucket.Encryption.CustomerSuppliedEncryptionEnforcementConfig = new Bucket.EncryptionData.CustomerSuppliedEncryptionEnforcementConfigData { RestrictionMode = csek };
        bucket.Encryption.GoogleManagedEncryptionEnforcementConfig = new Bucket.EncryptionData.GoogleManagedEncryptionEnforcementConfigData { RestrictionMode = gmek };

        if (message != null)
        {
            Console.WriteLine($"Bucket {bucketName} updated with {message}");
        }

        var updatedBucket = storage.UpdateBucket(bucket);
        return updatedBucket.Encryption;
    }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

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

// setBucketEncryptionEnforcementConfig sets a bucket's encryption enforcement configuration.
func setBucketEncryptionEnforcementConfig(w io.Writer, projectID, bucketName string) error {
	// projectID := "my-project-id"
	// bucketName := "bucket-name"
	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*30)
	defer cancel()

	bucket := client.Bucket(bucketName)
	if err := bucket.Create(ctx, projectID, &storage.BucketAttrs{
		GoogleManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
		CustomerManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.NotRestricted,
		},
		CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
	}); err != nil {
		return fmt.Errorf("Bucket(%q).Create: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v encryption enforcement policies set.\n", bucketName)
	return nil
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo;
import com.google.cloud.storage.BucketInfo.CustomerManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.CustomerSuppliedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.EncryptionEnforcementRestrictionMode;
import com.google.cloud.storage.BucketInfo.GoogleManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class SetBucketEncryptionEnforcementConfig {
  public static void setBucketEncryptionEnforcementConfig(String projectId, String bucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

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

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

      // Example 1: Enforce GMEK Only
      setGmekEnforcedPolicy(storage, "g-" + bucketName);

      // Example 2: Enforce CMEK Only
      setCmekEnforcedPolicy(storage, "c-" + bucketName);

      // Example 3: Restrict CSEK (Ransomware Protection)
      restrictCsekPolicy(storage, "rc-" + bucketName);
    }
  }

  public static void setGmekEnforcedPolicy(Storage storage, String bucketName) {
    GoogleManagedEncryptionEnforcementConfig gmekConfig =
        GoogleManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);
    CustomerManagedEncryptionEnforcementConfig cmekConfig =
        CustomerManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setGoogleManagedEncryptionEnforcementConfig(gmekConfig)
            .setCustomerManagedEncryptionEnforcementConfig(cmekConfig)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println(
        "Bucket " + bucket.getName() + " created with GMEK-only enforcement policy.");
  }

  public static void setCmekEnforcedPolicy(Storage storage, String bucketName) {
    GoogleManagedEncryptionEnforcementConfig gmekConfig =
        GoogleManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);
    CustomerManagedEncryptionEnforcementConfig cmekConfig =
        CustomerManagedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setGoogleManagedEncryptionEnforcementConfig(gmekConfig)
            .setCustomerManagedEncryptionEnforcementConfig(cmekConfig)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println(
        "Bucket " + bucket.getName() + " created with CMEK-only enforcement policy.");
  }

  public static void restrictCsekPolicy(Storage storage, String bucketName) {
    CustomerSuppliedEncryptionEnforcementConfig csekConfig =
        CustomerSuppliedEncryptionEnforcementConfig.of(
            EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

    BucketInfo bucketInfo =
        BucketInfo.newBuilder(bucketName)
            .setCustomerSuppliedEncryptionEnforcementConfig(csekConfig)
            .build();

    Bucket bucket = storage.create(bucketInfo);
    System.out.println("Bucket " + bucket.getName() + " created with a policy to restrict CSEK.");
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

// The name of the KMS key to be used as the default
// const defaultKmsKeyName = 'my-key';

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

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

async function setBucketEncryptionEnforcementConfig() {
  const options = {
    encryption: {
      defaultKmsKeyName,
      googleManagedEncryptionEnforcementConfig: {
        restrictionMode: 'FullyRestricted',
      },
      customerSuppliedEncryptionEnforcementConfig: {
        restrictionMode: 'FullyRestricted',
      },
      customerManagedEncryptionEnforcementConfig: {
        restrictionMode: 'NotRestricted',
      },
    },
  };

  const [metadata] = await storage.bucket(bucketName).setMetadata(options);

  console.log(
    `Encryption enforcement configuration updated for bucket ${bucketName}.`
  );
  const enc = metadata.encryption;
  if (enc) {
    console.log(`Default KMS Key: ${enc.defaultKmsKeyName}`);

    const logEnforcement = (label, config) => {
      if (config) {
        console.log(`${label}:`);
        console.log(`  Mode: ${config.restrictionMode}`);
        console.log(`  Effective: ${config.effectiveTime}`);
      }
    };

    logEnforcement(
      'Google Managed (GMEK) Enforcement',
      enc.googleManagedEncryptionEnforcementConfig
    );
    logEnforcement(
      'Customer Managed (CMEK) Enforcement',
      enc.customerManagedEncryptionEnforcementConfig
    );
    logEnforcement(
      'Customer Supplied (CSEK) Enforcement',
      enc.customerSuppliedEncryptionEnforcementConfig
    );
  }
}

setBucketEncryptionEnforcementConfig().catch(console.error);

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Storage\StorageClient;

/**
 * Creates a bucket with specific encryption enforcement (e.g., CMEK-only).
 *
 * @param string $bucketName The ID of your GCS bucket (e.g. "my-bucket").
 * @param string $kmsKeyName The name of the KMS key to be used as the default (e.g. "projects/my-project/...").
 */
function set_bucket_encryption_enforcement_config(string $bucketName, string $kmsKeyName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    // This configuration enforces that all objects uploaded to the bucket
    // must use Customer Managed Encryption Keys (CMEK).
    $options = [
        'encryption' => [
            'defaultKmsKeyName' => $kmsKeyName,
            'googleManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted',
            ],
            'customerSuppliedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted',
            ],
            'customerManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'NotRestricted',
            ],
        ],
    ];
    $storage->createBucket($bucketName, $options);

    printf('Bucket %s created with encryption enforcement configuration.' . PHP_EOL, $bucketName);
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from google.cloud import storage
from google.cloud.storage.bucket import EncryptionEnforcementConfig


def set_bucket_encryption_enforcement_config(bucket_name):
    """Creates a bucket with encryption enforcement configuration."""
    # The ID of your GCS bucket
    # bucket_name = "your-unique-bucket-name"

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

    # Setting restriction_mode to "FullyRestricted" for Google-managed encryption (GMEK)
    # means objects cannot be created using the default Google-managed keys.
    bucket.encryption.google_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    # Setting restriction_mode to "NotRestricted" for Customer-managed encryption (CMEK)
    # ensures that objects ARE permitted to be created using Cloud KMS keys.
    bucket.encryption.customer_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="NotRestricted")
    )

    # Setting restriction_mode to "FullyRestricted" for Customer-supplied encryption (CSEK)
    # prevents objects from being created using raw, client-side provided keys.
    bucket.encryption.customer_supplied_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    bucket.create()

    print(f"Created bucket {bucket.name} with Encryption Enforcement Config.")

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

def set_bucket_encryption_enforcement_config bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  require "google/cloud/storage"

  storage = Google::Cloud::Storage.new

  customer_managed_config = { restriction_mode: "NotRestricted" }
  customer_supplied_config = { restriction_mode: "FullyRestricted" }
  google_managed_config = { restriction_mode: "FullyRestricted" }

  bucket = storage.create_bucket bucket_name do |b|
    b.customer_managed_encryption_enforcement_config = customer_managed_config
    b.customer_supplied_encryption_enforcement_config = customer_supplied_config
    b.google_managed_encryption_enforcement_config = google_managed_config
  end
  puts "Created bucket #{bucket.name} with Encryption Enforcement Config."
end

ממשקי API ל-REST

‫API בפורמט JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ JSON עם ההגדרות של הקטגוריה. רשימה מלאה של ההגדרות מופיעה במאמרי העזרה של Buckets: Insert. ההגדרות הבאות מגדירות רק את שם הקטגוריה וההצפנה:

    {
      "name": "BUCKET_NAME",
      "encryption": {
        "googleManagedEncryptionEnforcementConfig": {
          "restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"
        },
        "customerManagedEncryptionEnforcementConfig": {
          "restrictionMode": "CMEK_RESTRICTION_MODE"
        },
        "customerSuppliedEncryptionEnforcementConfig": {
          "restrictionMode": "CSEK_RESTRICTION_MODE"
        }
      }
    }

    מחליפים את מה שכתוב בשדות הבאים:

    • BUCKET_NAME: שם הקטגוריה.
    • STANDARD_ENCRYPTION_RESTRICTION_MODE: האם מותר להשתמש בהצפנה רגילה (הצפנה שמוגדרת כברירת מחדל ב-Google) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש בהצפנה רגילה.
      • FullyRestricted: אי אפשר להשתמש בהצפנה רגילה לאובייקטים חדשים.
    • CMEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות CMEK כשיוצרים אובייקטים בקטגוריה הזו. הערכים הנתמכים:
      • NotRestricted: אפשר להשתמש במפתחות CMEK לאובייקטים חדשים.
      • FullyRestricted: אי אפשר להשתמש במפתחות CMEK באובייקטים חדשים.
    • CSEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות מפתחות הצפנה באספקת הלקוח (CSEK) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש במפתחות הצפנה באספקת הלקוח (CSEK).
      • FullyRestricted: אי אפשר להשתמש במפתחות הצפנה באספקת הלקוח (CSEK) לאובייקטים חדשים.

    חובה לאפשר לפחות סוג הצפנה אחד. אם לא מציינים את הגדרת האכיפה לסוג הצפנה מסוים, סוג ההצפנה הזה מותר כברירת מחדל.

  3. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של קטגוריית POST:

    curl -X POST --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b?project=PROJECT_ID"

    מחליפים את מה שכתוב בשדות הבאים:

    • JSON_FILE_NAME: הנתיב לקובץ JSON שיצרתם בשלב הקודם.
    • PROJECT_ID: המזהה או המספר של הפרויקט שבו נמצא המאגר.

‫API בפורמט XML

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ XML עם ההגדרות של הקטגוריה. רשימה מלאה של ההגדרות מופיעה במאמרי העזרה בנושא XML: Create a bucket. ההגדרות הבאות מגדירות רק את אכיפת ההצפנה:

    <CreateBucketConfiguration>
      <EncryptionConfiguration>
        <GoogleManagedEncryptionEnforcement>
          <RestrictionMode>STANDARD_ENCRYPTION_RESTRICTION_MODE</RestrictionMode>
        </GoogleManagedEncryptionEnforcement>
        <CustomerManagedEncryptionEnforcement>
          <RestrictionMode>CMEK_RESTRICTION_MODE</RestrictionMode>
        </CustomerManagedEncryptionEnforcement>
        <CustomerSuppliedEncryptionEnforcement>
          <RestrictionMode>CSEK_RESTRICTION_MODE</RestrictionMode>
        </CustomerSuppliedEncryptionEnforcement>
      </EncryptionConfiguration>
    </CreateBucketConfiguration>

    מחליפים את מה שכתוב בשדות הבאים:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: האם מותר להשתמש בהצפנה רגילה (הצפנה שמוגדרת כברירת מחדל ב-Google) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש בהצפנה רגילה.
      • FullyRestricted: אי אפשר להשתמש בהצפנה רגילה לאובייקטים חדשים.
    • CMEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות CMEK כשיוצרים אובייקטים בקטגוריה הזו. הערכים הנתמכים:
      • NotRestricted: אפשר להשתמש במפתחות CMEK לאובייקטים חדשים.
      • FullyRestricted: אי אפשר להשתמש במפתחות CMEK באובייקטים חדשים.
    • CSEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות מפתחות הצפנה באספקת הלקוח (CSEK) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש במפתחות הצפנה באספקת הלקוח (CSEK).
      • FullyRestricted: אי אפשר להשתמש במפתחות הצפנה באספקת הלקוח (CSEK) לאובייקטים חדשים.

    חובה לאפשר לפחות סוג הצפנה אחד. אם לא מציינים את הגדרת האכיפה לסוג הצפנה מסוים, סוג ההצפנה הזה מותר כברירת מחדל.

  3. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשת קטגוריה PUT:

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "x-goog-project-id: PROJECT_ID" \
      "https://storage.googleapis.com/BUCKET_NAME"

    מחליפים את מה שכתוב בשדות הבאים:

    • XML_FILE_NAME: הנתיב לקובץ ה-XML שיצרתם בשלב הקודם.
    • PROJECT_ID: המזהה או המספר של הפרויקט שבו נמצא המאגר.
    • BUCKET_NAME: שם הקטגוריה.

עדכון של סוגי ההצפנה שמותרים לקטגוריה

כדי לעדכן את שיטות ההצפנה שמותרות לאובייקטים חדשים בקטגוריה קיימת, פועלים לפי השלבים הבאים.

אם בקטגוריה מוגדר מפתח KMS כברירת מחדל, אי אפשר להגביל גם מפתחות CMEK וגם מפתחות הצפנה באספקת הלקוח (CSEK), כי זה ימנע יצירה של אובייקטים חדשים. צריך לאפשר CMEK או CSEK בקטגוריה כזו, או להסיר את מפתח ברירת המחדל של Cloud KMS מהקטגוריה.

המסוף

  1. במסוף Google Cloud , נכנסים לדף Buckets של Cloud Storage.

    כניסה לדף Buckets

  2. ברשימת הקטגוריות, לוחצים על שם הקטגוריה.

  3. לוחצים על הכרטיסייה Configuration.

  4. בקטע Protection לוחצים על  Edit encryption.

  5. בקטע Encryption enforcement rules, בשדה Key types, בוחרים את סוגי ההצפנה שרוצים לאפשר או להגביל לאובייקטים חדשים בקטגוריה.

  6. לוחצים על Save.

gcloud

  1. יוצרים קובץ JSON שמכיל את הפרטים הבאים:

    {
      "gmekEnforcement": {"restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"},
      "cmekEnforcement": {"restrictionMode": "CMEK_RESTRICTION_MODE"},
      "csekEnforcement": {"restrictionMode": "CSEK_RESTRICTION_MODE"}
    }

    מחליפים את מה שכתוב בשדות הבאים:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: האם מותר להשתמש בהצפנה רגילה (הצפנה שמוגדרת כברירת מחדל ב-Google) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש בהצפנה רגילה.
      • FullyRestricted: אי אפשר להשתמש בהצפנה רגילה לאובייקטים חדשים.
    • CMEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות CMEK כשיוצרים אובייקטים בקטגוריה הזו. הערכים הנתמכים:
      • NotRestricted: אפשר להשתמש במפתחות CMEK לאובייקטים חדשים.
      • FullyRestricted: אי אפשר להשתמש במפתחות CMEK באובייקטים חדשים.
    • CSEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות מפתחות הצפנה באספקת הלקוח (CSEK) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש במפתחות הצפנה באספקת הלקוח (CSEK).
      • FullyRestricted: אי אפשר להשתמש במפתחות הצפנה באספקת הלקוח (CSEK) לאובייקטים חדשים.

    חובה לאפשר לפחות סוג הצפנה אחד. אם לא מציינים סוג הצפנה, ההגדרה הקיימת נשמרת.

  2. משתמשים בפקודה gcloud storage buckets update עם הדגל --encryption-enforcement-file:

    gcloud storage buckets update gs://BUCKET_NAME \
      --encryption-enforcement-file=ENCRYPTION_ENFORCEMENT_FILE

    מחליפים את מה שכתוב בשדות הבאים:

    • BUCKET_NAME: שם הקטגוריה.
    • ENCRYPTION_ENFORCEMENT_FILE: הנתיב לקובץ JSON שיצרתם בשלב הקודם.

    יכול להיות שיחלפו עד שתי דקות עד שההגדרה המעודכנת תיכנס לתוקף.

ספריות לקוח

C++

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C++ API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

namespace gcs = ::google::cloud::storage;
using ::google::cloud::StatusOr;
[](gcs::Client client, std::string const& bucket_name) {
  StatusOr<gcs::BucketMetadata> original =
      client.GetBucketMetadata(bucket_name);

  gcs::BucketMetadata updated_metadata = *original;
  gcs::BucketEncryption encryption;
  if (original->has_encryption()) {
    encryption = original->encryption();
  }

  // 1. Update a specific type (e.g., change GMEK to FullyRestricted)
  encryption.google_managed_encryption_enforcement_config.restriction_mode =
      "FullyRestricted";
  // 2. Remove a specific type (e.g., remove CMEK enforcement)
  encryption.customer_managed_encryption_enforcement_config.restriction_mode =
      "NotRestricted";
  // For the update, need to specify all three configs, so keeping this same
  // as before
  encryption.customer_supplied_encryption_enforcement_config
      .restriction_mode = "FullyRestricted";

  updated_metadata.set_encryption(encryption);

  StatusOr<gcs::BucketMetadata> updated =
      client.PatchBucket(bucket_name, *original, updated_metadata);
  if (!updated) throw std::move(updated).status();

  std::cout << "Encryption enforcement policy updated for bucket "
            << updated->name() << "\n"
            << "GMEK is now fully restricted, and CMEK enforcement has been "
               "removed.\n";
}

C#

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage C# API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


using Google.Apis.Storage.v1.Data;
using Google.Cloud.Storage.V1;
using System;

public class BucketUpdateEncryptionEnforcementConfigSample
{
    /// <summary>
    /// Updates the encryption enforcement configuration of the bucket.
    /// </summary>
    /// <param name="bucketName">The name of the bucket.</param>
    /// <param name="encryptionData">The encryption configuration for the bucket.</param>
    public Bucket.EncryptionData BucketUpdateEncryptionEnforcementConfig(string bucketName = "your-unique-bucket-name", Bucket.EncryptionData encryptionData = null)
    {
        var storage = StorageClient.Create();
        var bucket = storage.GetBucket(bucketName);

        if (bucket.Encryption is null
            || (bucket.Encryption.CustomerManagedEncryptionEnforcementConfig is null
                && bucket.Encryption.CustomerSuppliedEncryptionEnforcementConfig is null
                && bucket.Encryption.GoogleManagedEncryptionEnforcementConfig is null))
        {
            Console.WriteLine($"No Encryption Enforcement Configuration found for bucket {bucketName}");
            return bucket.Encryption;
        }

        bucket.Encryption = encryptionData;
        bucket = storage.UpdateBucket(bucket);
        Console.WriteLine($"The Encryption Enforcement Configuration has been updated for the bucket {bucketName}");
        return bucket.Encryption;
    }
}

Go

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Go API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

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

// updateBucketEncryptionEnforcementConfig updates a bucket's encryption enforcement configuration.
func updateBucketEncryptionEnforcementConfig(w io.Writer, bucketName string) error {
	// bucketName := "bucket-name"
	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*30)
	defer cancel()

	bucket := client.Bucket(bucketName)
	if _, err := bucket.Update(ctx, storage.BucketAttrsToUpdate{
		GoogleManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.NotRestricted,
		},
		CustomerManagedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
		CustomerSuppliedEncryptionEnforcementConfig: &storage.EncryptionEnforcementConfig{
			RestrictionMode: storage.FullyRestricted,
		},
	}); err != nil {
		return fmt.Errorf("Bucket(%q).Update: %w", bucketName, err)
	}
	fmt.Fprintf(w, "Bucket %v encryption enforcement policies updated.\n", bucketName)
	return nil
}

Java

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Java API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


import com.google.cloud.storage.Bucket;
import com.google.cloud.storage.BucketInfo.CustomerManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.CustomerSuppliedEncryptionEnforcementConfig;
import com.google.cloud.storage.BucketInfo.EncryptionEnforcementRestrictionMode;
import com.google.cloud.storage.BucketInfo.GoogleManagedEncryptionEnforcementConfig;
import com.google.cloud.storage.Storage;
import com.google.cloud.storage.StorageOptions;

public class UpdateBucketEncryptionEnforcementConfig {
  public static void updateBucketEncryptionEnforcementConfig(String projectId, String bucketName)
      throws Exception {
    // The ID of your GCP project
    // String projectId = "your-project-id";

    // The ID of your GCS bucket with CMEK and CSEK restricted
    // String bucketName = "your-unique-bucket-name";

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

      Bucket bucket = storage.get(bucketName);
      if (bucket == null) {
        System.out.println("Bucket " + bucketName + " not found.");
        return;
      }

      // 1. Update a specific type (e.g., change GMEK to FULLY_RESTRICTED)
      GoogleManagedEncryptionEnforcementConfig newGmekConfig =
          GoogleManagedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

      // 2. Remove a specific type (e.g., remove CMEK enforcement)
      CustomerManagedEncryptionEnforcementConfig newCmekConfig =
          CustomerManagedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.NOT_RESTRICTED);

      // For the update, need to specify all three configs, so keeping this same as before
      CustomerSuppliedEncryptionEnforcementConfig sameCsekConfig =
          CustomerSuppliedEncryptionEnforcementConfig.of(
              EncryptionEnforcementRestrictionMode.FULLY_RESTRICTED);

      bucket.toBuilder()
          .setGoogleManagedEncryptionEnforcementConfig(newGmekConfig)
          .setCustomerManagedEncryptionEnforcementConfig(newCmekConfig)
          .setCustomerSuppliedEncryptionEnforcementConfig(sameCsekConfig)
          .build()
          .update();

      System.out.println("Encryption enforcement policy updated for bucket " + bucketName);
      System.out.println("GMEK is now fully restricted, and CMEK enforcement has been removed.");
    }
  }
}

Node.js

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Node.js API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

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

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

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

async function updateBucketEncryptionEnforcementConfig() {
  const bucket = storage.bucket(bucketName);

  // Update a specific encryption type's restriction mode
  // This partial update preserves other existing encryption settings.
  const updateOptions = {
    encryption: {
      googleManagedEncryptionEnforcementConfig: {
        restrictionMode: 'FullyRestricted',
      },
    },
  };

  await bucket.setMetadata(updateOptions);
  console.log(
    `Google-managed encryption enforcement set to FullyRestricted for ${bucketName}.`
  );

  // Remove all encryption enforcement configurations altogether
  // Setting these values to null removes the policies from the bucket metadata.
  const clearOptions = {
    encryption: {
      defaultKmsKeyName: null,
      googleManagedEncryptionEnforcementConfig: null,
      customerSuppliedEncryptionEnforcementConfig: null,
      customerManagedEncryptionEnforcementConfig: null,
    },
  };

  await bucket.setMetadata(clearOptions);
  console.log(
    `All encryption enforcement configurations removed from bucket ${bucketName}.`
  );
}

updateBucketEncryptionEnforcementConfig().catch(console.error);

PHP

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage PHP API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

use Google\Cloud\Storage\StorageClient;

/**
 * Updates or removes encryption enforcement configurations from a bucket.
 *
 * @param string $bucketName The ID of your GCS bucket (e.g. "my-bucket").
 */
function update_bucket_encryption_enforcement_config(string $bucketName): void
{
    $storage = new StorageClient();
    $bucket = $storage->bucket($bucketName);

    // Update a specific encryption type's restriction mode
    // This partial update preserves other existing encryption settings.
    $updateOptions = [
        'encryption' => [
            'googleManagedEncryptionEnforcementConfig' => [
                'restrictionMode' => 'FullyRestricted'
            ]
        ]
    ];
    $bucket->update($updateOptions);
    printf('Google-managed encryption enforcement set to FullyRestricted for %s.' . PHP_EOL, $bucketName);

    // Remove all encryption enforcement configurations altogether
    // Setting these values to null removes the policies from the bucket metadata.
    $clearOptions = [
        'encryption' => [
            'defaultKmsKeyName' => null,
            'googleManagedEncryptionEnforcementConfig' => null,
            'customerSuppliedEncryptionEnforcementConfig' => null,
            'customerManagedEncryptionEnforcementConfig' => null,
        ],
    ];

    $bucket->update($clearOptions);
    printf('All encryption enforcement configurations removed from bucket %s.' . PHP_EOL, $bucketName);
}

Python

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Python API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.

from google.cloud import storage
from google.cloud.storage.bucket import EncryptionEnforcementConfig


def update_bucket_encryption_enforcement_config(bucket_name):
    """Updates the encryption enforcement policy for a bucket."""
    # The ID of your GCS bucket with GMEK and CSEK restricted
    # bucket_name = "your-unique-bucket-name"

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

    # Update a specific type (e.g., change GMEK to NotRestricted)
    bucket.encryption.google_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="NotRestricted")
    )

    # Update another type (e.g., change CMEK to FullyRestricted)
    bucket.encryption.customer_managed_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    # Keeping CSEK unchanged
    bucket.encryption.customer_supplied_encryption_enforcement_config = (
        EncryptionEnforcementConfig(restriction_mode="FullyRestricted")
    )

    bucket.patch()

    print(f"Encryption enforcement policy updated for bucket {bucket.name}.")

    gmek = bucket.encryption.google_managed_encryption_enforcement_config
    cmek = bucket.encryption.customer_managed_encryption_enforcement_config
    csek = bucket.encryption.customer_supplied_encryption_enforcement_config

    print(f"GMEK restriction mode: {gmek.restriction_mode if gmek else 'None'}")
    print(f"CMEK restriction mode: {cmek.restriction_mode if cmek else 'None'}")
    print(f"CSEK restriction mode: {csek.restriction_mode if csek else 'None'}")

Ruby

למידע נוסף, קראו את מאמרי העזרה של Cloud Storage Ruby API.

כדי לבצע אימות ב-Cloud Storage, אתם צריכים להגדיר את Application Default Credentials. מידע נוסף זמין במאמר הגדרת אימות לספריות לקוח.


def update_bucket_encryption_enforcement_config bucket_name:
  # The ID to give your GCS bucket
  # bucket_name = "your-unique-bucket-name"

  storage = Google::Cloud::Storage.new
  bucket = storage.bucket bucket_name
  # Update a specific type (e.g., change GMEK to NotRestricted)
  new_config =  { restriction_mode: "NotRestricted" }

  bucket.update do |b|
    b.google_managed_encryption_enforcement_config = new_config
  end
  puts "Updated google_managed_config to " \
       "#{bucket.google_managed_encryption_enforcement_config.restriction_mode} " \
       "for bucket #{bucket.name}."
end

ממשקי API ל-REST

‫API בפורמט JSON

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ JSON שמכיל את הפרטים הבאים:

    {
      "encryption": {
        "googleManagedEncryptionEnforcementConfig": {
          "restrictionMode": "STANDARD_ENCRYPTION_RESTRICTION_MODE"
        },
        "customerManagedEncryptionEnforcementConfig": {
          "restrictionMode": "CMEK_RESTRICTION_MODE"
        },
        "customerSuppliedEncryptionEnforcementConfig": {
          "restrictionMode": "CSEK_RESTRICTION_MODE"
        }
      }
    }

    מחליפים את מה שכתוב בשדות הבאים:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: האם מותר להשתמש בהצפנה רגילה (הצפנה שמוגדרת כברירת מחדל ב-Google) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש בהצפנה רגילה.
      • FullyRestricted: אי אפשר להשתמש בהצפנה רגילה לאובייקטים חדשים.
    • CMEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות CMEK כשיוצרים אובייקטים בקטגוריה הזו. הערכים הנתמכים:
      • NotRestricted: אפשר להשתמש במפתחות CMEK לאובייקטים חדשים.
      • FullyRestricted: אי אפשר להשתמש במפתחות CMEK באובייקטים חדשים.
    • CSEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות מפתחות הצפנה באספקת הלקוח (CSEK) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש במפתחות הצפנה באספקת הלקוח (CSEK).
      • FullyRestricted: אי אפשר להשתמש במפתחות הצפנה באספקת הלקוח (CSEK) לאובייקטים חדשים.

    חובה לאפשר לפחות סוג הצפנה אחד. אם לא מציינים סוג הצפנה, ההגדרה הקיימת נשמרת.

  3. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט JSON באמצעות בקשה של קטגוריית PATCH:

    curl -X PATCH --data-binary @JSON_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      -H "Content-Type: application/json" \
      "https://storage.googleapis.com/storage/v1/b/BUCKET_NAME?fields=encryption"

    מחליפים את מה שכתוב בשדות הבאים:

    • JSON_FILE_NAME: הנתיב לקובץ JSON שיצרתם בשלב הקודם.
    • BUCKET_NAME: שם הקטגוריה.

    יכול להיות שיחלפו עד שתי דקות עד שההגדרה המעודכנת תיכנס לתוקף.

‫API בפורמט XML

  1. התקנה והפעלה של ה-CLI של gcloud, שמאפשרות ליצור אסימון גישה לכותרת Authorization.

  2. יוצרים קובץ XML שמכיל את הגדרות ההצפנה של הקטגוריה. ההגדרות הבאות מגדירות רק את תצורת האכיפה של ההצפנה.

    <EncryptionConfiguration>
      <GoogleManagedEncryptionEnforcement>
        <RestrictionMode>STANDARD_ENCRYPTION_RESTRICTION_MODE</RestrictionMode>
      </GoogleManagedEncryptionEnforcement>
      <CustomerManagedEncryptionEnforcement>
        <RestrictionMode>CMEK_RESTRICTION_MODE</RestrictionMode>
      </CustomerManagedEncryptionEnforcement>
      <CustomerSuppliedEncryptionEnforcement>
        <RestrictionMode>CSEK_RESTRICTION_MODE</RestrictionMode>
      </CustomerSuppliedEncryptionEnforcement>
    </EncryptionConfiguration>

    מחליפים את מה שכתוב בשדות הבאים:

    • STANDARD_ENCRYPTION_RESTRICTION_MODE: האם מותר להשתמש בהצפנה רגילה (הצפנה שמוגדרת כברירת מחדל ב-Google) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש בהצפנה רגילה.
      • FullyRestricted: אי אפשר להשתמש בהצפנה רגילה לאובייקטים חדשים.
    • CMEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות CMEK כשיוצרים אובייקטים בקטגוריה הזו. הערכים הנתמכים:
      • NotRestricted: אפשר להשתמש במפתחות CMEK לאובייקטים חדשים.
      • FullyRestricted: אי אפשר להשתמש במפתחות CMEK באובייקטים חדשים.
    • CSEK_RESTRICTION_MODE: האם מותר להשתמש בהצפנה באמצעות מפתחות הצפנה באספקת הלקוח (CSEK) כשיוצרים אובייקטים בקטגוריה הזו. אלה הערכים הנתמכים:
      • NotRestricted: אובייקטים חדשים יכולים להשתמש במפתחות הצפנה באספקת הלקוח (CSEK).
      • FullyRestricted: אי אפשר להשתמש במפתחות הצפנה באספקת הלקוח (CSEK) לאובייקטים חדשים.

    חובה לאפשר לפחות סוג הצפנה אחד.

  3. משתמשים ב-cURL כדי לשלוח קריאה ל-API בפורמט XML באמצעות בקשת קטגוריה PUT בהיקף של ?encryptionConfig:

    curl -X PUT --data-binary @XML_FILE_NAME \
      -H "Authorization: Bearer $(gcloud auth print-access-token)" \
      "https://storage.googleapis.com/BUCKET_NAME?encryptionConfig"

    מחליפים את מה שכתוב בשדות הבאים:

    • XML_FILE_NAME: הנתיב לקובץ ה-XML שיצרתם בשלב הקודם.
    • BUCKET_NAME: שם הקטגוריה.

    יכול להיות שיחלפו עד שתי דקות עד שההגדרה המעודכנת תיכנס לתוקף.

צפייה בהגדרות ההצפנה של קטגוריה

במאמר קבלת מטא-נתונים של קטגוריה מוסבר איך לראות אילו שיטות הצפנה מותרות לקטגוריה.

המאמרים הבאים