Menu Docs
Página inicial do Docs
/
Manual do MongoDB
/ / / / /

Use a criptografia no nível do campo automática no lado do cliente com Azure

Nesta página

  • Visão geral
  • Antes de começar
  • Configurar o KMS
  • Registre seu aplicativo com o Azure
  • Criar a Chave Mestre do Cliente
  • Criar o aplicativo
  • Crie um índice único em sua coleção do Key Vault
  • Criar uma nova chave de criptografia de dados
  • Configure o MongoClient
  • Inserir um documento com campos criptografados
  • Recupere seu documento criptografado
  • Saiba mais

Este guia mostra como criar um aplicativo habilitado para criptografia de nível de campo (CSFLE) do lado do cliente usando o Azure Key Vault.

Depois de concluir as etapas deste guia, você deverá ter:

  • Uma chave mestra do cliente hospedada em uma instância do Azure Key Vault.

  • Uma aplicação funcional que insere documento criptografados usando sua chave mestra do cliente.

Para concluir e executar o código neste guia, você precisa configurar seu ambiente de desenvolvimento como mostrado na páginaRequisitos de instalação do .

Neste guia, os exemplos de código usam texto de espaço reservado. Antes de executar os exemplos, substitua seus valores por esses espaços reservados.

Por exemplo:

dek_id := "<Your Base64 DEK ID>"

Você substituiria tudo entre aspas pelo seu DEK ID.

dek_id := "abc123"

Selecione a linguagem de programação para a qual você deseja ver exemplos de código no menu suspenso Select your language no lado direito da página.

Dica

Veja: Aplicação Completa

Para ver o código completo do aplicativo executável deste tutorial, acesse o link a seguir:

Aplicativo C# completo

// You are viewing the C# driver code examples.
// Use the dropdown menu to select a different driver.
// You are viewing the Golang driver code examples.
// Use the dropdown menu to select a different driver.
// You are viewing the Java synchronous driver code examples.
// Use the dropdown menu to select a different driver.
// You are viewing the Node.js driver code examples.
// Use the dropdown menu to select a different driver.
# You are viewing the Python driver code examples.
# Use the dropdown menu to select a different driver.
1
1
2

Para registrar um aplicativo no Azure Active Directory, siga o guia oficial da Microsoft. Registre um aplicativo na plataforma de identidade da Microsoft Início rápido.

Importante

Registre suas Credenciais

Certifique-se de registrar as seguintes credenciais:

  • ID do Inquilino

  • ID do cliente

  • segredo do cliente

Você precisará delas para construir seu objeto kmsProviders mais tarde neste tutorial.

2
1

Para criar uma nova instância do Azure Key Vault e uma chave mestra do cliente, siga o conjunto oficial da Microsoft e recupere uma chave do Azure Key Vault usando o portal do Azure Início rápido.

Observação

A chave mestra do cliente deve ter um tamanho de chave RSA de 2048 ou 4096 bits.

Importante

Registre suas Credenciais

Certifique-se de registrar as seguintes credenciais:

  • Nome da chave

  • Identificador de chave (referido como keyVaultEndpoint mais adiante neste guia)

  • keyVersion

Você precisará deles para construir seu objeto dataKeyOpts mais tarde neste tutorial.

2

Conceda ao seu aplicativo cliente permissões wrap e unwrap para a chave.

1

Crie um índice único no campo keyAltNames na sua collection encryption.__keyVault .

Selecione a guia correspondente ao driver MongoDB de sua preferência:

