Tüm Ürünler
Search
Belge Merkezi

Key Management Service:Sample code for encryption and decryption

Son Güncelleme:Oct 04, 2026

Simetrik anahtar şifreleme ve şifre çözme işlemleri için KMS örnek SDK istemcisini kullanarak Encrypt ve Decrypt API'lerini çağırın. Bu sayfadaki örnekler Python 3 kullanmaktadır.

GitHub'daki tam kaynak kodu:

Tam örnek

Aşağıdaki örnek; istemciyi başlatma, düz metni şifreleme ve ardından ortaya çıkan şifreli metnin şifresini çözme adımlarını sırasıyla gösterir.

# -*- 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 EncryptRequest, DecryptRequest

config = Config()
# Set the connection protocol to "https". The KMS instance service only allows access through the HTTPS protocol.
config.protocol = "https"
# Client Key.
config.client_key_file = "<CLIENT_KEY_FILE>"
# Client Key decryption password.
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# Set the endpoint to <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com.
config.endpoint = "<ENDPOINT>"
client = Client(config)

class AESEncryptContext(object):
    """The aes encrypt context may be stored."""

    def __init__(self, key_id, ciphertext_blob, iv, algorithm):
        self.key_id = key_id
        self.ciphertext_blob = ciphertext_blob
        self.iv = iv
        # Use default algorithm value, if the value is not set.
        self.algorithm = algorithm

def encrypt(key_id, plaintext):
    request = EncryptRequest()
    request.plaintext = plaintext
    request.key_id = key_id
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.encrypt_with_options(request, runtime_options)
    print(resp)
    return AESEncryptContext(resp.key_id, resp.ciphertext_blob, resp.iv, resp.algorithm)

def decrypt(context):
    request = DecryptRequest()
    request.ciphertext_blob = context.ciphertext_blob
    request.key_id = context.key_id
    request.iv = context.iv
    request.algorithm = context.algorithm
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.decrypt_with_options(request, runtime_options)
    print(resp)

plaintext = "<PLAINTEXT>".encode("utf-8")
key_id = "<KEY_ID>"
context = encrypt(key_id, plaintext)
decrypt(context)

Örnek adım adım açıklama

İstemciyi başlatma

Herhangi bir API çağrısı yapmadan önce istemciyi KMS örnek kimlik bilgilerinizle yapılandırın. KMS örnek hizmeti HTTPS gerektirir; istemciyi oluşturmadan önce config.protocol değerini "https" olarak ayarlayın.

Aşağıdaki yer tutucuları gerçek değerlerle değiştirin:

Yer Tutucu Açıklama
<CLIENT_KEY_FILE> İstemci Anahtarı dosyanızın yolu. İstemci Anahtarı, KMS örneği ile kimlik doğrulaması yapmak için kullanılan kimlik bilgisi dosyasıdır.
CLIENT_KEY_PASSWORD İstemci Anahtarı şifre çözme parolanızı içeren ortam değişkeninin adı.
<ENDPOINT> <KMS_INSTANCE_ID>.cryptoservice.kms.aliyuncs.com formatındaki KMS örnek uç noktanız.

Ayrıntılar için bkz. İstemciyi başlatma.

# -*- coding: utf-8 -*-
from openapi.models import Config
from sdk.client import Client

config = Config()
# The connection protocol. Set the value to https. The KMS instance service only allows access through the HTTPS protocol.
config.protocol = "https"

# Client Key.
config.client_key_file = "<CLIENT_KEY_FILE>"

# Client Key decryption password.
config.password = os.getenv('CLIENT_KEY_PASSWORD')

# The endpoint of your KMS instance. Set the value in the following format: <ID of your KMS instance>.cryptoservice.kms.aliyuncs.com.
config.endpoint = "<ENDPOINT>"
client = Client(config)

Simetrik bir anahtar kullanarak verileri şifrelemek için Encrypt API'sini çağırma

encrypt işlevi, bir düz metin değerini ve bir anahtar kimliğini Encrypt API'sine gönderir. API, başlatma vektörü (iv) ve kullanılan şifreleme algoritması ile birlikte bir şifreli metin blob'u döndürür. Şifreli metnin daha sonra şifresini çözmek için bu üç değerin tamamı gereklidir; şifrelenmiş verilerinizin yanında tüm AESEncryptContext nesnesini saklayın.

HTTPS bağlantısını doğrulamak için runtime_options.verify değerini KMS örnek CA sertifikanızın yoluna ayarlayın. Geliştirme sırasında sertifika doğrulamasını atlamak için runtime_options.ignore_ssl = True satırının yorumunu kaldırın.

def encrypt(key_id, plaintext):
    request = EncryptRequest()
    request.plaintext = plaintext
    request.key_id = key_id
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.encrypt_with_options(request, runtime_options)
    print(resp)
    return AESEncryptContext(resp.key_id, resp.ciphertext_blob, resp.iv, resp.algorithm)

Simetrik bir anahtar kullanarak şifreli metnin şifresini çözmek için Decrypt API'sini çağırma

decrypt işlevi; şifreli metin blob'u, anahtar kimliği, başlatma vektörü ve algoritma dahil olmak üzere tam AESEncryptContext nesnesini Decrypt API'sine iletir. iv ve algorithm değerleri, Encrypt API'sinin döndürdüğü değerlerle tam olarak eşleşmelidir; KMS örneği orijinal düz metni yeniden oluşturmak için bu değerleri kullanır.

def decrypt(context):
    request = DecryptRequest()
    request.ciphertext_blob = context.ciphertext_blob
    request.key_id = context.key_id
    request.iv = context.iv
    request.algorithm = context.algorithm
    runtime_options = RuntimeOptions()
    # Ignore server certificate.
    # runtime_options.ignore_ssl = True
    # verify indicates the path of the instance CA certificate.
    runtime_options.verify = "<CA_CERTIFICATE_FILE_PATH>"
    resp = client.decrypt_with_options(request, runtime_options)
    print(resp)

Sonraki adımlar