将 gRPC 与 Cloud KMS 搭配使用

如果您使用手动创建的 gRPC 库调用 Cloud Key Management Service,则必须在调用的元数据或标头中指定 x-google-request-params 值。正确使用 x-google-request-params 会将调用路由到适用于您的 Cloud KMS 资源的区域。

x-google-request-params 值设置为方法请求中的字段,如下表所示。

设置请求字段

以下示例显示了在各种方法中指定资源名称的位置。将样式为 place-holder 的文本替换为 Cloud KMS 资源 ID 中使用的实际值。

Decrypt 示例

如果您将调用 Decrypt,则需要在请求中填充以下字段:

name: 'projects/project-id/locations/location/keyRings/key-ring/cryptoKeys/key-name/'
ciphertext: 'iQALWM/r6alAxQm0VQe3...'

分配给 name 字段的值是您的 CryptoKey 的资源名称。 要正确路由调用,还必须在调用元数据中包含该资源名称,格式如下:

x-goog-request-params: 'name=projects/project-id/locations/location/keyRings/key-ring/cryptoKeys/key-name/'

CreateKeyRing 示例

如果要调用 CreateKeyRing,则需要在请求中填充以下字段:

parent: 'projects/project-id/locations/location/'
key_ring_id: 'myKeyRing'
...

调用元数据还需要包含 parent 资源名称:

x-goog-request-params: 'parent=projects/project-id/locations/location/'

UpdateCryptoKey 示例

如果要调用 UpdateCryptoKey,则需要在请求中填充以下字段:

name: 'projects/project-id/locations/location/keyRings/key-ring/cryptoKeys/key-name/'
field_mask: ...

元数据还需要包含 name 资源名称。请注意,该格式使用的是 crypto_key.name=,而非 name=

x-goog-request-params: 'crypto_key.name=projects/project-id/locations/location/keyRings/key-ring/cryptoKeys/key-name/'

使用 C++ 添加元数据

如果您使用的是 C++,请在进行 RPC 调用之前先调用 ClientContext::AddMetadata,以将适当的信息添加到调用元数据中。

例如,如果要为对 Decrypt 的调用添加元数据:

context.AddMetadata("x-goog-request-params",
                    "name=projects/project-id/locations/location/keyRings/key-ring-name/cryptoKeys/key-name/");

然后,您可以像往常一样将上下文与请求和响应协议缓冲一起传递给方法调用。