Database Manual / Reference / mongosh Methods / In-Use Encryption

ClientEncryption.encrypt() (mongosh method方法)

ClientEncryption.encrypt(keyId, value, algorithm or encOptions)

ClientEncryption.encrypt() encrypts the value using the specified keyId and the algorithm specified by algorithm or encOptions. 使用指定的keyIdalgorithmencOptions指定的算法对value进行加密。encrypt() supports explicit (manual) encryption of field values.支持字段值的显式(手动)加密。

Returns:返回A binary data object with subtype 6.

Compatibility兼容性

This command is available in deployments hosted in the following environments:此命令在以下环境中托管的部署中可用:

  • MongoDB Atlas: The fully managed service for MongoDB deployments in the cloud:云中MongoDB部署的完全托管服务
  • MongoDB Enterprise: The subscription-based, self-managed version of MongoDB:MongoDB的基于订阅的自我管理版本
  • MongoDB Community: The source-available, free-to-use, and self-managed version of MongoDB:MongoDB的源代码可用、免费使用和自我管理版本

Syntax语法

clientEncryption = db.getMongo().getClientEncryption()

clientEncryption.encrypt(
keyId,
value,
algorithm or encOptions,
)
Parameter参数Type类型Description描述
keyIdUUID

The data encryption key to use for encrypting the value.用于加密value的数据加密键。

The UUID is a BSON binary data object with subtype 4 that identifies a specific data encryption key. If the data encryption key does not exist in the key vault configured for the database connection, encrypt() returns an error. See Key Vault Collections for more information on key vaults and data encryption keys.

valueSee Unsupported BSON Types.The value to encrypt.
algorithm or encOptionsstring or document字符串或文档
  • To explicitly encrypt fields with Client-Side Field Level Encryption:

    Specify the algorithm as a string or encOptions as a document containing the field algorithm.algorithm指定为字符串,或将encOptions指定为包含字段算法的文档。

    The supported algorithms are:支持的算法有:

    • AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic
    • AEAD_AES_256_CBC_HMAC_SHA_512-Random

    For examples, see Set the Client-Side Field Level Encryption Algorithm.

    For complete documentation on the supported encryption algorithms, see Fields and Encryption Types.

  • To explicitly encrypt fields with Queryable Encryption:

    Specify the algorithm as a string or encOptions as a document containing the fields:algorithm指定为字符串,或将encOptions指定为包含以下字段的文档:

    • algorithm: The encryption algorithm to use for encrypting the value. The supported algorithms are::用于加密value的加密算法。支持的算法有:

      • Indexed
      • Unindexed
    • contentionFactor: Required when algorithm is set to Indexed. Related to the frequency of the values for this field.
    • queryType: The only query type currently supported is "equality". queryType must be set when algorithm is not Indexed.

    For examples, see Set the Queryable Encryption Algorithm.

    For details on the supported encryption algorithms, see Algorithm Choice.

Behavior行为

The mongosh client-side field level and queryable encryption methods require a database connection configured for client-side encryption. If the current database connection was not initiated with client-side field level encryption enabled, either:

or

Unsupported BSON Types

You cannot use encrypt() to encrypt values with the following BSON types:

  • minKey
  • maxKey
  • null
  • undefined

If encrypting a field using AEAD_AES_256_CBC_HMAC_SHA_512-Deterministic, encrypt() does not support the following BSON types:

  • double
  • decimal128
  • bool
  • object
  • array

Examples示例

Client-Side Field Level Encryption客户端字段级加密

The following example uses a locally managed KMS for the client-side field level encryption configuration.以下示例使用本地管理的KMS进行客户端字段级加密配置。

1

Create Your Encrypted Connection创建加密连接

  1. Start mongosh

    Run:运行:

    mongosh --nodb

    --nodb means don't connect to a database.意味着不要连接到数据库。

  2. Generate a Key String生成键字符串

    Generate a base 64 96-byte string:生成一个基本64 96字节的字符串:

    const TEST_LOCAL_KEY = require("crypto").randomBytes(96).toString("base64")
  3. Create an Encryption Options Object创建加密选项对象

    To create a client-side field level encryption options object, use the TEST_LOCAL_KEY string from the previous step:要创建客户端字段级加密选项对象,请使用上一步中的TEST_LOCAL_KEY字符串:

       var autoEncryptionOpts = {
    "keyVaultNamespace" : "encryption.__dataKeys",
    "kmsProviders" : {
    "local" : {
    "key" : BinData(0, TEST_LOCAL_KEY)
    }
    }
    }
  4. Create an Encrypted Client Object创建加密客户端对象

    To create an encrypted client object, use the Mongo() constructor. Replace the mongodb://myMongo.example.net URI with the connection string URI for the target cluster. For example:

    encryptedClient = Mongo(
    "mongodb://myMongo.example.net:27017/?replSetName=myMongo",
    autoEncryptionOpts
    )
