Melakukan de-identifikasi data sensitif

Sensitive Data Protection dapat melakukan de-identifikasi data sensitif dalam konten teks, termasuk teks yang disimpan dalam struktur penampung seperti tabel. De-identifikasi adalah proses penghapusan informasi identitas pribadi dari data. API mendeteksi data sensitif seperti informasi identitas pribadi (PII), lalu menggunakan transformasi de-identifikasi untuk menyamarkan, menghapus, atau mengaburkan data tersebut. Misalnya, teknik de-identifikasi dapat mencakup salah satu dari hal berikut:

  • Menyamarkan data sensitif dengan mengganti sebagian atau seluruh karakter dengan simbol, seperti tanda bintang (*) atau tanda pagar (#).
  • Mengganti setiap instance data sensitif dengan token, atau string pengganti.
  • Mengenkripsi dan mengganti data sensitif menggunakan kunci yang dibuat secara acak atau telah ditentukan sebelumnya.

Anda dapat memasukkan informasi ke API menggunakan JSON melalui HTTPS, serta CLI dan beberapa bahasa pemrograman menggunakan library klien Sensitive Data Protection. Untuk menyiapkan CLI, lihat panduan memulai. Untuk mengetahui informasi selengkapnya tentang cara mengirimkan informasi dalam format JSON, lihat mulai cepat JSON.

Ringkasan API

Untuk melakukan de-identifikasi data sensitif, gunakan metode content.deidentify Sensitive Data Protection.

Ada tiga bagian untuk panggilan API de-identifikasi:

  • Data yang akan diperiksa: Struktur string atau tabel (objek ContentItem) untuk diperiksa oleh API.
  • Yang harus diperiksa: Informasi konfigurasi deteksi (InspectConfig) seperti jenis data (atau infoType) yang harus dicari, apakah akan memfilter temuan yang berada di atas nilai minimum kemungkinan tertentu, dan apakah akan menampilkan tidak lebih dari jumlah hasil tertentu.

    Dalam objek InspectConfig, pastikan untuk menyertakan infoType yang ingin Anda pindai. Jika tidak, Sensitive Data Protection akan memindai serangkaian infoType default (ALL_BASIC), yang beberapa di antaranya mungkin tidak Anda perlukan. Memindai infoType yang tidak diperlukan dapat menambahkan latensi yang tidak perlu pada permintaan Anda.

    Objek InspectConfig diperlukan dalam permintaan Anda, dengan satu pengecualian. Untuk mengetahui informasi selengkapnya, lihat Merekam transformasi di halaman ini.

  • Tindakan yang harus dilakukan terhadap temuan inspeksi: Informasi konfigurasi (DeidentifyConfig) yang menentukan cara Anda ingin melakukan de-identifikasi data sensitif. Argumen ini dibahas lebih mendetail di bagian berikut.

API menampilkan item yang sama yang Anda berikan, dalam format yang sama, tetapi teks apa pun yang diidentifikasi sebagai berisi informasi sensitif menurut kriteria Anda telah dihilangkan identitasnya.

Menentukan kriteria deteksi

Detektor jenis informasi (atau "infoType") adalah mekanisme yang digunakan Sensitive Data Protection untuk menemukan data sensitif.

Sensitive Data Protection mencakup beberapa jenis detektor infoType, yang semuanya diringkas di sini:

  • Detektor infoType bawaan disertakan dalam Sensitive Data Protection. Detektor ini mencakup jenis data sensitif khusus negara atau wilayah, serta jenis data yang berlaku secara global.
  • Detektor infoType kustom adalah detektor yang Anda buat sendiri. Ada tiga jenis pendeteksi infoType kustom:
    • Pendeteksi kamus kustom reguler adalah daftar kata sederhana yang dicocokkan oleh Sensitive Data Protection. Gunakan pendeteksi kamus kustom reguler jika Anda memiliki daftar hingga beberapa puluh ribu kata atau frasa. Detektor kamus kustom reguler lebih disarankan jika Anda tidak memperkirakan daftar kata Anda akan berubah secara signifikan.
    • Detektor kamus kustom tersimpan dibuat oleh Sensitive Data Protection menggunakan daftar besar kata atau frasa yang disimpan di Cloud Storage atau BigQuery. Gunakan detektor kamus kustom tersimpan jika Anda memiliki daftar kata atau frasa yang besar—hingga puluhan juta.
    • Detektor ekspresi reguler (regex) memungkinkan Sensitive Data Protection mendeteksi kecocokan berdasarkan pola ekspresi reguler.

Untuk menyempurnakan hasil pemindaian, Anda dapat membuat aturan pemeriksaan.

Transformasi de-identifikasi

Anda harus menentukan satu atau beberapa transformasi saat menetapkan konfigurasi de-identifikasi (DeidentifyConfig). Ada dua kategori transformasi:

  • InfoTypeTransformations: Transformasi yang hanya diterapkan pada nilai dalam teks yang dikirimkan yang diidentifikasi sebagai infoType tertentu.
  • RecordTransformations: Transformasi yang hanya diterapkan pada nilai dalam data teks tabular yang dikirimkan yang diidentifikasi sebagai infoType tertentu, atau pada seluruh kolom data tabular.

Transformasi InfoType

Anda dapat menentukan satu atau beberapa transformasi infoType per permintaan. Dalam setiap objek InfoTypeTransformation, Anda menentukan keduanya:

Perhatikan bahwa penentuan infoType bersifat opsional, tetapi tidak menentukan setidaknya satu infoType dalam argumen InspectConfig akan menyebabkan transformasi diterapkan ke semua infoType bawaan yang tidak memiliki transformasi yang diberikan. Tindakan ini tidak direkomendasikan karena dapat menyebabkan penurunan performa dan peningkatan biaya.

Transformasi primitif

Anda harus menentukan setidaknya satu transformasi primitif untuk diterapkan pada input, terlepas dari apakah Anda menerapkannya hanya pada infoType tertentu atau pada seluruh string teks. Bagian berikut menjelaskan contoh metode transformasi yang dapat Anda gunakan. Untuk mengetahui daftar semua metode transformasi yang ditawarkan Sensitive Data Protection, lihat Referensi transformasi.

replaceConfig

Menetapkan replaceConfig ke objek ReplaceValueConfig mengganti nilai input yang cocok dengan nilai yang Anda tentukan.

Misalnya, Anda telah menetapkan replaceConfig ke "[email-address]" untuk semua infoType EMAIL_ADDRESS, dan string berikut dikirim ke Sensitive Data Protection:

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

String yang ditampilkan akan menjadi berikut:

My name is Alicia Abernathy, and my email address is [email-address].

Contoh JSON dan kode berikut dalam beberapa bahasa menunjukkan cara membuat permintaan API dan apa yang ditampilkan DLP API:

Python

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Sensitive Data Protection, lihat library klien Sensitive Data Protection.

Untuk melakukan autentikasi ke Sensitive Data Protection, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

from typing import List

import google.cloud.dlp


def deidentify_with_replace(
    project: str,
    input_str: str,
    info_types: List[str],
    replacement_str: str = "REPLACEMENT_STR",
) -> None:
    """Uses the Data Loss Prevention API to deidentify sensitive data in a
    string by replacing matched input values with a value you specify.
    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.
        replacement_str: The string to replace all values that match given
            info types.
    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": {
                        "replace_config": {
                            "new_value": {"string_value": replacement_str}
                        }
                    }
                }
            ]
        }
    }

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

Java

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Sensitive Data Protection, lihat library klien Sensitive Data Protection.

Untuk melakukan autentikasi ke Sensitive Data Protection, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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.ReplaceValueConfig;
import com.google.privacy.dlp.v2.Value;

public class DeIdentifyWithReplacement {

  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.";
    deIdentifyWithReplacement(projectId, textToInspect);
  }

  // Inspects the provided text.
  public static void deIdentifyWithReplacement(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();
      // Specify replacement string to be used for the finding.
      ReplaceValueConfig replaceValueConfig =
          ReplaceValueConfig.newBuilder()
              .setNewValue(Value.newBuilder().setStringValue("[email-address]").build())
              .build();
      // Define type of deidentification as replacement.
      PrimitiveTransformation primitiveTransformation =
          PrimitiveTransformation.newBuilder().setReplaceConfig(replaceValueConfig).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());
    }
  }
}

REST

Lihat mulai cepat JSON untuk mengetahui informasi selengkapnya tentang penggunaan DLP API dengan JSON.

Input JSON:

POST https://dlp.googleapis.com/v2/projects/[PROJECT_ID]/content:deidentify?key={YOUR_API_KEY}

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

Output JSON:

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

Menentukan redactConfig akan menyamarkan nilai tertentu dengan menghapusnya sepenuhnya. Pesan redactConfig tidak memiliki argumen; menentukannya akan mengaktifkan transformasinya.

Misalnya, Anda telah menentukan redactConfig untuk semua EMAIL_ADDRESS infoType, dan string berikut dikirim ke Sensitive Data Protection:

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

String yang ditampilkan akan menjadi berikut:

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

Contoh berikut menunjukkan cara membuat permintaan API dan apa yang ditampilkan DLP API:

C#

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Sensitive Data Protection, lihat library klien Sensitive Data Protection.

Untuk melakukan autentikasi ke Sensitive Data Protection, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.


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

Untuk mempelajari cara menginstal dan menggunakan library klien untuk Sensitive Data Protection, lihat library klien Sensitive Data Protection.

Untuk melakukan autentikasi ke Sensitive Data Protection, siapkan Kredensial Default Aplikasi. Untuk mengetahui informasi selengkapnya, lihat Menyiapkan autentikasi untuk lingkungan pengembangan lokal.

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
}