Re-identify content (v2)

Re-identify pseudonymized content using a deterministic cryptographic key and a surrogate infoType.

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.ContentItem;
import com.google.privacy.dlp.v2.CryptoDeterministicConfig;
import com.google.privacy.dlp.v2.CryptoKey;
import com.google.privacy.dlp.v2.CustomInfoType;
import com.google.privacy.dlp.v2.DeidentifyConfig;
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.PrimitiveTransformation;
import com.google.privacy.dlp.v2.ReidentifyContentRequest;
import com.google.privacy.dlp.v2.ReidentifyContentResponse;
import com.google.privacy.dlp.v2.UnwrappedCryptoKey;
import com.google.protobuf.ByteString;
import java.util.Base64;

public class ReidentifyContent {

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

  public static void reidentifyContent(String projectId) throws Exception {
    try (DlpServiceClient client = DlpServiceClient.create()) {
      String parent = String.format("projects/%s", projectId);

      // Specify the content containing pseudonymized data
      ContentItem item = ContentItem.newBuilder()
          .setValue("Contact EMAIL_ADDRESS_TOKEN(39):AV30fD78kO9eXfLw==")
          .build();

      // Configure surrogate type detector to locate tokens in the content
      InfoType surrogateInfoType = InfoType.newBuilder()
          .setName("EMAIL_ADDRESS_TOKEN")
          .build();

      CustomInfoType customInfoType = CustomInfoType.newBuilder()
          .setInfoType(surrogateInfoType)
          .setSurrogateType(CustomInfoType.SurrogateType.getDefaultInstance())
          .build();

      InspectConfig inspectConfig = InspectConfig.newBuilder()
          .addCustomInfoTypes(customInfoType)
          .build();

      // AES-256 key matching the key used during de-identification
      byte[] keyBytes = Base64.getDecoder().decode("YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXowMTIzNDU=");
      UnwrappedCryptoKey unwrappedKey = UnwrappedCryptoKey.newBuilder()
          .setKey(ByteString.copyFrom(keyBytes))
          .build();

      CryptoKey cryptoKey = CryptoKey.newBuilder()
          .setUnwrapped(unwrappedKey)
          .build();

      // Configure deterministic decryption transformation
      CryptoDeterministicConfig cryptoDeterministicConfig = CryptoDeterministicConfig.newBuilder()
          .setCryptoKey(cryptoKey)
          .setSurrogateInfoType(surrogateInfoType)
          .build();

      PrimitiveTransformation primitiveTransformation = PrimitiveTransformation.newBuilder()
          .setCryptoDeterministicConfig(cryptoDeterministicConfig)
          .build();

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

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

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

      ReidentifyContentRequest request = ReidentifyContentRequest.newBuilder()
          .setParent(parent)
          .setItem(item)
          .setInspectConfig(inspectConfig)
          .setReidentifyConfig(reidentifyConfig)
          .build();

      ReidentifyContentResponse response = client.reidentifyContent(request);
      System.out.println("Re-identified content: " + 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();

/**
 * Re-identify previously de-identified content using deterministic encryption.
 *
 * @param {string} projectId - The Google Cloud project ID (for example, 'example-project-id')
 */
async function reidentifyContent(projectId) {
  try {
    const parent = `projects/${projectId}`;

    const surrogateInfoType = {
      name: 'EMAIL_ADDRESS_TOKEN',
    };

    // A 128-bit unwrapped AES key used for deterministic encryption and decryption
    const cryptoKey = {
      unwrapped: {
        key: Buffer.from('example-key-128b'),
      },
    };

    const cryptoDeterministicConfig = {
      cryptoKey,
      surrogateInfoType,
    };

    // De-identify the content first to generate a valid encrypted surrogate token
    const deidentifyTransformation = {
      primitiveTransformation: {
        cryptoDeterministicConfig,
      },
      infoTypes: [{name: 'EMAIL_ADDRESS'}],
    };

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

    const deidentifyInspectConfig = {
      infoTypes: [{name: 'EMAIL_ADDRESS'}],
    };

    const [deidentifiedResponse] = await client.deidentifyContent({
      parent,
      deidentifyConfig,
      inspectConfig: deidentifyInspectConfig,
      item: {
        value: 'Contact support at example@example.com',
      },
    });

    // Re-identify the surrogate token back to the original plaintext content
    const reidentifyTransformation = {
      primitiveTransformation: {
        cryptoDeterministicConfig,
      },
      infoTypes: [surrogateInfoType],
    };

    const reidentifyConfig = {
      infoTypeTransformations: {
        transformations: [reidentifyTransformation],
      },
    };

    const reidentifyInspectConfig = {
      customInfoTypes: [
        {
          infoType: surrogateInfoType,
          surrogateType: {},
        },
      ],
    };

    const request = {
      parent,
      reidentifyConfig,
      inspectConfig: reidentifyInspectConfig,
      item: deidentifiedResponse.item,
    };

    const [response] = await client.reidentifyContent(request);
    console.log(`Re-identified content: ${response.item?.value}`);
  } catch (err) {
    if (err.code === status.INVALID_ARGUMENT) {
      console.error(`Invalid argument provided: ${err.message}`);
    } else if (err.code === status.PERMISSION_DENIED) {
      console.error(`Permission denied: ${err.message}`);
    } else if (err.code === status.NOT_FOUND) {
      console.error(`Resource not found: ${err.message}`);
    } else if (typeof err.code === 'number') {
      console.error(`API error with gRPC status code ${err.code}: ${err.message}`);
    } else {
      throw err;
    }
  }
}

module.exports = { reidentifyContent };

Python

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 google.api_core.exceptions
from google.cloud import dlp_v2

client = dlp_v2.DlpServiceClient()


def reidentify_content(project_id: str) -> None:
    """Use the reidentify_content method

    Args:
        project_id: The Google Cloud project ID.
    """
    parent = f"projects/{project_id}"

    # Configure the surrogate info type used during de-identification
    surrogate_info_type = dlp_v2.InfoType(name="EMAIL_TOKEN")
    inspect_config = dlp_v2.InspectConfig(
        custom_info_types=[
            dlp_v2.CustomInfoType(
                info_type=surrogate_info_type,
                surrogate_type=dlp_v2.CustomInfoType.SurrogateType(),
            )
        ]
    )

    # Configure the deterministic decryption parameters
    crypto_key = dlp_v2.CryptoKey(
        unwrapped=dlp_v2.UnwrappedCryptoKey(
            key=b"example-key-32-bytes-length-1234"
        )
    )
    crypto_deterministic_config = dlp_v2.CryptoDeterministicConfig(
        crypto_key=crypto_key,
        surrogate_info_type=surrogate_info_type,
    )
    primitive_transformation = dlp_v2.PrimitiveTransformation(
        crypto_deterministic_config=crypto_deterministic_config
    )
    transformation = dlp_v2.InfoTypeTransformations.InfoTypeTransformation(
        primitive_transformation=primitive_transformation
    )
    reidentify_config = dlp_v2.DeidentifyConfig(
        info_type_transformations=dlp_v2.InfoTypeTransformations(
            transformations=[transformation]
        )
    )

    # Encrypted token data to be re-identified
    item = dlp_v2.ContentItem(value="EMAIL_TOKEN(52):AY2x9yL7v0n0zD1Q==")

    request = dlp_v2.ReidentifyContentRequest(
        parent=parent,
        reidentify_config=reidentify_config,
        inspect_config=inspect_config,
        item=item,
    )

    try:
        response = client.reidentify_content(request=request)
        print(f"Re-identified content: {response.item.value}")
    except google.api_core.exceptions.GoogleAPICallError as exc:
        print(f"Failed to re-identify content: {exc}")

What's next

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