创建非对称签名密钥。
深入探索
如需查看包含此代码示例的详细文档,请参阅以下内容:
代码示例
C#
如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库。
如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
using Google.Cloud.Kms.V1;
using Google.Protobuf.WellKnownTypes;
public class CreateKeyAsymmetricSignSample
{
public CryptoKey CreateKeyAsymmetricSign(
string projectId = "my-project", string locationId = "us-east1", string keyRingId = "my-key-ring",
string id = "my-asymmetric-signing-key")
{
// Create the client.
KeyManagementServiceClient client = KeyManagementServiceClient.Create();
// Build the parent key ring name.
KeyRingName keyRingName = new KeyRingName(projectId, locationId, keyRingId);
// Build the key.
CryptoKey key = new CryptoKey
{
Purpose = CryptoKey.Types.CryptoKeyPurpose.AsymmetricSign,
VersionTemplate = new CryptoKeyVersionTemplate
{
Algorithm = CryptoKeyVersion.Types.CryptoKeyVersionAlgorithm.RsaSignPkcs12048Sha256,
},
// Optional: customize how long key versions should be kept before destroying.
DestroyScheduledDuration = new Duration
{
Seconds = 24 * 60 * 60,
}
};
// Call the API.
CryptoKey result = client.CreateCryptoKey(keyRingName, id, key);
// Return the result.
return result;
}
}
Go
如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库。
如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import (
"context"
"fmt"
"io"
"time"
kms "cloud.google.com/go/kms/apiv1"
"cloud.google.com/go/kms/apiv1/kmspb"
"google.golang.org/protobuf/types/known/durationpb"
)
// createKeyAsymmetricSign creates a new asymmetric RSA sign/verify key pair
// where the private key is stored in Cloud KMS.
func createKeyAsymmetricSign(w io.Writer, parent, id string) error {
// parent := "projects/my-project/locations/us-east1/keyRings/my-key-ring"
// id := "my-asymmetric-signing-key"
// Create the client.
ctx := context.Background()
client, err := kms.NewKeyManagementClient(ctx)
if err != nil {
return fmt.Errorf("failed to create kms client: %w", err)
}
defer client.Close()
// Build the request.
req := &kmspb.CreateCryptoKeyRequest{
Parent: parent,
CryptoKeyId: id,
CryptoKey: &kmspb.CryptoKey{
Purpose: kmspb.CryptoKey_ASYMMETRIC_SIGN,
VersionTemplate: &kmspb.CryptoKeyVersionTemplate{
Algorithm: kmspb.CryptoKeyVersion_RSA_SIGN_PKCS1_2048_SHA256,
},
// Optional: customize how long key versions should be kept before destroying.
DestroyScheduledDuration: durationpb.New(24 * time.Hour),
},
}
// Call the API.
result, err := client.CreateCryptoKey(ctx, req)
if err != nil {
return fmt.Errorf("failed to create key: %w", err)
}
fmt.Fprintf(w, "Created key: %s\n", result.Name)
return nil
}
Java
如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库。
如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import com.google.cloud.kms.v1.CryptoKey;
import com.google.cloud.kms.v1.CryptoKey.CryptoKeyPurpose;
import com.google.cloud.kms.v1.CryptoKeyVersion.CryptoKeyVersionAlgorithm;
import com.google.cloud.kms.v1.CryptoKeyVersionTemplate;
import com.google.cloud.kms.v1.KeyManagementServiceClient;
import com.google.cloud.kms.v1.KeyRingName;
import com.google.protobuf.Duration;
import java.io.IOException;
public class CreateKeyAsymmetricSign {
public void createKeyAsymmetricSign() throws IOException {
// TODO(developer): Replace these variables before running the sample.
String projectId = "your-project-id";
String locationId = "us-east1";
String keyRingId = "my-key-ring";
String id = "my-asymmetric-signing-key";
createKeyAsymmetricSign(projectId, locationId, keyRingId, id);
}
// Create a new asymmetric key for the purpose of signing and verifying data.
public void createKeyAsymmetricSign(
String projectId, String locationId, String keyRingId, String id) throws IOException {
// Initialize client that will be used to send requests. This client only
// needs to be created once, and can be reused for multiple requests. After
// completing all of your requests, call the "close" method on the client to
// safely clean up any remaining background resources.
try (KeyManagementServiceClient client = KeyManagementServiceClient.create()) {
// Build the parent name from the project, location, and key ring.
KeyRingName keyRingName = KeyRingName.of(projectId, locationId, keyRingId);
// Build the asymmetric key to create.
CryptoKey key =
CryptoKey.newBuilder()
.setPurpose(CryptoKeyPurpose.ASYMMETRIC_SIGN)
.setVersionTemplate(
CryptoKeyVersionTemplate.newBuilder()
.setAlgorithm(CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256))
// Optional: customize how long key versions should be kept before destroying.
.setDestroyScheduledDuration(Duration.newBuilder().setSeconds(24 * 60 * 60))
.build();
// Create the key.
CryptoKey createdKey = client.createCryptoKey(keyRingName, id, key);
System.out.printf("Created asymmetric key %s%n", createdKey.getName());
}
}
}
Node.js
如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库。
如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
//
// TODO(developer): Uncomment these variables before running the sample.
//
// const projectId = 'my-project';
// const locationId = 'us-east1';
// const keyRingId = 'my-key-ring';
// const id = 'my-asymmetric-sign-key';
// Imports the Cloud KMS library
const {KeyManagementServiceClient} = require('@google-cloud/kms');
// Instantiates a client
const client = new KeyManagementServiceClient();
// Build the parent key ring name
const keyRingName = client.keyRingPath(projectId, locationId, keyRingId);
async function createKeyAsymmetricSign() {
const [key] = await client.createCryptoKey({
parent: keyRingName,
cryptoKeyId: id,
cryptoKey: {
purpose: 'ASYMMETRIC_SIGN',
versionTemplate: {
algorithm: 'RSA_SIGN_PKCS1_2048_SHA256',
},
// Optional: customize how long key versions should be kept before
// destroying.
destroyScheduledDuration: {seconds: 60 * 60 * 24},
},
});
console.log(`Created asymmetric key: ${key.name}`);
return key;
}
return createKeyAsymmetricSign();
PHP
如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库。
如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
use Google\Cloud\Kms\V1\Client\KeyManagementServiceClient;
use Google\Cloud\Kms\V1\CreateCryptoKeyRequest;
use Google\Cloud\Kms\V1\CryptoKey;
use Google\Cloud\Kms\V1\CryptoKey\CryptoKeyPurpose;
use Google\Cloud\Kms\V1\CryptoKeyVersion\CryptoKeyVersionAlgorithm;
use Google\Cloud\Kms\V1\CryptoKeyVersionTemplate;
use Google\Protobuf\Duration;
function create_key_asymmetric_sign(
string $projectId = 'my-project',
string $locationId = 'us-east1',
string $keyRingId = 'my-key-ring',
string $id = 'my-asymmetric-signing-key'
): CryptoKey {
// Create the Cloud KMS client.
$client = new KeyManagementServiceClient();
// Build the parent key ring name.
$keyRingName = $client->keyRingName($projectId, $locationId, $keyRingId);
// Build the key.
$key = (new CryptoKey())
->setPurpose(CryptoKeyPurpose::ASYMMETRIC_SIGN)
->setVersionTemplate((new CryptoKeyVersionTemplate())
->setAlgorithm(CryptoKeyVersionAlgorithm::RSA_SIGN_PKCS1_2048_SHA256)
)
// Optional: customize how long key versions should be kept before destroying.
->setDestroyScheduledDuration((new Duration())
->setSeconds(24 * 60 * 60)
);
// Call the API.
$createCryptoKeyRequest = (new CreateCryptoKeyRequest())
->setParent($keyRingName)
->setCryptoKeyId($id)
->setCryptoKey($key);
$createdKey = $client->createCryptoKey($createCryptoKeyRequest);
printf('Created asymmetric signing key: %s' . PHP_EOL, $createdKey->getName());
return $createdKey;
}
Python
如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库。
如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
import datetime
# Import the client library.
from google.cloud import kms
from google.protobuf import duration_pb2 # type: ignore
def create_key_asymmetric_sign(
project_id: str, location_id: str, key_ring_id: str, key_id: str
) -> kms.CryptoKey:
"""
Creates a new asymmetric signing key in Cloud KMS.
Args:
project_id (string): Google Cloud project ID (e.g. 'my-project').
location_id (string): Cloud KMS location (e.g. 'us-east1').
key_ring_id (string): ID of the Cloud KMS key ring (e.g. 'my-key-ring').
key_id (string): ID of the key to create (e.g. 'my-asymmetric-signing-key').
Returns:
CryptoKey: Cloud KMS key.
"""
# Create the client.
client = kms.KeyManagementServiceClient()
# Build the parent key ring name.
key_ring_name = client.key_ring_path(project_id, location_id, key_ring_id)
# Build the key.
purpose = kms.CryptoKey.CryptoKeyPurpose.ASYMMETRIC_SIGN
algorithm = (
kms.CryptoKeyVersion.CryptoKeyVersionAlgorithm.RSA_SIGN_PKCS1_2048_SHA256
)
key = {
"purpose": purpose,
"version_template": {
"algorithm": algorithm,
},
# Optional: customize how long key versions should be kept before
# destroying.
"destroy_scheduled_duration": duration_pb2.Duration().FromTimedelta(
datetime.timedelta(days=1)
),
}
# Call the API.
created_key = client.create_crypto_key(
request={"parent": key_ring_name, "crypto_key_id": key_id, "crypto_key": key}
)
print(f"Created asymmetric signing key: {created_key.name}")
return created_key
Ruby
如需了解如何安装和使用 Cloud KMS 客户端库,请参阅 Cloud KMS 客户端库。
如需向 Cloud KMS 进行身份验证,请设置应用默认凭据。如需了解详情,请参阅为本地开发环境设置身份验证。
# TODO(developer): uncomment these values before running the sample.
# project_id = "my-project"
# location_id = "us-east1"
# key_ring_id = "my-key-ring"
# id = "my-asymmetric-signing-key"
# Require the library.
require "google/cloud/kms"
# Create the client.
client = Google::Cloud::Kms.key_management_service
# Build the parent key ring name.
key_ring_name = client.key_ring_path project: project_id, location: location_id, key_ring: key_ring_id
# Build the key.
key = {
purpose: :ASYMMETRIC_SIGN,
version_template: {
algorithm: :RSA_SIGN_PKCS1_2048_SHA256
},
# Optional: customize how long key versions should be kept before destroying.
destroy_scheduled_duration: {
seconds: 24 * 60 * 60
}
}
# Call the API.
created_key = client.create_crypto_key parent: key_ring_name, crypto_key_id: id, crypto_key: key
puts "Created asymmetric signing key: #{created_key.name}"
后续步骤
如需搜索和过滤其他 Google Cloud 产品的代码示例,请参阅 Google Cloud 示例浏览器。