MarqueDataKey.cs
var connectionString = "<Your MongoDB URI>";
var keyVaultNamespace = CollectionNamespace.FromFullName("encryption.__keyVault");
var keyVaultClient = new MongoClient(connectionString);
var indexOptions = new CreateIndexOptions<BsonDocument>();
indexOptions.Unique = true;
indexOptions.PartialFilterExpression = new BsonDocument { { "keyAltNames", new BsonDocument { { "$exists", new BsonBoolean(true) } } } };
var builder = Builders<BsonDocument>.IndexKeys;
var indexKeysDocument = builder.Ascending("keyAltNames");
var indexModel = new CreateIndexModel<BsonDocument>(indexKeysDocument, indexOptions);
var keyVaultDatabase = keyVaultClient.GetDatabase(keyVaultNamespace.DatabaseNamespace.ToString());
// Drop the Key Vault Collection in case you created this collection
// in a previous run of this application.
keyVaultDatabase.DropCollection(keyVaultNamespace.CollectionName);
// Drop the database storing your encrypted fields as all
// the DEKs encrypting those fields were deleted in the preceding line.
keyVaultClient.GetDatabase("medicalRecords").DropCollection("patients");
var keyVaultCollection = keyVaultDatabase.GetCollection<BsonDocument>(keyVaultNamespace.CollectionName.ToString());
keyVaultCollection.Indexes.CreateOne(indexModel);
insert-encrypted-document.go
uri := "<Your MongoDB URI>"
keyVaultClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri))
if err != nil {
return fmt.Errorf("Connect error for regular client: %v", err)
}
defer func() {
_ = keyVaultClient.Disconnect(context.TODO())
}()
keyVaultColl := "__keyVault"
keyVaultDb := "encryption"
keyVaultNamespace := keyVaultDb + "." + keyVaultColl
keyVaultIndex := mongo.IndexModel{
Keys: bson.D{{"keyAltNames", 1}},
Options: options.Index().
SetUnique(true).
SetPartialFilterExpression(bson.D{
{"keyAltNames", bson.D{
{"$exists", true},
}},
}),
}
// Drop the Key Vault Collection in case you created this collection
// in a previous run of this application.
if err = keyVaultClient.Database(keyVaultDb).Collection(keyVaultColl).Drop(context.TODO()); err != nil {
log.Fatalf("Collection.Drop error: %v", err)
}
// Drop the database storing your encrypted fields as all
// the DEKs encrypting those fields were deleted in the preceding line.
if err = keyVaultClient.Database("medicalRecords").Collection("patients").Drop(context.TODO()); err != nil {
log.Fatalf("Collection.Drop error: %v", err)
}
_, err = keyVaultClient.Database(keyVaultDb).Collection(keyVaultColl).Indexes().CreateOne(context.TODO(), keyVaultIndex)
if err != nil {
panic(err)
}
MakeDataKey.java
String connectionString = "<Your MongoDB URI>";
String keyVaultDb = "encryption";
String keyVaultColl = "__keyVault";
String keyVaultNamespace = keyVaultDb + "." + keyVaultColl;
MongoClient keyVaultClient = MongoClients.create(connectionString);
// Drop the Key Vault Collection in case you created this collection
// in a previous run of this application.
keyVaultClient.getDatabase(keyVaultDb).getCollection(keyVaultColl).drop();
// Drop the database storing your encrypted fields as all
// the DEKs encrypting those fields were deleted in the preceding line.
keyVaultClient.getDatabase("medicalRecords").getCollection("patients").drop();
MongoCollection keyVaultCollection = keyVaultClient.getDatabase(keyVaultDb).getCollection(keyVaultColl);
IndexOptions indexOpts = new IndexOptions().partialFilterExpression(new BsonDocument("keyAltNames", new BsonDocument("$exists", new BsonBoolean(true) ))).unique(true);
keyVaultCollection.createIndex(new BsonDocument("keyAltNames", new BsonInt32(1)), indexOpts);
keyVaultClient.close();
get_data_key.js
const uri = "<Your Connection String>";
const keyVaultDatabase = "encryption";
const keyVaultCollection = "__keyVault";
const keyVaultNamespace = `${keyVaultDatabase}.${keyVaultCollection}`;
const keyVaultClient = new MongoClient(uri);
await keyVaultClient.connect();
const keyVaultDB = keyVaultClient.db(keyVaultDatabase);
// Drop the Key Vault Collection in case you created this collection
// in a previous run of this application.
await keyVaultDB.dropDatabase();
// Drop the database storing your encrypted fields as all
// the DEKs encrypting those fields were deleted in the preceding line.
await keyVaultClient.db("medicalRecords").dropDatabase();
const keyVaultColl = keyVaultDB.collection(keyVaultCollection);
await keyVaultColl.createIndex(
{ keyAltNames: 1 },
{
unique: true,
partialFilterExpression: { keyAltNames: { $exists: true } },
}
);
create_data_key.py
connection_string = "<your connection string here>"
key_vault_coll = "__keyVault"
key_vault_db = "encryption"
key_vault_namespace = f"{key_vault_db}.{key_vault_coll}"
key_vault_client = MongoClient(connection_string)
# Drop the Key Vault Collection in case you created this collection
# in a previous run of this application.
key_vault_client.drop_database(key_vault_db)
# Drop the database storing your encrypted fields as all
# the DEKs encrypting those fields were deleted in the preceding line.
key_vault_client["medicalRecords"].drop_collection("patients")
key_vault_client[key_vault_db][key_vault_coll].create_index(
[("keyAltNames", ASCENDING)],
unique=True,
partialFilterExpression={"keyAltNames": {"$exists": True}},
)
2
1

Adicione as credenciais da conta de serviço ao código do cliente habilitado para CSFLE.

Dica

Você registrou suas credenciais do Azure Key Vault na etapa Registrar seu Aplicativo no Azure deste guia.

