הפניה לשינוי

במאמר הזה מוסבר על הטכניקות הזמינות לביטול הזיהוי, או הטרנספורמציות, ב-Sensitive Data Protection.

סוגים של טכניקות להסרת פרטי הזיהוי

הבחירה של טרנספורמציית הסרת הפרטים המזהים שרוצים להשתמש בה תלויה בסוג הנתונים שרוצים להסיר מהם את הפרטים המזהים ובמטרה שלשמה רוצים להסיר את הפרטים המזהים מהנתונים. טכניקות הסרת הפרטים המזהים שנתמכות ב-Sensitive Data Protection נחלקות לקטגוריות הכלליות הבאות:

  • טשטוש: מחיקה של חלק או של כל ערך רגיש שזוהה.
  • החלפה: החלפה של ערך רגיש שזוהה בערך חלופי שצוין.
  • מיסוך: החלפה של מספר תווים בערך רגיש בתו חלופי שצוין, כמו סולמית (#) או כוכבית (*).
  • טוקניזציה מבוססת-הצפנה: הצפנה של הערך המקורי של מידע אישי רגיש באמצעות מפתח קריפטוגרפי. Sensitive Data Protection תומכת בכמה סוגים של טוקניזציה, כולל טרנספורמציות שאפשר לבטל, או "לשחזר פרטי זיהוי".
  • הצבה בדלי: 'הכללה' של ערך רגיש על ידי החלפתו בטווח ערכים. (לדוגמה, החלפת גיל ספציפי בטווח גילאים, או החלפת טמפרטורות בטווחים שתואמים ל'חם', 'בינוני' ו'קר').
  • הזזת תאריכים: הזזה של ערכי תאריכים רגישים בפרק זמן אקראי.
  • חילוץ זמן: חילוץ או שמירה של חלקים מסוימים של ערכי תאריך ושעה.

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

שיטות טרנספורמציה

בטבלה הבאה מפורטות הטרנספורמציות ש-Sensitive Data Protection מספק כדי להסיר פרטי זיהוי ממידע אישי רגיש:

שינוי אובייקט תיאור Can Reverse1 שלמות רפרנציאלית2 סוג הקלט
צנזורה RedactConfig מצנזרת ערך על ידי הסרתו. הכול
החלפה ReplaceValueConfig הפונקציה מחליפה כל ערך קלט בערך נתון. הכול
החלפה במילון ReplaceDictionaryConfig הפונקציה מחליפה ערך קלט בערך שנבחר באופן אקראי מתוך רשימת מילים. הכול
החלפה ב-infoType ReplaceWithInfoTypeConfig הפונקציה מחליפה ערך קלט בשם של סוג המידע שלו. הכול
מסיכה עם דמות CharacterMaskConfig הפונקציה מסתירה מחרוזת באופן מלא או חלקי על ידי החלפת מספר נתון של תווים בתו קבוע שצוין. הכול
פסאודונימיזציה על ידי החלפת ערך הקלט בגיבוב קריפטוגרפי CryptoHashConfig הפונקציה מחליפה ערכי קלט במחרוזת הקסדצימלית של 32 בייט שנוצרה באמצעות מפתח הצפנה נתון של נתונים. מידע נוסף זמין במאמרי העזרה בנושא פסאודונימיזציה. מחרוזות או מספרים שלמים
פסאודונימיזציה באמצעות החלפה באסימון ששומר על פורמט קריפטוגרפי CryptoReplaceFfxFpeConfig מחליפה ערך קלט באסימון או בערך חלופי באורך זהה באמצעות הצפנה ששומרת על הפורמט (FPE) עם מצב הפעולה FFX. כך אפשר להשתמש בפלט במערכות שכוללות אימות של הפורמט לפי אורך. האפשרות הזו שימושית במערכות מדור קודם שבהן צריך לשמור על אורך המחרוזת. חשוב: אם הקלט משתנה באורך או שאורכו גדול מ-32 בייט, צריך להשתמש ב-CryptoDeterministicConfig. כדי לשמור על אבטחה, מומלץ להשתמש במגבלות הבאות שנקבעו על ידי המכון הלאומי לתקנים ולטכנולוגיה:
  • radix^max_size <= 2^128.
  • radix^min_len >= 100
מחרוזות או מספרים שלמים עם מספר מוגבל של תווים ואורך אחיד. האלפבית צריך לכלול לפחות 2 תווים ולא יותר מ-95 תווים.
פסאודונימיזציה באמצעות החלפה באסימון קריפטוגרפי CryptoDeterministicConfig הפונקציה מחליפה ערך קלט בטוקן או בערך חלופי באורך זהה באמצעות AES במצב וקטור אתחול סינתטי (AES-SIV). בשיטת הטרנספורמציה הזו, בניגוד לטוקניזציה ששומרת על הפורמט, אין הגבלה על ערכות התווים של המחרוזות הנתמכות, נוצרים טוקנים זהים לכל מופע של ערך קלט זהה, והמערכת משתמשת בתחליפים כדי לאפשר זיהוי מחדש בהינתן מפתח ההצפנה המקורי. הכול
הקצאת ערכים לדליים על סמך טווחי גודל קבועים FixedSizeBucketingConfig הפונקציה מחליפה את ערכי הקלט בדליים או בטווחים שבהם ערך הקלט נכלל. הכול
הקצאת ערכים לדלי על סמך טווחי גדלים מותאמים אישית BucketingConfig הפונקציה מחלקת את ערכי הקלט לקבוצות על סמך טווחים שניתנים להגדרה על ידי המשתמש וערכי החלפה. הכול
שינוי התאריך DateShiftConfig הפונקציה משנה את התאריכים במספר אקראי של ימים, עם אפשרות לשמור על עקביות באותו הקשר. ‫✔
שומר על הרצף ועל משך הזמן
תאריכים/שעות
חילוץ נתוני זמן TimePartConfig מחזירה או שומרת חלק מהערכים Date,‏ Timestamp ו-TimeOfDay. תאריכים/שעות

הערות שוליים

‫1 אפשר לבטל טרנספורמציות הפיכות כדי לשחזר פרטי זיהוי של המידע האישי הרגיש באמצעות השיטה content.reidentify.
2 השלמות ההפניה מאפשרת לרשומות לשמור על הקשר ביניהן תוך ביטול האפשרות לזהות את הנתונים. לדוגמה, אם משתמשים באותו מפתח קריפטוגרפי ובאותו הקשר, הנתונים יוחלפו באותו טופס מוסתר בכל פעם שהם יעברו טרנספורמציה, כך שהקשר בין הרשומות יישמר.

צנזורה

אם רוצים פשוט להסיר מידע אישי רגיש מתוכן הקלט, Sensitive Data Protection תומך בטרנספורמציה של צנזור (RedactConfig ב-DLP API).

לדוגמה, נניח שרוצים לבצע צנזורה פשוטה של כל EMAIL_ADDRESS סוגי המידע, והמחרוזת הבאה נשלחת אל Sensitive Data Protection:

My name is Alicia Abernathy, and my email address is aabernathy@example.com.

המחרוזת שתוחזר תהיה:

My name is Alicia Abernathy, and my email address is .

בדוגמה הבאה בפורמט JSON ובקוד בכמה שפות אפשר לראות איך ליצור את בקשת ה-API ומה מוחזר מ-DLP API.

C#

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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


using System;
using System.Collections.Generic;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class DeidentifyDataUsingRedactWithMatchedInputValues
{
    public static DeidentifyContentResponse Deidentify(
        string projectId,
        string text,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the client.
        var dlp = DlpServiceClient.Create();

        // Construct inspect config.
        var inspectConfig = new InspectConfig
        {
            InfoTypes = { infoTypes ?? new InfoType[] { new InfoType { Name = "EMAIL_ADDRESS" } } },
        };

        // Construct redact config.
        var redactConfig = new RedactConfig();

        // Construct deidentify config using redact config.
        var deidentifyConfig = new DeidentifyConfig
        {
            InfoTypeTransformations = new InfoTypeTransformations
            {
                Transformations =
                {
                    new InfoTypeTransformations.Types.InfoTypeTransformation
                    {
                        PrimitiveTransformation = new PrimitiveTransformation
                        {
                            RedactConfig = redactConfig
                        }
                    }
                }
            }
        };

        // Construct a request.
        var request = new DeidentifyContentRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            DeidentifyConfig = deidentifyConfig,
            InspectConfig = inspectConfig,
            Item = new ContentItem { Value = text }
        };

        // Call the API.
        var response = dlp.DeidentifyContent(request);

        // Check the deidentified content.
        Console.WriteLine($"Deidentified content: {response.Item.Value}");
        return response;
    }
}

