Tüm Ürünler
Search
Belge Merkezi

Key Management Service:İmzalama ve doğrulama için örnek kod

Son Güncelleme:Oct 10, 2026

Asimetrik bir anahtar kullanarak verileri imzalamak ve dijital imzaları doğrulamak için KMS instance SDK Python istemcisini kullanın. Bu sayfada eksiksiz bir çalışan örnek ve adım adım açıklama sunulmaktadır.

Tüm örneklerde yapılandırılmış bir istemci aracılığıyla istek göndermek için sign_with_options ve verify_with_options yöntemlerini kullanır.

Ön koşullar

Başlamadan önce şunlara sahip olduğunuzdan emin olun:

  • KMS instance SDK istemcisini başlattınız. Bkz. İstemciyi başlatma

  • Bir asimetrik anahtar kimliği (key_id) ve desteklenen bir imzalama algoritması

Eksiksiz örnek

# -*- coding: utf-8 -*-
import os

from openapi.models import Config
from openapi_util.models import RuntimeOptions
from sdk.client import Client
from sdk.models import SignRequest, VerifyRequest

config = Config()
# KMS instance service only allows HTTPS access.
config.protocol = "https"
# Path to the Client Key file.
config.client_key_file = "<CLIENT_KEY_FILE>"
# Client Key decryption password, loaded from an environment variable.
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# Endpoint format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
config.endpoint = "<ENDPOINT>"
client = Client(config)

class SignContext(object):
    """Stores sign response fields needed for subsequent verification."""

    def __init__(self, key_id, message_type, signature, algorithm):
        self.key_id = key_id
        self.message_type = message_type
        self.signature = signature
        # If algorithm is not set, the default value is used.
        self.algorithm = algorithm

def sign(key_id, message, message_type, algorithm):
    request = SignRequest()
    request.key_id = key_id
    request.message = message
    request.message_type = message_type
    request.algorithm = algorithm
    runtime_options = RuntimeOptions()
    # Uncomment the line below to skip server certificate verification.
    # runtime_options.ignore_ssl = True
    # Path to the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.sign_with_options(request, runtime_options)
    print(resp)
    return SignContext(resp.key_id, resp.message_type, resp.signature, resp.algorithm)

def verify(context, message):
    request = VerifyRequest()
    request.key_id = context.key_id
    request.message_type = context.message_type
    request.signature = context.signature
    request.algorithm = context.algorithm
    request.message = message
    runtime_options = RuntimeOptions()
    # Uncomment the line below to skip server certificate verification.
    # runtime_options.ignore_ssl = True
    # Path to the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.verify_with_options(request, runtime_options)
    print(resp)

key_id = "<KEY_ID>"
algorithm = "<ALGORITHM>"
message = "<MESSAGE>".encode("utf-8")
# RAW: pass the raw message. DIGEST: pass the digest of the message.
message_type = "RAW"
context = sign(key_id, message, message_type, algorithm)
verify(context, message)

Kodu çalıştırmadan önce aşağıdaki yer tutucuları değiştirin:

Yer Tutucu Açıklama Örnek
<CLIENT_KEY_FILE> İstemci Anahtarı dosyasının yolu /path/to/clientKey.json
<ENDPOINT> KMS instance uç noktası kst-example.cryptoservice.kms.aliyuncs.com
<CA_CERTIFICATE_FILE_PATH> Instance CA sertifikasının yolu /path/to/ca.pem
<KEY_ID> Asimetrik anahtarın kimliği key-12345abcde
<ALGORITHM> Anahtar tarafından desteklenen imzalama algoritması RSA_PKCS1_SHA_256
<MESSAGE> İmzalanacak veri hello

Adım adım açıklama

İstemciyi başlatma

Tam kurulum talimatları için İstemciyi başlatma bölümüne bakın. config.protocol değerini "https" olarak ayarlayın; KMS instance hizmeti yalnızca HTTPS bağlantılarını kabul eder.

# -*- coding: utf-8 -*-
import os

from openapi.models import Config
from sdk.client import Client

config = Config()
config.protocol = "https"
config.client_key_file = "<CLIENT_KEY_FILE>"
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# Format: <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com
config.endpoint = "<ENDPOINT>"
client = Client(config)

Asimetrik anahtarla verileri imzalama

Dijital imza oluşturmak için Sign API'sini çağırın.

Ham mesajı imzalamak için message_type değerini "RAW" olarak, önceden hesaplanmış mesaj özetini imzalamak için ise "DIGEST" olarak ayarlayın.

def sign(key_id, message, message_type, algorithm):
    request = SignRequest()
    request.key_id = key_id          # ID of the asymmetric key to use
    request.message = message        # Data to sign (bytes)
    request.message_type = message_type  # "RAW" or "DIGEST"
    request.algorithm = algorithm    # Signing algorithm the key supports
    runtime_options = RuntimeOptions()
    # runtime_options.ignore_ssl = True  # Uncomment to skip certificate verification
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.sign_with_options(request, runtime_options)
    print(resp)
    return SignContext(resp.key_id, resp.message_type, resp.signature, resp.algorithm)

Sign yanıtı şunları içerir:

Alan Açıklama
resp.key_id İmzayı oluşturan anahtarın kimliği
resp.signature Dijital imza (bayt cinsinden)
resp.algorithm Kullanılan imzalama algoritması
resp.message_type Mesaj türü (RAW veya DIGEST)

SignContext bu alanları saklar; böylece bunları doğrudan verify() yöntemine iletebilirsiniz.

Dijital imzayı doğrulama

Bir imzayı orijinal mesaja karşı doğrulamak için Verify API'sini çağırın.

def verify(context, message):
    request = VerifyRequest()
    request.key_id = context.key_id          # Must match the key used to sign
    request.message_type = context.message_type
    request.signature = context.signature    # Signature from the Sign response
    request.algorithm = context.algorithm    # Must match the algorithm used to sign
    request.message = message                # Original data (same as what was signed)
    runtime_options = RuntimeOptions()
    # runtime_options.ignore_ssl = True  # Uncomment to skip certificate verification
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.verify_with_options(request, runtime_options)
    print(resp)

Sonraki adımlar