初始化KMS執行個體SDK用戶端後,您可以通過用戶端調用Sign和Verify介面進行簽名驗簽。本文介紹簽名驗簽的程式碼範例。
完整程式碼範例
調用Sign介面使用非對稱金鑰進行數位簽章,調用Verify介面使用非對稱金鑰驗證數位簽章。
Python 2版本源碼github地址:sign_verify_sample.py
Python 3版本源碼github地址:sign_verify_sample.py
本文以Python 3版本為例介紹。
程式碼範例解析
初始化用戶端
關於初始化用戶端的詳細介紹,請參見初始化用戶端。
# -*- coding: utf-8 -*-
from openapi.models import Config
from sdk.client import Client
config = Config()
# 連線協定請設定為"https"。KMS執行個體服務僅允許通過HTTPS協議訪問。
config.protocol = "https"
# Client Key。
config.client_key_file = "<your-client-key-file>"
# Client Key解密口令。
config.password = os.getenv('CLIENT_KEY_PASSWORD')
# 設定endpoint為<your KMS Instance Id>.cryptoservice.kms.aliyuncs.com。
config.endpoint = "<your-endpoint>"
client = Client(config)調用Sign介面使用非對稱金鑰進行數位簽章
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()
# 忽略服務端認證
# runtime_options.ignore_ssl = True
# verify表示執行個體CA認證的路徑
runtime_options.verify = "<your-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)
調用Verify介面使用非對稱金鑰驗證數位簽章
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()
# 忽略服務端認證
# runtime_options.ignore_ssl = True
# verify表示執行個體CA認證的路徑
runtime_options.verify = "<your-ca-certificate-file-path>"
resp = client.verify_with_options(request, runtime_options)
print(resp)