2

Encrypt Your Data

Retrieve the ClientEncryption object and use the ClientEncryption.encrypt() method to encrypt a value using a specific data encryption key UUID and encryption algorithm:

clientEncryption = encryptedClient.getClientEncryption();

clientEncryption.encrypt(
UUID("64e2d87d-f168-493c-bbdf-a394535a2cb9"),
"123-45-6789",
"AEAD_AES_256_CBC_HMAC_SHA_512-Random"
)

You can also specify the algorithm using a document with an algorithm field:

clientEncryption = encryptedClient.getClientEncryption();

clientEncryption.encrypt(
UUID("64e2d87d-f168-493c-bbdf-a394535a2cb9"),
"123-45-6789",
{ algorithm: "AEAD_AES_256_CBC_HMAC_SHA_512-Random" }
)

Example Results

If successful, encrypt() returns the encrypted value:

BinData(6,"AmTi2H3xaEk8u9+jlFNaLLkC3Q/+kmwDbbWrq+h9nuv9W+u7A5a0UnpULBNZH+Q21fAztPpU09wpKPrju9dKfpN1Afpj1/ZhFcH6LYZOWSBBOAuUNjPLxMNSYOOuITuuYWo=")

For complete documentation on initiating MongoDB connections with client-side field level encryption enabled, see Mongo().

Queryable Encryption

The following example uses a locally managed KMS for the Queryable Encryption configuration.

1

Create Your Encrypted Connection

  1. Start mongosh

    Start the mongosh client.

    mongosh --nodb
  2. Generate Your Key

    To configure Queryable Encryption for a locally managed key, generate a base64-encoded 96-byte string with no line breaks.要为本地管理的键配置可查询加密,请生成一个没有换行符的base64编码的96字节字符串。

    const TEST_LOCAL_KEY = require("crypto").randomBytes(96).toString("base64")
  3. Create the Queryable Encryption Options创建可查询的加密选项

    Create the Queryable Encryption options using the generated local key string:使用生成的本地键字符串创建可查询加密选项:

       var autoEncryptionOpts = {
    "keyVaultNamespace" : "encryption.__dataKeys",
    "kmsProviders" : {
    "local" : {
    "key" : BinData(0, TEST_LOCAL_KEY)
    }
    }
    }
  4. Create Your Encrypted Client创建加密客户端

    Use the Mongo() constructor with the queryable encryption options configured to create a database connection. Replace the mongodb://myMongo.example.net URI with the connection string URI of the target cluster.

    encryptedClient = Mongo(
    "mongodb://myMongo.example.net:27017/?replSetName=myMongo",
    autoEncryptionOpts
    )
2

Encrypt Your Data加密数据

Retrieve the ClientEncryption object and use the ClientEncryption.encrypt() method to encrypt a value using a specific data encryption key UUID and encryption algorithm:

const eDB = "encrypted"
const eKV = "__keyVault"

const clientEncryption = encryptedClient.getClientEncryption();
const keyVaultClient = Mongo().getDB(eDB).getCollection(eKV)

const dek = keyVaultClient.findOne({ keyAltNames: "dataKey1" })

clientEncryption.encrypt(
dek._id,
"123-45-6789",
"Unindexed"
)

You can also specify the algorithm using a document containing the fields:您还可以使用包含以下字段的文档指定算法:

  • algorithm
  • queryType
  • contentionFactor
const eDB = "encrypted"
const eKV = "__keyVault"

const clientEncryption = encryptedClient.getClientEncryption();
const keyVaultClient = Mongo().getDB(eDB).getCollection(eKV)

const dek = keyVaultClient.findOne({ keyAltNames: "dataKey1" })

clientEncryption.encrypt(
dek._id,
"123-45-6789",
{
algorithm: "Indexed",
queryType: "equality",
contentionFactor: 8
}
)

Example Results示例结果

If successful, encrypt() returns the encrypted value:如果成功,encrypt()返回加密值:

Binary(Buffer.from("05b100000005640020000000005ab3581a43e39a8e855b1ac87013e841735c09d19ae86535eea718dd56122ba50573002000000000703d2cba9832d90436c6c92eb232aa5b968cdcd7a3138570bc87ef0a9eb3a0e905630020000000009cb61df010b1bb54670a5ad979f25f4c48889059dfd8920782cf03dd27d1a50b05650020000000003f5acea703ea357d3eea4c6a5b19139a580089341424a247839fd4d5cf0d312a12636d00040000000000000000", "hex"), 6)

Learn More了解更多

For complete documentation on initiating MongoDB connections with client-side field level encryption enabled, see Mongo().有关启用客户端字段级加密启动MongoDB连接的完整文档,请参阅Mongo()