Go

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// deidentifyWithRedact de-identify the data by redacting with matched input values
func deidentifyWithRedact(w io.Writer, projectID, inputStr string, infoTypeNames []string) error {
	// projectID := "my-project-id"
	// inputStr := "My name is Alicia Abernathy, and my email address is aabernathy@example.com."
	// infoTypeNames := []string{"EMAIL_ADDRESS"}

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err != nil {
		return fmt.Errorf("dlp.NewClient: %w", err)
	}

	// Closing the client safely cleans up background resources.
	defer client.Close()

	// Specify the content to be inspected.
	contentItem := &dlppb.ContentItem{
		DataItem: &dlppb.ContentItem_Value{
			Value: inputStr,
		},
	}

	// Specify the type of info the inspection will look for.
	// See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
	var infoTypes []*dlppb.InfoType
	for _, it := range infoTypeNames {
		infoTypes = append(infoTypes, &dlppb.InfoType{Name: it})
	}
	inspectConfig := &dlppb.InspectConfig{
		InfoTypes: infoTypes,
	}

	// Define type of de-identification.
	primitiveTransformation := &dlppb.PrimitiveTransformation{
		Transformation: &dlppb.PrimitiveTransformation_RedactConfig{
			RedactConfig: &dlppb.RedactConfig{},
		},
	}

	// Associate de-identification type with info type.
	transformation := &dlppb.InfoTypeTransformations_InfoTypeTransformation{
		InfoTypes:               infoTypes,
		PrimitiveTransformation: primitiveTransformation,
	}

	// Construct the configuration for the Redact request and list all desired transformations.
	redactConfig := &dlppb.DeidentifyConfig{
		Transformation: &dlppb.DeidentifyConfig_InfoTypeTransformations{
			InfoTypeTransformations: &dlppb.InfoTypeTransformations{
				Transformations: []*dlppb.InfoTypeTransformations_InfoTypeTransformation{
					transformation,
				},
			},
		},
	}

	// Create a configured request.
	req := &dlppb.DeidentifyContentRequest{
		Parent:           fmt.Sprintf("projects/%s/locations/global", projectID),
		DeidentifyConfig: redactConfig,
		InspectConfig:    inspectConfig,
		Item:             contentItem,
	}

	// Send the request.
	resp, err := client.DeidentifyContent(ctx, req)
	if err != nil {
		return err
	}

	// Print the result.
	fmt.Fprintf(w, "output: %v", resp.GetItem().GetValue())
	return nil
}