MarqueDataKey.cs
var kmsProviders = new Dictionary<string, IReadOnlyDictionary<string, object>>();
var provider = "azure";
var azureKmsOptions = new Dictionary<string, object>
{
{ "tenantId", "<Your Azure Tenant ID>" },
{ "clientId", "<Your Azure Client ID>" },
{ "clientSecret", "<Your Azure Client Secret>" },
};
make-data-key.go
provider := "azure"
kmsProviders := map[string]map[string]interface{}{
provider: {
"tenantId": "<Your Azure Tenant ID>",
"clientId": "<Your Azure Client ID>",
"clientSecret": "<Your Azure Client Secret>",
},
}
MakeDataKey.java
String kmsProvider = "azure";
Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>();
Map<String, Object> providerDetails = new HashMap<>();
providerDetails.put("tenantId", "<Azure account organization>");
providerDetails.put("clientId", "<Azure client ID>");
providerDetails.put("clientSecret", "<Azure client secret>");
kmsProviders.put(kmsProvider, providerDetails);
get_data_key.js
const provider = "azure";
const kmsProviders = {
azure: {
tenantId: "<Your Tenant ID>",
clientId: "<Your Client ID>",
clientSecret: "<Your Client Secret>",
},
};
create_data_key.py
provider = "azure"
kms_providers = {
provider: {
"tenantId": "<Azure account organization>",
"clientId": "<Azure client ID>",
"clientSecret": "<Azure client secret>",
}
}

Dica

Saiba mais

Para saber mais sobre o objeto do provedor de KMS para o Azure Key Vault, consulte Azure Key Vault.

2

Atualize o seguinte código para especificar sua Chave Mestre do Cliente:

Dica

Você registrou o ARN e a região da chave mestra do cliente na etapa Criar uma chave mestra do cliente deste guia.

MarqueDataKey.cs
kmsProviders.Add(provider, azureKmsOptions);
var dataKeyOptions = new DataKeyOptions(
masterKey: new BsonDocument
{
{ "keyName", "<Your Azure Key Name>" },
{ "keyVaultEndpoint", "<Your Azure Key Vault Endpoint>" },
});
make-data-key.go
masterKey := map[string]interface{}{
"keyVaultEndpoint": "<Your Azure Key Vault Endpoint>",
"keyName": "<Your Azure Key Name>",
}
MakeDataKey.java
BsonDocument masterKeyProperties = new BsonDocument();
masterKeyProperties.put("provider", new BsonString(kmsProvider));
masterKeyProperties.put("keyName", new BsonString("<Azure key name>"));
masterKeyProperties.put("keyVaultEndpoint", new BsonString("<Azure key vault endpoint"));
get_data_key.js
const masterKey = {
keyVaultEndpoint: "<Your Key Vault Endpoint>",
keyName: "<Your Key Name>",
};
create_data_key.py
master_key = {
"keyName": "<Azure key name>",
"keyVersion": "<Azure key version>",
"keyVaultEndpoint": "<Azure key vault endpoint/key identifier>",
}
3
MarqueDataKey.cs
var clientEncryptionOptions = new ClientEncryptionOptions(
keyVaultClient: keyVaultClient,
keyVaultNamespace: keyVaultNamespace,
kmsProviders: kmsProviders
);
var clientEncryption = new ClientEncryption(clientEncryptionOptions);
var dataKeyId = clientEncryption.CreateDataKey(provider, dataKeyOptions, CancellationToken.None);
var dataKeyIdBase64 = Convert.ToBase64String(GuidConverter.ToBytes(dataKeyId, GuidRepresentation.Standard));
Console.WriteLine($"DataKeyId [base64]: {dataKeyIdBase64}");
make-data-key.go
clientEncryptionOpts := options.ClientEncryption().SetKeyVaultNamespace(keyVaultNamespace).
SetKmsProviders(kmsProviders)
clientEnc, err := mongo.NewClientEncryption(keyVaultClient, clientEncryptionOpts)
if err != nil {
return fmt.Errorf("NewClientEncryption error %v", err)
}
defer func() {
_ = clientEnc.Close(context.TODO())
}()
dataKeyOpts := options.DataKey().
SetMasterKey(masterKey)
dataKeyID, err := clientEnc.CreateDataKey(context.TODO(), provider, dataKeyOpts)
if err != nil {
return fmt.Errorf("create data key error %v", err)
}
fmt.Printf("DataKeyId [base64]: %s\n", base64.StdEncoding.EncodeToString(dataKeyID.Data))
MakeDataKey.java
ClientEncryptionSettings clientEncryptionSettings = ClientEncryptionSettings.builder()
.keyVaultMongoClientSettings(MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString))
.build())
.keyVaultNamespace(keyVaultNamespace)
.kmsProviders(kmsProviders)
.build();
MongoClient regularClient = MongoClients.create(connectionString);
ClientEncryption clientEncryption = ClientEncryptions.create(clientEncryptionSettings);
BsonBinary dataKeyId = clientEncryption.createDataKey(kmsProvider, new DataKeyOptions().masterKey(masterKeyProperties));
String base64DataKeyId = Base64.getEncoder().encodeToString(dataKeyId.getData());
System.out.println("DataKeyId [base64]: " + base64DataKeyId);
clientEncryption.close();
get_data_key.js
const client = new MongoClient(uri, {
useNewUrlParser: true,
useUnifiedTopology: true,
});
await client.connect();
const encryption = new ClientEncryption(client, {
keyVaultNamespace,
kmsProviders,
});
const key = await encryption.createDataKey(provider, {
masterKey: masterKey,
});
console.log("DataKeyId [base64]: ", key.toString("base64"));
await keyVaultClient.close();
await client.close();
create_data_key.py
key_vault_database = "encryption"
key_vault_collection = "__keyVault"
key_vault_namespace = f"{key_vault_database}.{key_vault_collection}"
client = MongoClient(connection_string)
client_encryption = ClientEncryption(
kms_providers, # pass in the kms_providers variable from the previous step
key_vault_namespace,
client,
CodecOptions(uuid_representation=STANDARD),
)
data_key_id = client_encryption.create_data_key(provider, master_key)
base_64_data_key_id = base64.b64encode(data_key_id)
print("DataKeyId [base64]: ", base_64_data_key_id)

