Overview
Esta guía le muestra cómo crear una aplicación habilitada para cifrado de nivel de campo del lado del cliente (CSFLE) mediante el servicio de administración de claves de Google Cloud.
Después de completar los pasos de esta guía, debería tener:
A CMK alojado en el servicio de administración de claves de Google Cloud.
Una aplicación cliente que inserta documentos cifrados utilizando su CMK.
Antes de empezar
Para completar y ejecutar el código de esta guía, debe configurar su entorno de desarrollo como se muestra en la Páginade requisitos de instalación.
A lo largo de esta guía, los ejemplos de código utilizan texto de marcador de posición. Antes de ejecutar los ejemplos, se deben sustituir los valores propios que se van a usar para estos marcadores.
Por ejemplo:
dek_id := "<Your Base64 DEK ID>"
Sustituya todo entre comillas por su ID de DEK.
dek_id := "abc123"
Seleccione el lenguaje de programación para el cual desea ver ejemplos de código en el Select your language Menú desplegable en el lado derecho de la página.
Tip
Ver: Solicitud completa
Para ver el código completo de la aplicación ejecutable para este tutorial, vaya al siguiente enlace:
Configurar el KMS
// 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.
Registrar una cuenta de servicio de GCP
Regístrese o inicie sesión en su cuenta existente en Google Cloud.
Crea una cuenta de servicio para tu proyecto
Para crear una cuenta de servicio en Google Cloud, siga la guía Creación de una cuenta de servicio en la documentación oficial de Google.
Agregar una clave de cuenta de servicio
Para agregar una clave de cuenta de servicio en Google Cloud, siga la guía Administrar claves de cuenta de servicio en la documentación oficial de Google.
Importante
Al crear la clave de su cuenta de servicio, recibirá una descarga única de la información de la clave privada. Asegúrese de descargar este archivo en formato PKCS12 o JSON para usarlo más adelante en este tutorial.
Crear una clave maestra de cliente de GCP
Crear una nueva clave maestra de cliente
Crea un llavero y una llave simétrica siguiendo la guía Crear una llave de la documentación oficial de Google.
Esta clave es su clave maestra de cliente(CMK).
Registre los siguientes detalles de su CMK para usarlos en un paso futuro de este tutorial.
Campo | Requerido | Descripción |
|---|---|---|
key_name | Sí | Identificador para el CMK. |
llavero | Sí | Identificador del grupo de claves al que pertenece su clave. |
key_version | No | La versión de la clave nombrada. |
ubicación | Sí | Región especificada para tu clave. |
punto final | No | El host y el puerto opcional de Google Cloud KMS. El valor predeterminado es |
Crear la aplicación
Seleccione la pestaña que corresponde al controlador MongoDB que está utilizando en su aplicación para ver ejemplos de código relevantes.
Cree un índice único en su colección de Key Vault
Cree un índice único en el campo keyAltNames en su colección encryption.__keyVault.
Seleccione la pestaña correspondiente a su controlador MongoDB preferido:
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);
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) }
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();
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 } }, } );
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}}, )
Crear una llave de cifrado de datos
Agregue sus credenciales de GCP KMS
Agregue las credenciales de la cuenta de servicio a su código de cliente habilitado para CSFLE.
Tip
Guardó un archivo que contiene las credenciales de la clave de su cuenta de servicio en el paso Crear una cuenta de servicio de GCP de esta guía.
Si descargaste tus credenciales en formato JSON, puedes usar el siguiente comando para extraer el valor de tu clave privada, sustituyendo <credentials-filename> con el nombre de tu archivo de credenciales:
cat <credentials-filename> | jq -r .private_key | openssl pkcs8 -topk8 -nocrypt -inform PEM -outform DER | base64
Si descargó sus credenciales en formato PKCS12, debe especificar la contraseña de importación de su cuenta de servicio de GCP y agregar una frase de contraseña PEM para acceder a la clave cuando acceda a ella mediante el siguiente comando, sustituyendo <credentials-filename> con el nombre de su archivo de credenciales:
openssl pkcs12 -info -in <credentials-filename>
var kmsProviders = new Dictionary<string, IReadOnlyDictionary<string, object>>(); var provider = "gcp"; var gcpKmsOptions = new Dictionary<string, object> { { "privateKey", "<Your GCP Private Key>" }, { "email", "<Your GCP Email>" }, }; kmsProviders.Add(provider, gcpKmsOptions);
provider := "gcp" kmsProviders := map[string]map[string]interface{}{ provider: { "email": "<Your GCP Email>", "privateKey": "<Your GCP Private Key>", }, }
String kmsProvider = "gcp"; Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>(); Map<String, Object> providerDetails = new HashMap<>(); providerDetails.put("email", "<Your GCP Email Address>"); providerDetails.put("privateKey", "<Your GCP Private Key>"); kmsProviders.put(kmsProvider, providerDetails);
const provider = "gcp"; const kmsProviders = { gcp: { email: "<Your GCP Email>", privateKey: "<Your GCP Private Key>", }, };
provider = "gcp" kms_providers = { provider: {"email": "<your GCP email>", "privateKey": "<your GCP private key>"} }
Tip
Obtén más información
Para obtener más información sobre el objeto de proveedor KMS para GCP,consulte Google Cloud Platform KMS.
Agregue su información clave
Actualice el siguiente código para especificar su clave maestra de cliente:
Tip
Registró los detalles de su clave maestra de cliente en el paso Crear una clave maestra de cliente de esta guía.
var dataKeyOptions = new DataKeyOptions( masterKey: new BsonDocument { { "projectId", "Your GCP Project ID" }, { "location", "Your GCP Key Location" } , { "keyRing", "<Your GCP Key Ring>" }, { "keyName", "<Your GCP Key Name>" }, });
masterKey := map[string]interface{}{ "projectId": "<Your GCP Project ID>", "location": "<Your GCP Location>", "keyRing": "<Your GCP Key Ring>", "keyName": "<Your GCP Key Name>", }
BsonDocument masterKeyProperties = new BsonDocument(); masterKeyProperties.put("provider", new BsonString(kmsProvider)); masterKeyProperties.put("projectId", new BsonString("<Your GCP Project ID>")); masterKeyProperties.put("location", new BsonString("<Your GCP Key Location>")); masterKeyProperties.put("keyRing", new BsonString("<Your GCP Key Ring>")); masterKeyProperties.put("keyName", new BsonString("<Your GCP Key Name>"));
const masterKey = { projectId: "<Your Project ID>", location: "<Your Key Location>", keyRing: "<Your Key Ring>", keyName: "<Your Key Name>", };
master_key = { "projectId": "<GCP project identifier>", "location": "<GCP region>", "keyRing": "<GCP key ring name>", "keyName": "<GCP key name>", }
Genere su clave de cifrado de datos
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}");
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))
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();
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();
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)
Tip
Obtén más información
Para ver un diagrama que muestra cómo su aplicación cliente crea su clave de cifrado de datos cuando utiliza un servicio de administración de claves de Google Cloud, consulte Arquitectura.
Para obtener más información sobre las opciones para crear una clave de cifrado de datos cifrada con una clave maestra de cliente alojada en Azure Key Vault, consulte Objeto kmsProviders y Objeto dataKeyOpts.
Tip
Ver: Código completo
Para ver el código completo para crear una clave de cifrado de datos, consulte nuestro repositorio de Github.
Para ver el código completo para crear una clave de cifrado de datos, consulte nuestro repositorio de Github.
Para ver el código completo para crear una clave de cifrado de datos, consulte nuestro repositorio de Github.
Para ver el código completo para crear una clave de cifrado de datos, consulte nuestro repositorio de Github.
Para ver el código completo para crear una clave de cifrado de datos, consulte nuestro repositorio de Github.
Configurar MongoClient
Especifique el espacio de nombres de la colección Key Vault
Especifique encryption.__keyVault como el espacio de nombres de la colección Key Vault.
var keyVaultNamespace = CollectionNamespace.FromFullName("encryption.__keyVault");
keyVaultNamespace := "encryption.__keyVault"
String keyVaultNamespace = "encryption.__keyVault";
const keyVaultNamespace = "encryption.__keyVault";
key_vault_namespace = "encryption.__keyVault"
Especifica tus credenciales de cuenta en la nube
Especifique el proveedor de la nube y las credenciales de su cuenta de servicio:
var kmsProviders = new Dictionary<string, IReadOnlyDictionary<string, object>>(); var provider = "gcp"; var gcpKmsOptions = new Dictionary<string, object> { { "privateKey", "<Your GCP Private Key>" }, { "email", "<Your GCP Email>" }, }; kmsProviders.Add(provider, gcpKmsOptions);
kmsProviders := map[string]map[string]interface{}{ "gcp": { "email": "<Your GCP Email>", "privateKey": "<Your GCP Private Key>", }, }
String kmsProvider = "gcp"; Map<String, Map<String, Object>> kmsProviders = new HashMap<String, Map<String, Object>>(); Map<String, Object> providerDetails = new HashMap<>(); providerDetails.put("email", "<Your GCP Email Address>"); providerDetails.put("privateKey", "<Your GCP Private Key>"); kmsProviders.put(kmsProvider, providerDetails);
const kmsProviders = { gcp: { email: "<Your GCP Email>", privateKey: "<Your GCP Private Key>", }, };
provider = "gcp" kms_providers = { "gcp": {"email": "<your GCP email>", "privateKey": "<your GCP private key>"} }
Cree un esquema de cifrado para su colección
Tip
Agregue su ID de base de clave de cifrado de datos64
Asegúrate de actualizar el siguiente código para incluir tu ID de64 DEK Base. Recibiste este valor en el paso "Generar tu clave de cifrado de datos" de esta guía.
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);
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, }
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()));
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;
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}
Especificar la ubicación de la biblioteca compartida de cifrado automático
var mongoBinariesPath = "<Full path to your Automatic Encryption Shared Library>"; var extraOptions = new Dictionary<string, object>() { { "cryptSharedLibPath", mongoBinariesPath }, };
extraOptions := map[string]interface{}{ "cryptSharedLibPath": "<Full path to your Automatic Encryption Shared Library>", }
Map<String, Object> extraOptions = new HashMap<String, Object>(); extraOptions.put("cryptSharedLibPath", "<Full path to your Automatic Encryption Shared Library>"));
const extraOptions = { cryptSharedLibPath: "<Full path to your Automatic Encryption Shared Library>", };
extra_options = { "cryptSharedLibPath": "<Full path to your Automatic Encryption Shared Library>" }
Nota
Opciones de cifrado automático
Las opciones de cifrado automático proporcionan información de configuración a la biblioteca compartida de cifrado automático, que modifica el comportamiento de la aplicación al acceder a campos cifrados.
Para obtener más información sobre la librería Compartida de Cifrado Automático, consulta la página librería Compartida de Cifrado Automático para CSFLE.
Crear el MongoClient
Cree una instancia de un objeto cliente MongoDB con las siguientes configuraciones de cifrado automático:
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);
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()) }()
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);
const secureClient = new MongoClient(connectionString, { useNewUrlParser: true, useUnifiedTopology: true, autoEncryption: { keyVaultNamespace, kmsProviders, schemaMap: patientSchema, extraOptions: extraOptions, }, });
fle_opts = AutoEncryptionOpts( kms_providers, key_vault_namespace, schema_map=patient_schema, **extra_options ) secureClient = MongoClient(connection_string, auto_encryption_opts=fle_opts)
Insertar un documento con campos cifrados
Utilice su instancia MongoClient habilitada para CSFLE para insertar un documento cifrado en el espacio de nombres medicalRecords.patients utilizando el siguiente fragmento de código:
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);
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) }
Nota
En lugar de crear un documento BSON sin procesar, puede pasar una estructura con etiquetas bson directamente al controlador para su codificación.
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);
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); }
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", )
Cuando inserta un documento, su cliente compatible con CSFLE cifra los campos de su documento de forma que se parece a lo siguiente:
{ "_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" } } }
Tip
Ver: Código completo
Para ver el código completo para insertar un documento cifrado, consulte nuestro repositorio de Github
Para ver el código completo para insertar un documento cifrado, consulte nuestro repositorio de Github.
Para ver el código completo para insertar un documento cifrado, consulte nuestro repositorio de Github.
Para ver el código completo para insertar un documento cifrado, consulte nuestro repositorio de Github.
Para ver el código completo para insertar un documento cifrado, consulte nuestro repositorio de Github.
Recupere su documento cifrado
Recupere el documento cifrado que insertó en el paso Insertar un documento con campos cifrados de esta guía.
Para mostrar la funcionalidad de CSFLE, el siguiente fragmento de código consulta su documento con un cliente configurado para CSFLE automático, así como con un cliente que no está configurado para CSFLE automático.
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");
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)
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());
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" }) );
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}))
La salida del fragmento de código anterior debería verse así:
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' } }
Tip
Ver: Código completo
Para ver el código completo para encontrar un documento cifrado, consulte nuestro repositorio de Github
Para ver el código completo para encontrar un documento cifrado, consulte nuestro repositorio de Github.
Para ver el código completo para encontrar un documento cifrado, consulte nuestro repositorio de Github.
Para ver el código completo para encontrar un documento cifrado, consulte nuestro repositorio de Github.
Para ver el código completo para encontrar un documento cifrado, consulte nuestro repositorio de Github.
Obtén más información
Para obtener más información sobre los temas mencionados en esta guía, consulte los siguientes enlaces:
Obtenga más información sobre los componentes CSFLE en la página de Referencia.
Descubra cómo funcionan las claves maestras del cliente y las claves de cifrado de datos en la página Claves y bóvedas de claves.
Vea cómo los proveedores de KMS administran sus claves CSFLE en la página Proveedores de KMS CSFLE.