Java

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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


import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.ContentItem;
import com.google.privacy.dlp.v2.DeidentifyConfig;
import com.google.privacy.dlp.v2.DeidentifyContentRequest;
import com.google.privacy.dlp.v2.DeidentifyContentResponse;
import com.google.privacy.dlp.v2.InfoType;
import com.google.privacy.dlp.v2.InfoTypeTransformations;
import com.google.privacy.dlp.v2.InfoTypeTransformations.InfoTypeTransformation;
import com.google.privacy.dlp.v2.InspectConfig;
import com.google.privacy.dlp.v2.LocationName;
import com.google.privacy.dlp.v2.PrimitiveTransformation;
import com.google.privacy.dlp.v2.RedactConfig;

public class DeIdentifyWithRedaction {

  public static void main(String[] args) throws Exception {
    // TODO(developer): Replace these variables before running the sample.
    String projectId = "your-project-id";
    String textToInspect =
        "My name is Alicia Abernathy, and my email address is aabernathy@example.com.";
    deIdentifyWithRedaction(projectId, textToInspect);
  }

  // Inspects the provided text.
  public static void deIdentifyWithRedaction(String projectId, String textToRedact) {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests. After completing all of your requests, call
    // the "close" method on the client to safely clean up any remaining background resources.
    try (DlpServiceClient dlp = DlpServiceClient.create()) {
      // Specify the content to be inspected.
      ContentItem item = ContentItem.newBuilder().setValue(textToRedact).build();

      // Specify the type of info the inspection will look for.
      // See https://cloud.google.com/dlp/docs/infotypes-reference for complete list of info types
      InfoType infoType = InfoType.newBuilder().setName("EMAIL_ADDRESS").build();
      InspectConfig inspectConfig = InspectConfig.newBuilder().addInfoTypes(infoType).build();
      // Define type of deidentification.
      PrimitiveTransformation primitiveTransformation =
          PrimitiveTransformation.newBuilder()
              .setRedactConfig(RedactConfig.getDefaultInstance())
              .build();
      // Associate deidentification type with info type.
      InfoTypeTransformation transformation =
          InfoTypeTransformation.newBuilder()
              .addInfoTypes(infoType)
              .setPrimitiveTransformation(primitiveTransformation)
              .build();
      // Construct the configuration for the Redact request and list all desired transformations.
      DeidentifyConfig redactConfig =
          DeidentifyConfig.newBuilder()
              .setInfoTypeTransformations(
                  InfoTypeTransformations.newBuilder().addTransformations(transformation))
              .build();

      // Construct the Redact request to be sent by the client.
      DeidentifyContentRequest request =
          DeidentifyContentRequest.newBuilder()
              .setParent(LocationName.of(projectId, "global").toString())
              .setItem(item)
              .setDeidentifyConfig(redactConfig)
              .setInspectConfig(inspectConfig)
              .build();

      // Use the client to send the API request.
      DeidentifyContentResponse response = dlp.deidentifyContent(request);

      // Parse the response and process results
      System.out.println("Text after redaction: " + response.getItem().getValue());
    } catch (Exception e) {
      System.out.println("Error during inspectString: \n" + e.toString());
    }
  }
}