Dica

Saiba mais

Para ver um diagrama que mostra como o aplicativo cliente cria a chave de encriptação de dados ao usar o Azure Key Vault, consulte Arquitetura.

Para saber mais sobre as opções de criação de uma Chave de criptografia de dados criptografada com uma Chave Mestre do Cliente hospedada no Azure Key Vault, consulte Objeto kmsProviders e Objeto dataKeyOpts.

Dica

Veja: Código Completo

Para visualizar o código completo para criar uma Chave de criptografia de dados, consulte nosso repositório Github

Para visualizar o código completo para criar uma Chave de Criptografia de Dados, consulte nosso repositório Github.

Para visualizar o código completo para criar uma Chave de Criptografia de Dados, consulte nosso repositório Github.

Para visualizar o código completo para criar uma Chave de Criptografia de Dados, consulte nosso repositório Github.

Para visualizar o código completo para criar uma Chave de Criptografia de Dados, consulte nosso repositório Github.

3
1

Especifique encryption.__keyVault como o namespace da coleção Key Vault.

InsertEncryptedDocument.cs
var keyVaultNamespace = CollectionNamespace.FromFullName("encryption.__keyVault");
insert-encrypted-document.go
keyVaultNamespace := "encryption.__keyVault"
InsertEncryptedDocument.java
String keyVaultNamespace = "encryption.__keyVault";
insert_encrypted_document.js
const keyVaultNamespace = "encryption.__keyVault";
insert_encrypted_document.py
key_vault_namespace = "encryption.__keyVault"
2

Especifique o provedor de KMS do azure e suas credenciais do Azure:

InsertEncryptedDocument.cs
var kmsProviders = new Dictionary<string, IReadOnlyDictionary<string, object>>();
var provider = "azure";
var azureKmsOptions = new Dictionary<string, object>
{
{ "tenantId", "<Your Azure Tenant ID>" },
{ "clientId", "<Your Azure Client ID>" },
{ "clientSecret", "<Your Azure Client Secret>" },
};
kmsProviders.Add(provider, azureKmsOptions);
insert-encrypted-document.go
kmsProviders := map[string]map[string]interface{}{
"azure": {
"tenantId": "<Your Azure Tenant ID>",
"clientId": "<Your Azure Client ID>",
"clientSecret": "<Your Azure Client Secret>",
},
}
InsertEncryptedDocument.java
String kmsProvider = "azure";
Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>();
Map<String, Object> providerDetails = new HashMap<>();
providerDetails.put("tenantId", "<Azure account organization>");
providerDetails.put("clientId", "<Azure client ID>");
providerDetails.put("clientSecret", "<Azure client secret>");
kmsProviders.put(kmsProvider, providerDetails);
insert_encrypted_document.js
const kmsProviders = {
azure: {
tenantId: "<Your Tenant ID>",
clientId: "<Your Client ID>",
clientSecret: "<Your Client Secret>",
},
};
insert_encrypted_document.py
provider = "azure"
kms_providers = {
"azure": {
"tenantId": "<Azure account organization>",
"clientId": "<Azure client ID>",
"clientSecret": "<Azure client secret>",
}
}
3

Dica

Adicione sua chave de encriptação de dados ID Base64

Certifique-se de atualizar o seguinte código para incluir seu ID Base64 DEK . Você recebeu esse valor na etapa Gerar sua chave de criptografia de dados deste guia.

