你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。
适用于 Java 的 Azure Cosmos DB Java SDK 的加密插件库
Azure Cosmos 加密插件用于使用用户提供的密钥加密数据,然后保存到 Cosmos DB 并在从数据库回读时对其进行解密。
源代码 | 包 (Maven) | API 参考文档 | 产品文档 | 样品
入门
添加包
<dependency>
<groupId>com.azure</groupId>
<artifactId>azure-cosmos-encryption</artifactId>
<version>2.6.0</version>
</dependency>
有关以前的版本,请参阅 maven central
有关包的更多详细信息,请参阅 javadocs
先决条件
- Java 开发工具包 (JDK) 版本 8 或更高版本
- 有效的 Azure 帐户。 如果没有,可以注册 免费帐户。 另外,可使用 Azure Cosmos DB 仿真器进行开发和测试。 由于模拟器 HTTPS 证书是自签名的,因此需要将其证书导入 Java 受信任的证书存储,如此 处所述
- (可选)SLF4J 是一种日志外观。
- (可选)SLF4J 绑定用于将特定的记录框架与 SLF4J 相关联。
- (可选)Maven
仅当计划使用日志记录时,才需要 SLF4J。还请下载 SLF4J 绑定,该绑定可将 SLF4J API 与你选择的记录实现链接在一起。 有关详细信息,请参阅 SLF4J 用户手册。
SDK 提供基于 Reactor Core 的异步 API。 可在此处阅读有关 Reactor Core 和 Flux/Mono 类型的详细信息
关键概念
Azure Cosmos 加密插件用于使用用户提供的密钥加密数据,然后保存到 Cosmos DB 并在从数据库回读时对其进行解密。 它使用 Azure Cosmos DB Java SDK,该 SDK 提供客户端逻辑表示来访问 Azure Cosmos DB SQL API。 Cosmos DB 帐户包含零个或多个数据库,数据库 (DB) 包含零个或多个容器,容器包含零个或多个项。 可 在此处阅读有关数据库、容器和项的详细信息。 在容器级别定义了一些重要属性,其中包括预配的吞吐量和分区键。
示例
以下部分提供了几个代码片段,涵盖了一些最常见的 Cosmos 加密 API 任务,包括:
创建 Cosmos 加密客户端
// Create a new CosmosEncryptionAsyncClient
CosmosAsyncClient cosmosAsyncClient = new CosmosClientBuilder()
.endpoint("<YOUR ENDPOINT HERE>")
.key("<YOUR KEY HERE>")
.buildAsyncClient();
KeyEncryptionKeyClientBuilder keyEncryptionKeyClientBuilder = new KeyEncryptionKeyClientBuilder().credential(tokenCredentials);
CosmosEncryptionAsyncClient cosmosEncryptionAsyncClient =
new CosmosEncryptionClientBuilder().cosmosAsyncClient(cosmosAsyncClient).keyEncryptionKeyResolver(
keyEncryptionKeyClientBuilder).keyEncryptionKeyResolverName(CosmosEncryptionClientBuilder.KEY_RESOLVER_NAME_AZURE_KEY_VAULT).buildAsyncClient();
创建 Cosmos 加密数据库
需要首先创建一个数据库,并使用在上一示例中创建的 cosmos 加密客户端,可以创建一个 cosmos 加密数据库代理对象,如下所示:
// This will create a database with the regular cosmosAsyncClient.
CosmosEncryptionAsyncDatabase cosmosEncryptionAsyncDatabase = cosmosEncryptionAsyncClient.getCosmosAsyncClient()
.createDatabaseIfNotExists("<YOUR DATABASE NAME>")
// TIP: Our APIs are Reactor Core based, so try to chain your calls
.map(databaseResponse ->
// Get a reference to the encryption database
// This will create a cosmos encryption database proxy object.
cosmosEncryptionAsyncClient.getCosmosEncryptionAsyncDatabase(databaseResponse.getProperties().getId()))
.block(); // Blocking for demo purposes (avoid doing this in production unless you must)
创建 Cosmos 加密容器
需要首先使用 ClientEncryptionPolicy 创建容器,并使用在上一示例中创建的 cosmos 加密数据库对象,可以创建一个 cosmos 加密容器代理对象,如下所示:
//Create Client Encryption Key
EncryptionKeyWrapMetadata metadata = new EncryptionKeyWrapMetadata(this.cosmosEncryptionAsyncClient.getKeyEncryptionKeyResolverName(), "key", "tempmetadata", EncryptionAlgorithm.RSA_OAEP.toString());
CosmosEncryptionAsyncContainer cosmosEncryptionAsyncContainer = cosmosEncryptionAsyncDatabase
.createClientEncryptionKey("key", CosmosEncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256.getName(), metadata)
// TIP: Our APIs are Reactor Core based, so try to chain your calls
.then(Mono.defer(() -> {
//Create Encryption Container
ClientEncryptionIncludedPath includedPath = new ClientEncryptionIncludedPath();
includedPath.setClientEncryptionKeyId("key");
includedPath.setPath("/sensitiveString");
includedPath.setEncryptionType(CosmosEncryptionType.DETERMINISTIC.toString());
includedPath.setEncryptionAlgorithm(CosmosEncryptionAlgorithm.AEAD_AES_256_CBC_HMAC_SHA256.getName());
List<ClientEncryptionIncludedPath> paths = new ArrayList<>();
paths.add(includedPath);
ClientEncryptionPolicy clientEncryptionPolicy = new ClientEncryptionPolicy(paths);
CosmosContainerProperties properties = new CosmosContainerProperties("<YOUR CONTAINER NAME>", "/mypk");
properties.setClientEncryptionPolicy(clientEncryptionPolicy);
return cosmosEncryptionAsyncDatabase.getCosmosAsyncDatabase().createContainer(properties);
}))
.map(containerResponse ->
// Create a reference to the encryption container
// This will create a cosmos encryption container proxy object.
cosmosEncryptionAsyncDatabase.getCosmosEncryptionAsyncContainer(containerResponse.getProperties().getId()))
.block(); // Blocking for demo purposes (avoid doing this in production unless you must)
对项执行 CRUD 操作
// Create an item
Pojo pojo = new Pojo();
pojo.setSensitiveString("Sensitive Information need to be encrypted");
cosmosEncryptionAsyncContainer.createItem(pojo)
.flatMap(response -> {
System.out.println("Created item: " + response.getItem());
// Read that item 👓
return cosmosEncryptionAsyncContainer.readItem(response.getItem().getId(),
new PartitionKey(response.getItem().getId()),
Pojo.class);
})
.flatMap(response -> {
System.out.println("Read item: " + response.getItem());
// Replace that item 🔁
Pojo p = response.getItem();
pojo.setSensitiveString("New Sensitive Information");
return cosmosEncryptionAsyncContainer.replaceItem(p, response.getItem().getId(),
new PartitionKey(response.getItem().getId()));
})
// delete that item 💣
.flatMap(response -> cosmosEncryptionAsyncContainer.deleteItem(response.getItem().getId(),
new PartitionKey(response.getItem().getId())))
.subscribe();
此处 提供了入门示例应用。
疑难解答
常规
Azure Cosmos DB 是一个快速、弹性的分布式数据库,可以在提供延迟与吞吐量保证的情况下无缝缩放。 凭借 Azure Cosmos DB,无需对体系结构进行重大更改或编写复杂的代码即可缩放数据库。 扩展和缩减操作就像执行单个 API 调用或 SDK 方法调用一样简单。 但是,由于 Azure Cosmos DB 是通过网络调用访问的,因此,使用 Azure Cosmos DB Java SDK v4 时,可以通过客户端优化获得最高性能。
性能 指南介绍了这些客户端优化。
故障排除指南 介绍了将 Azure Cosmos DB Java SDK v4 与 Azure Cosmos DB SQL API 帐户配合使用时的常见问题、解决方法、诊断步骤和工具。
启用客户端日志记录
Azure Cosmos DB Java SDK v4 使用 SLF4j 作为日志外观,支持记录到常用的日志框架,如 log4j 和 logback。
例如,如果要使用 log4j 作为日志记录框架,请在 Java classpath 中添加以下库。
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>${slf4j.version}</version>
</dependency>
<dependency>
<groupId>log4j</groupId>
<artifactId>log4j</artifactId>
<version>${log4j.version}</version>
</dependency>
此外,请添加 log4j 配置。
# this is a sample log4j configuration
# Set root logger level to INFO and its only appender to A1.
log4j.rootLogger=INFO, A1
log4j.category.com.azure.cosmos=INFO
#log4j.category.io.netty=OFF
#log4j.category.io.projectreactor=OFF
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d %5X{pid} [%t] %-5p %c - %m%n
后续步骤
- Cosmos 加密示例程序 在此处
- Cosmos DB 核心 java sdk 快速入门 - 构建 Java 应用来管理 Cosmos DB SQL API 数据
- 阅读有关 Azure Cosmos DB 服务的详细信息
贡献
本项目欢迎贡献和建议。 大多数贡献要求你同意贡献者许可协议 (CLA),并声明你有权(并且确实有权)授予我们使用你的贡献的权利。
提交拉取请求时,CLA 机器人将自动确定你是否需要提供 CLA,并相应地修饰 PR(例如标签、注释)。 直接按机器人提供的说明操作。 只需使用 CLA 对所有存储库执行一次这样的操作。
此项目采用了 Microsoft 开放源代码行为准则。 有关详细信息,请参阅行为准则常见问题解答,或如果有任何其他问题或意见,请与 联系。