Node.js

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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

// Imports the Google Cloud Data Loss Prevention library
const DLP = require('@google-cloud/dlp');

// Instantiates a client
const dlp = new DLP.DlpServiceClient();

// TODO(developer): Replace these variables before running the sample.
// const projectId = "your-project-id";

// The string to deidentify
// const string =
//   'My name is Alicia Abernathy, and my email address is aabernathy@example.com.';

// The infoTypes of information to match
// See https://cloud.google.com/dlp/docs/concepts-infotypes for more information
// about supported infoTypes.
// const infoTypes = [{name: 'EMAIL_ADDRESS'}];

async function deIdentifyRedaction() {
  // Construct deidentify configuration
  const deidentifyConfig = {
    infoTypeTransformations: {
      transformations: [
        {
          infoTypes: infoTypes,
          primitiveTransformation: {
            redactConfig: {},
          },
        },
      ],
    },
  };

  // Construct inspect configuration
  const inspectConfig = {
    infoTypes: infoTypes,
  };

  // Construct Item
  const item = {
    value: string,
  };

  // Combine configurations into a request for the service.
  const request = {
    parent: `projects/${projectId}/locations/global`,
    item,
    deidentifyConfig,
    inspectConfig,
  };

  // Send the request and receive response from the service
  const [response] = await dlp.deidentifyContent(request);

  // Print the results
  console.log(`Text after redaction: ${response.item.value}`);
}

deIdentifyRedaction();

PHP

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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

use Google\Cloud\Dlp\V2\Client\DlpServiceClient;
use Google\Cloud\Dlp\V2\ContentItem;
use Google\Cloud\Dlp\V2\DeidentifyConfig;
use Google\Cloud\Dlp\V2\DeidentifyContentRequest;
use Google\Cloud\Dlp\V2\InfoType;
use Google\Cloud\Dlp\V2\InfoTypeTransformations;
use Google\Cloud\Dlp\V2\InfoTypeTransformations\InfoTypeTransformation;
use Google\Cloud\Dlp\V2\InspectConfig;
use Google\Cloud\Dlp\V2\PrimitiveTransformation;
use Google\Cloud\Dlp\V2\RedactConfig;