InsertEncryptedDocument.cs
var keyId = "<Your base64 DEK ID here>";
var schema = new BsonDocument
{
{ "bsonType", "object" },
{
"encryptMetadata",
new BsonDocument("keyId", new BsonArray(new[] { new BsonBinaryData(Convert.FromBase64String(keyId), BsonBinarySubType.UuidStandard) }))
},
{
"properties",
new BsonDocument
{
{
"ssn", new BsonDocument
{
{
"encrypt", new BsonDocument
{
{ "bsonType", "int" },
{ "algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" }
}
}
}
},
{
"bloodType", new BsonDocument
{
{
"encrypt", new BsonDocument
{
{ "bsonType", "string" },
{ "algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Random" }
}
}
}
},
{
"medicalRecords", new BsonDocument
{
{
"encrypt", new BsonDocument
{
{ "bsonType", "array" },
{ "algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Random" }
}
}
}
},
{
"insurance", new BsonDocument
{
{ "bsonType", "object" },
{
"properties", new BsonDocument
{
{
"policyNumber", new BsonDocument
{
{
"encrypt", new BsonDocument
{
{ "bsonType", "int" },
{ "algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic" }
}
}
}
}
}
}
}
}
}
}
};
var schemaMap = new Dictionary<string, BsonDocument>();
schemaMap.Add(dbNamespace, schema);
insert-encrypted-document.go
dek_id := "<Your Base64 DEK ID>"
schema_template := `{
"bsonType": "object",
"encryptMetadata": {
"keyId": [
{
"$binary": {
"base64": "%s",
"subType": "04"
}
}
]
},
"properties": {
"insurance": {
"bsonType": "object",
"properties": {
"policyNumber": {
"encrypt": {
"bsonType": "int",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
}
}
}
},
"medicalRecords": {
"encrypt": {
"bsonType": "array",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
}
},
"bloodType": {
"encrypt": {
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random"
}
},
"ssn": {
"encrypt": {
"bsonType": "int",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"
}
}
}
}`
schema := fmt.Sprintf(schema_template, dek_id)
var schemaDoc bson.Raw
if err := bson.UnmarshalExtJSON([]byte(schema), true, &schemaDoc); err != nil {
return fmt.Errorf("UnmarshalExtJSON error: %v", err)
}
schemaMap := map[string]interface{}{
dbName + "." + collName: schemaDoc,
}
InsertEncryptedDocument.java
String dekId = "<paste-base-64-encoded-data-encryption-key-id>>";
Document jsonSchema = new Document().append("bsonType", "object").append("encryptMetadata",
new Document().append("keyId", new ArrayList<>((Arrays.asList(new Document().append("$binary", new Document()
.append("base64", dekId)
.append("subType", "04")))))))
.append("properties", new Document()
.append("ssn", new Document().append("encrypt", new Document()
.append("bsonType", "int")
.append("algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic")))
.append("bloodType", new Document().append("encrypt", new Document()
.append("bsonType", "string")
.append("algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Random")))
.append("medicalRecords", new Document().append("encrypt", new Document()
.append("bsonType", "array")
.append("algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Random")))
.append("insurance", new Document()
.append("bsonType", "object")
.append("properties",
new Document().append("policyNumber", new Document().append("encrypt", new Document()
.append("bsonType", "int")
.append("algorithm", "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic"))))));
HashMap<String, BsonDocument> schemaMap = new HashMap<String, BsonDocument>();
schemaMap.put("medicalRecords.patients", BsonDocument.parse(jsonSchema.toJson()));
insert_encrypted_document.js
dataKey = "<Your base64 DEK ID>";
const schema = {
bsonType: "object",
encryptMetadata: {
keyId: [new Binary(Buffer.from(dataKey, "base64"), 4)],
},
properties: {
insurance: {
bsonType: "object",
properties: {
policyNumber: {
encrypt: {
bsonType: "int",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
},
},
},
},
medicalRecords: {
encrypt: {
bsonType: "array",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
},
},
bloodType: {
encrypt: {
bsonType: "string",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
},
},
ssn: {
encrypt: {
bsonType: "int",
algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
},
},
},
};
var patientSchema = {};
patientSchema[namespace] = schema;
insert_encrypted_document.py
dek_id = b"<paste-base-64-encoded-data-encryption-key-id>"
json_schema = {
"bsonType": "object",
"encryptMetadata": {"keyId": [Binary(base64.b64decode(dek_id), UUID_SUBTYPE)]},
"properties": {
"insurance": {
"bsonType": "object",
"properties": {
"policyNumber": {
"encrypt": {
"bsonType": "int",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
}
}
},
},
"medicalRecords": {
"encrypt": {
"bsonType": "array",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
}
},
"bloodType": {
"encrypt": {
"bsonType": "string",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Random",
}
},
"ssn": {
"encrypt": {
"bsonType": "int",
"algorithm": "AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic",
}
},
},
}
patient_schema = {"medicalRecords.patients": json_schema}
patient_schema = {"medicalRecords.patients": json_schema}
4
InsertEncryptedDocument.cs
var mongoBinariesPath = "<Full path to your Automatic Encryption Shared Library>";
var extraOptions = new Dictionary<string, object>()
{
{ "cryptSharedLibPath", mongoBinariesPath },
};
insert-encrypted-document.go
extraOptions := map[string]interface{}{
"cryptSharedLibPath": "<Full path to your Automatic Encryption Shared Library>",
}
InsertEncryptedDocument.java
Map<String, Object> extraOptions = new HashMap<String, Object>();
extraOptions.put("cryptSharedLibPath", "<Full path to your Automatic Encryption Shared Library>"));
insert_encrypted_document.js
const extraOptions = {
cryptSharedLibPath: "<Full path to your Automatic Encryption Shared Library>",
};
insert_encrypted_document.py
extra_options = {
"cryptSharedLibPath": "<Full path to your Automatic Encryption Shared Library>"
}

