De-identify content (v2)

De-identify sensitive information in a text string by masking detected phone numbers and email addresses.

Code sample

Java

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

import com.google.cloud.dlp.v2.DlpServiceClient;
import com.google.privacy.dlp.v2.CharacterMaskConfig;
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.Likelihood;
import com.google.privacy.dlp.v2.PrimitiveTransformation;
import com.google.privacy.dlp.v2.ProjectName;
import java.io.IOException;

public class DeidentifyContent {

  public static void main(String[] args) throws Exception {
    String projectId = "example-project-id";
    deidentifyContent(projectId);
  }

  public static void deidentifyContent(String projectId) throws Exception {
    // Initialize client that will be used to send requests. This client only needs to be created
    // once, and can be reused for multiple requests.
    try (DlpServiceClient client = DlpServiceClient.create()) {
      ContentItem item =
          ContentItem.newBuilder()
              .setValue("My phone number is 206-555-0123 and email is user@example.com")
              .build();

      InspectConfig inspectConfig =
          InspectConfig.newBuilder()
              .addInfoTypes(InfoType.newBuilder().setName("PHONE_NUMBER").build())
              .addInfoTypes(InfoType.newBuilder().setName("EMAIL_ADDRESS").build())
              .setMinLikelihood(Likelihood.POSSIBLE)
              .build();

      CharacterMaskConfig characterMaskConfig =
          CharacterMaskConfig.newBuilder().setMaskingCharacter("*").build();

      PrimitiveTransformation primitiveTransformation =
          PrimitiveTransformation.newBuilder()
              .setCharacterMaskConfig(characterMaskConfig)
              .build();

      InfoTypeTransformation infoTypeTransformation =
          InfoTypeTransformation.newBuilder()
              .setPrimitiveTransformation(primitiveTransformation)
              .build();

      InfoTypeTransformations infoTypeTransformations =
          InfoTypeTransformations.newBuilder()
              .addTransformations(infoTypeTransformation)
              .build();

      DeidentifyConfig deidentifyConfig =
          DeidentifyConfig.newBuilder()
              .setInfoTypeTransformations(infoTypeTransformations)
              .build();

      DeidentifyContentRequest request =
          DeidentifyContentRequest.newBuilder()
              .setParent(ProjectName.of(projectId).toString())
              .setItem(item)
              .setInspectConfig(inspectConfig)
              .setDeidentifyConfig(deidentifyConfig)
              .build();

      DeidentifyContentResponse response = client.deidentifyContent(request);

      System.out.println("De-identified item: " + response.getItem().getValue());
    }
  }
}

Node.js

To learn how to install and use the client library for Sensitive Data Protection, see Sensitive Data Protection client libraries.

To authenticate to Sensitive Data Protection, set up Application Default Credentials. For more information, see Set up authentication for a local development environment.

'use strict';

const {DlpServiceClient} = require('@google-cloud/dlp');
const {status} = require('@grpc/grpc-js');

const client = new DlpServiceClient();

/**
 * Use the deidentifyContent method
 *
 * @param {string} projectId - The Google Cloud project ID to run the de-identification request under.
 */
async function deidentifyContent(projectId) {
  try {
    // Construct the parent resource path
    const parent = `projects/${projectId}`;

    // Define transformation rules to replace sensitive info types
    const transformation = {
      infoTypes: [{name: 'PHONE_NUMBER'}, {name: 'EMAIL_ADDRESS'}],
      primitiveTransformation: {
        replaceConfig: {
          newValue: {stringValue: '[REDACTED]'},
        },
      },
    };

    const deidentifyConfig = {
      infoTypeTransformations: {
        transformations: [transformation],
      },
    };

    const item = {
      value: 'Contact email is employee@example.com and phone is 206-555-0123.',
    };

    const request = {
      parent,
      deidentifyConfig,
      item,
    };

    const [response] = await client.deidentifyContent(request);
    console.log(`De-identified text: ${response.item.value}`);
  } catch (err) {
    if (err.code === status.INVALID_ARGUMENT || err.code === status.PERMISSION_DENIED) {
      console.error(`Google API request error: ${err.message}`);
      return;
    }
    if (err.code !== undefined) {
      console.error(`DLP API error (${err.code}): ${err.message}`);
      return;
    }
    throw err;
  }
}

module.exports = { deidentifyContent };

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.