/**
 * De-identify data: Redacting with matched input values
 * Uses the Data Loss Prevention API to de-identify sensitive data in a string by redacting matched input values.
 *
 * @param string $callingProjectId      The Google Cloud project id to use as a parent resource.
 * @param string $textToInspect         The string to deidentify (will be treated as text).
 */
function deidentify_redact(
    // TODO(developer): Replace sample parameters before running the code.
    string $callingProjectId,
    string $textToInspect = 'My name is Alicia Abernathy, and my email address is aabernathy@example.com.'

): void {
    // Instantiate a client.
    $dlp = new DlpServiceClient();

    // Specify the content to be de-identify.
    $contentItem = (new ContentItem())
        ->setValue($textToInspect);

    // Specify the type of info the inspection will look for.
    $infoType = (new InfoType())
        ->setName('EMAIL_ADDRESS');
    $inspectConfig = (new InspectConfig())
        ->setInfoTypes([$infoType]);

    // Define type of de-identification.
    $primitiveTransformation = (new PrimitiveTransformation())
        ->setRedactConfig(new RedactConfig());

    // Associate de-identification type with info type.
    $transformation = (new InfoTypeTransformation())
        ->setInfoTypes([$infoType])
        ->setPrimitiveTransformation($primitiveTransformation);

    // Construct the configuration for the Redact request and list all desired transformations.
    $deidentifyConfig = (new DeidentifyConfig())
        ->setInfoTypeTransformations((new InfoTypeTransformations())
            ->setTransformations([$transformation]));

    $parent = "projects/$callingProjectId/locations/global";

    // Run request
    $deidentifyContentRequest = (new DeidentifyContentRequest())
        ->setParent($parent)
        ->setDeidentifyConfig($deidentifyConfig)
        ->setInspectConfig($inspectConfig)
        ->setItem($contentItem);
    $response = $dlp->deidentifyContent($deidentifyContentRequest);

    // Print results
    printf('Text after redaction: %s', $response->getItem()->getValue());
}

Python

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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

from typing import List

import google.cloud.dlp


def deidentify_with_redact(
    project: str,
    input_str: str,
    info_types: List[str],
) -> None:
    """Uses the Data Loss Prevention API to deidentify sensitive data in a
    string by redacting matched input values.
    Args:
        project: The Google Cloud project id to use as a parent resource.
        input_str: The string to deidentify (will be treated as text).
        info_types: A list of strings representing info types to look for.
    Returns:
        None; the response from the API is printed to the terminal.
    """

    # Instantiate a client
    dlp = google.cloud.dlp_v2.DlpServiceClient()

    # Convert the project id into a full resource id.
    parent = f"projects/{project}/locations/global"

    # Construct inspect configuration dictionary
    inspect_config = {"info_types": [{"name": info_type} for info_type in info_types]}

    # Construct deidentify configuration dictionary
    deidentify_config = {
        "info_type_transformations": {
            "transformations": [{"primitive_transformation": {"redact_config": {}}}]
        }
    }

    # Construct item
    item = {"value": input_str}

    # Call the API
    response = dlp.deidentify_content(
        request={
            "parent": parent,
            "deidentify_config": deidentify_config,
            "inspect_config": inspect_config,
            "item": item,
        }
    )

    # Print out the results.
    print(response.item.value)

REST

למידע נוסף על שימוש ב-DLP API עם JSON, אפשר לעיין במדריך לתחילת העבודה עם JSON.

ה-method של ה-HTTP וכתובת ה-URL

POST https://dlp.googleapis.com/v2/projects/PROJECT_ID/content:deidentify

מחליפים את PROJECT_ID במזהה הפרויקט.

קלט JSON

{
  "item":{
    "value":"My name is Alicia Abernathy, and my email address is aabernathy@example.com."
  },
  "deidentifyConfig":{
    "infoTypeTransformations":{
      "transformations":[
        {
          "infoTypes":[
            {
              "name":"EMAIL_ADDRESS"
            }
          ],
          "primitiveTransformation":{
            "redactConfig":{
            }
          }
        }
      ]
    }
  },
  "inspectConfig":{
    "infoTypes":[
      {
        "name":"EMAIL_ADDRESS"
      }
    ]
  }
}

פלט מסוג JSON