Observação

Opções de criptografia automática

As opções de criptografia automática fornecem informações de configuração para a Biblioteca compartilhada de criptografia automática, que modifica o comportamento do aplicativo ao acessar campos criptografados.

Para saber mais sobre a Biblioteca compartilhada de criptografia automática, consulte a página Biblioteca compartilhada de criptografia automática para CSFLE.

5

Instale instantaneamente um objeto de cliente MongoDB com as seguintes configurações de criptografia automática:

InsertEncryptedDocument.cs
var clientSettings = MongoClientSettings.FromConnectionString(connectionString);
var autoEncryptionOptions = new AutoEncryptionOptions(
keyVaultNamespace: keyVaultNamespace,
kmsProviders: kmsProviders,
schemaMap: schemaMap,
extraOptions: extraOptions
);
clientSettings.AutoEncryptionOptions = autoEncryptionOptions;
var secureClient = new MongoClient(clientSettings);
insert-encrypted-document.go
autoEncryptionOpts := options.AutoEncryption().
SetKmsProviders(kmsProviders).
SetKeyVaultNamespace(keyVaultNamespace).
SetSchemaMap(schemaMap).
SetExtraOptions(extraOptions)
secureClient, err := mongo.Connect(context.TODO(), options.Client().ApplyURI(uri).SetAutoEncryptionOptions(autoEncryptionOpts))
if err != nil {
return fmt.Errorf("Connect error for encrypted client: %v", err)
}
defer func() {
_ = secureClient.Disconnect(context.TODO())
}()
InsertEncryptedDocument.java
MongoClientSettings clientSettings = MongoClientSettings.builder()
.applyConnectionString(new ConnectionString(connectionString))
.autoEncryptionSettings(AutoEncryptionSettings.builder()
.keyVaultNamespace(keyVaultNamespace)
.kmsProviders(kmsProviders)
.schemaMap(schemaMap)
.extraOptions(extraOptions)
.build())
.build();
MongoClient mongoClientSecure = MongoClients.create(clientSettings);
insert_encrypted_document.js
const secureClient = new MongoClient(connectionString, {
useNewUrlParser: true,
useUnifiedTopology: true,
autoEncryption: {
keyVaultNamespace,
kmsProviders,
schemaMap: patientSchema,
extraOptions: extraOptions,
},
});
insert_encrypted_document.py
fle_opts = AutoEncryptionOpts(
kms_providers, key_vault_namespace, schema_map=patient_schema, **extra_options
)
secureClient = MongoClient(connection_string, auto_encryption_opts=fle_opts)
4

Use sua instância de MongoClient habilitada para CSFLE para inserir um documento criptografado no namespace medicalRecords.patients usando o seguinte trecho de código:

InsertEncryptedDocument.cs
var sampleDocFields = new BsonDocument
{
{ "name", "Jon Doe" },
{ "ssn", 145014000 },
{ "bloodType", "AB-" },
{
"medicalRecords", new BsonArray
{
new BsonDocument("weight", 180),
new BsonDocument("bloodPressure", "120/80")
}
},
{
"insurance", new BsonDocument
{
{ "policyNumber", 123142 },
{ "provider", "MaestCare" }
}
}
};
// Construct an auto-encrypting client
var secureCollection = secureClient.GetDatabase(db).GetCollection<BsonDocument>(coll);
// Insert a document into the collection
secureCollection.InsertOne(sampleDocFields);
insert-encrypted-document.go
test_patient := map[string]interface{}{
"name": "Jon Doe",
"ssn": 241014209,
"bloodType": "AB+",
"medicalRecords": []map[string]interface{}{{
"weight": 180,
"bloodPressure": "120/80",
}},
"insurance": map[string]interface{}{
"provider": "MaestCare",
"policyNumber": 123142,
},
}
if _, err := secureClient.Database(dbName).Collection(collName).InsertOne(context.TODO(), test_patient); err != nil {
return fmt.Errorf("InsertOne error: %v", err)
}

Observação

Em vez de criar um documento BSON bruto, você pode passar uma estrutura com marcações bson diretamente para o driver para codificação.

InsertEncryptedDocument.java
ArrayList<Document> medicalRecords = new ArrayList<>();
medicalRecords.add(new Document().append("weight", "180"));
medicalRecords.add(new Document().append("bloodPressure", "120/80"));
Document insurance = new Document()
.append("policyNumber", 123142)
.append("provider", "MaestCare");
Document patient = new Document()
.append("name", "Jon Doe")
.append("ssn", 241014209)
.append("bloodType", "AB+")
.append("medicalRecords", medicalRecords)
.append("insurance", insurance);
mongoClientSecure.getDatabase(recordsDb).getCollection(recordsColl).insertOne(patient);
insert_encrypted_document.js
try {
const writeResult = await secureClient
.db(db)
.collection(coll)
.insertOne({
name: "Jon Doe",
ssn: 241014209,
bloodType: "AB+",
medicalRecords: [{ weight: 180, bloodPressure: "120/80" }],
insurance: {
policyNumber: 123142,
provider: "MaestCare",
},
});
} catch (writeError) {
console.error("writeError occurred:", writeError);
}
insert_encrypted_document.py
def insert_patient(
collection, name, ssn, blood_type, medical_records, policy_number, provider
):
insurance = {"policyNumber": policy_number, "provider": provider}
doc = {
"name": name,
"ssn": ssn,
"bloodType": blood_type,
"medicalRecords": medical_records,
"insurance": insurance,
}
collection.insert_one(doc)
medical_record = [{"weight": 180, "bloodPressure": "120/80"}]
insert_patient(
secureClient.medicalRecords.patients,
"Jon Doe",
241014209,
"AB+",
medical_record,
123142,
"MaestCare",
)

Quando você insere um documento, o cliente habilitado para CSFLE criptografa os campos do documento de forma que ele se pareça com o seguinte:

{
"_id": { "$oid": "<_id of your document>" },
"name": "Jon Doe",
"ssn": {
"$binary": "<cipher-text>",
"$type": "6"
},
"bloodType": {
"$binary": "<cipher-text>",
"$type": "6"
},
"medicalRecords": {
"$binary": "<cipher-text>",
"$type": "6"
},
"insurance": {
"provider": "MaestCare",
"policyNumber": {
"$binary": "<cipher-text>",
"$type": "6"
}
}
}

Dica

Veja: Código Completo

Para visualizar o código completo para inserir um documento criptografado, consulte nosso repositório Github

Para visualizar o código completo de inserção de um documento criptografado, consulte nosso repositório do Github.

Para visualizar o código completo de inserção de um documento criptografado, consulte nosso repositório do Github.

Para visualizar o código completo de inserção de um documento criptografado, consulte nosso repositório do Github.

Para visualizar o código completo de inserção de um documento criptografado, consulte nosso repositório do Github.

5

Recupere o documento criptografado inserido na etapa Inserir um documento com campos criptografados deste guia.

Para mostrar a funcionalidade do CSFLE, as seguintes consultas de trecho de código para seu documento com um cliente configurado para CSFLE automático, bem como um cliente que não está configurado para CSFLE automático.