{
  "item":{
    "value":"My name is Alicia Abernathy, and my email address is ."
  },
  "overview":{
    "transformedBytes":"22",
    "transformationSummaries":[
      {
        "infoType":{
          "name":"EMAIL_ADDRESS"
        },
        "transformation":{
          "redactConfig":{
          }
        },
        "results":[
          {
            "count":"1",
            "code":"SUCCESS"
          }
        ],
        "transformedBytes":"22"
      }
    ]
  }
}

החלפה

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

החלפה בסיסית

הטרנספורמציה הבסיסית של החלפה (ReplaceValueConfig ב-DLP API) מחליפה ערכים של מידע אישי רגיש שזוהו בערך שאתם מציינים. לדוגמה, נניח שהגדרתם ב-Sensitive Data Protection להשתמש בערך [fake@example.com] כדי להחליף את כל ה-infoTypes של EMAIL_ADDRESS שזוהו, והמחרוזת הבאה נשלחת ל-Sensitive Data Protection:

My name is Alicia Abernathy, and my email address is aabernathy@example.com.

המחרוזת שמוחזרת היא:

My name is Alicia Abernathy, and my email address is [fake@example.com].

בדוגמה הבאה בפורמט JSON ובקוד בכמה שפות אפשר לראות איך ליצור את בקשת ה-API ומה מוחזר מ-DLP API.

C#

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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


using System;
using System.Collections.Generic;
using Google.Api.Gax.ResourceNames;
using Google.Cloud.Dlp.V2;

public class DeidentifyWithReplacement
{
    public static DeidentifyContentResponse Deidentify(
        string projectId,
        string text,
        string replaceText = null,
        IEnumerable<InfoType> infoTypes = null)
    {
        // Instantiate the client.
        var dlp = DlpServiceClient.Create();

        // Set the info type if null.
        var infotypes = infoTypes ?? new InfoType[] { new InfoType { Name = "EMAIL_ADDRESS" } };

        // Construct the inspect config.
        var inspectConfig = new InspectConfig
        {
            InfoTypes = { infotypes }
        };

        // Construct the replace value config.
        var replaceConfig = new ReplaceValueConfig
        {
            NewValue = new Value { StringValue = replaceText ?? "[email-address]" }
        };

        // Construct the deidentify config using replace value config.
        var deidentifyConfig = new DeidentifyConfig
        {
            InfoTypeTransformations = new InfoTypeTransformations
            {
                Transformations =
                {
                    new InfoTypeTransformations.Types.InfoTypeTransformation
                    {
                        InfoTypes = { infotypes },
                        PrimitiveTransformation = new PrimitiveTransformation
                        {
                            ReplaceConfig = replaceConfig
                        }
                    }
                },
            }
        };

        // Construct the request.
        var request = new DeidentifyContentRequest
        {
            ParentAsLocationName = new LocationName(projectId, "global"),
            DeidentifyConfig = deidentifyConfig,
            InspectConfig = inspectConfig,
            Item = new ContentItem { Value = text }
        };

        // Call the API.
        var response = dlp.DeidentifyContent(request);

        // Check the deidentified content.
        Console.WriteLine($"Deidentified content: {response.Item.Value}");
        return response;
    }
}

Go

מידע על התקנת ספריית הלקוח של Sensitive Data Protection והשימוש בה מופיע במאמר ספריות הלקוח של Sensitive Data Protection.

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

import (
	"context"
	"fmt"
	"io"

	dlp "cloud.google.com/go/dlp/apiv2"
	"cloud.google.com/go/dlp/apiv2/dlppb"
)

// deidentifyWithReplacement de-identifies sensitive data by replacing matched input values
func deidentifyWithReplacement(w io.Writer, projectID, inputStr string, infoTypeNames []string, replaceVal string) error {
	// projectId := "your-project-id"
	// inputStr := "My name is Alicia Abernathy, and my email address is aabernathy@example.com."
	// infoTypeNames := []string{"EMAIL_ADDRESS"}
	// replaceVal := "[email-address]"

	ctx := context.Background()

	// Initialize a client once and reuse it to send multiple requests. Clients
	// are safe to use across goroutines. When the client is no longer needed,
	// call the Close method to cleanup its resources.
	client, err := dlp.NewClient(ctx)
	if err