InsertEncryptedDocument.cs
Console.WriteLine("Finding a document with regular (non-encrypted) client.");
var filter = Builders<BsonDocument>.Filter.Eq("name", "Jon Doe");
var regularResult = regularCollection.Find(filter).Limit(1).ToList()[0];
Console.WriteLine($"\n{regularResult}\n");
Console.WriteLine("Finding a document with encrypted client, searching on an encrypted field");
var ssnFilter = Builders<BsonDocument>.Filter.Eq("ssn", 145014000);
var secureResult = secureCollection.Find(ssnFilter).Limit(1).First();
Console.WriteLine($"\n{secureResult}\n");
insert-encrypted-document.go
fmt.Println("Finding a document with regular (non-encrypted) client.")
var resultRegular bson.M
err = regularClient.Database(dbName).Collection(collName).FindOne(context.TODO(), bson.D{{"name", "Jon Doe"}}).Decode(&resultRegular)
if err != nil {
panic(err)
}
outputRegular, err := json.MarshalIndent(resultRegular, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", outputRegular)
fmt.Println("Finding a document with encrypted client, searching on an encrypted field")
var resultSecure bson.M
err = secureClient.Database(dbName).Collection(collName).FindOne(context.TODO(), bson.D{{"ssn", "241014209"}}).Decode(&resultSecure)
if err != nil {
panic(err)
}
outputSecure, err := json.MarshalIndent(resultSecure, "", " ")
if err != nil {
panic(err)
}
fmt.Printf("%s\n", outputSecure)
InsertEncryptedDocument.java
System.out.println("Finding a document with regular (non-encrypted) client.");
Document docRegular = mongoClientRegular.getDatabase(recordsDb).getCollection(recordsColl).find(eq("name", "Jon Doe")).first();
System.out.println(docRegular.toJson());
System.out.println("Finding a document with encrypted client, searching on an encrypted field");
Document docSecure = mongoClientSecure.getDatabase(recordsDb).getCollection(recordsColl).find(eq("ssn", 241014209)).first();
System.out.println(docSecure.toJson());
insert_encrypted_document.js
console.log("Finding a document with regular (non-encrypted) client.");
console.log(
await regularClient.db(db).collection(coll).findOne({ name: /Jon/ })
);
console.log(
"Finding a document with encrypted client, searching on an encrypted field"
);
console.log(
await secureClient.db(db).collection(coll).findOne({ ssn: "241014209" })
);
insert_encrypted_document.py
print("Finding a document with regular (non-encrypted) client.")
result = regularClient.medicalRecords.patients.find_one({"name": "Jon Doe"})
pprint.pprint(result)
print("Finding a document with encrypted client, searching on an encrypted field")
pprint.pprint(secureClient.medicalRecords.patients.find_one({"ssn": 241014209}))

A saída do trecho de código anterior deve ser semelhante a esta:

Finding a document with regular (non-encrypted) client.
{
_id: new ObjectId("629a452e0861b3130887103a"),
name: 'Jon Doe',
ssn: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e7910c20697e5f4fa95710aafc9153f0a3dc769c8a132a604b468732ff1f4d8349ded3244b59cbfb41444a210f28b21ea1b6c737508d9d30e8baa30c1d8070c4d5e26", "hex"), 6),
bloodType: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e79022e238536dfd8caadb4d7751ac940e0f195addd7e5c67b61022d02faa90283ab69e02303c7e4001d1996128428bf037dea8bbf59fbb20c583cbcff2bf3e2519b4", "hex"), 6),
'key-id': 'demo-data-key',
medicalRecords: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e790405163a3207cff175455106f57eef14e5610c49a99bcbd14a7db9c5284e45e3ee30c149354015f941440bf54725d6492fb3b8704bc7c411cff6c868e4e13c58233c3d5ed9593eca4e4d027d76d3705b6d1f3b3c9e2ceee195fd944b553eb27eee69e5e67c338f146f8445995664980bf0", "hex"), 6),
insurance: {
policyNumber: new Binary(Buffer.from("0217482732d8014cdd9ffdd6e2966e5e79108decd85c05be3fec099e015f9d26d9234605dc959cc1a19b63072f7ffda99db38c7b487de0572a03b2139ac3ee163bcc40c8508f366ce92a5dd36e38b3c742f7", "hex"), 6),
provider: 'MaestCare'
}
}
Finding a document with encrypted client, searching on an encrypted field
{
_id: new ObjectId("629a452e0861b3130887103a"),
name: 'Jon Doe',
ssn: 241014209,
bloodType: 'AB+',
'key-id': 'demo-data-key',
medicalRecords: [ { weight: 180, bloodPressure: '120/80' } ],
insurance: { policyNumber: 123142, provider: 'MaestCare' }
}

Dica

Veja: Código Completo

Para visualizar o código completo para localizar um documento criptografado, consulte nosso repositório do Github

Para visualizar o código completo para localizar um documento criptografado, consulte nosso repositório do Github.

Para visualizar o código completo para localizar um documento criptografado, consulte nosso repositório do Github.

Para visualizar o código completo para localizar um documento criptografado, consulte nosso repositório do Github.

Para visualizar o código completo para localizar um documento criptografado, consulte nosso repositório do Github.

Para saber como funciona o CSFLE, consulte Fundamentos.

Para saber mais sobre os tópicos mencionados neste guia, consulte os seguintes links:

  • Saiba mais sobre componentes CSFLE na página Referência.

  • Saiba como funcionam as chaves mestras do cliente e as chaves de criptografia de dados na página Chaves e cofres de chaves

  • Veja como os provedores de KMS gerenciam suas chaves CSFLE na página Provedores de KMS CSFLE.

Voltar

Usar AWS

Próximo

Usar o GCP