你当前正在访问 Microsoft Azure Global Edition 技术文档网站。 如果需要访问由世纪互联运营的 Microsoft Azure 中国技术文档网站,请访问 https://docs.azure.cn。

验证 Azure 机密账本写入交易收据

Azure 机密账本写入事务收据表示一个加密的 Merkle 证明,证明相应的写入事务已由 CCF 网络全局提交。 Azure机密账本用户可以在任何时间点获取已提交的写入事务的收据,以验证相应的写入操作是否已成功记录到不可变账本中。

有关 Azure 机密账本写事务收据的详细信息,请参阅专题文章。

收据验证步骤

可以按照以下小节中概述的一组特定步骤验证写入事务收据。 CCF 文档中概述了相同的步骤。

叶节点计算

第一步是计算 Merkle 树中与已提交交易对应的叶节点的 SHA-256 哈希值。 叶节点由以下字段按顺序串联组成,这些字段可在 Azure 机密账本收据中位于 leafComponents 下找到:

  1. writeSetDigest
  2. SHA-256 摘要 commitEvidence
  3. claimsDigest 字段

这些值需要串联为字节数组:这两个值writeSetDigestclaimsDigest都需要从十六进制数字的字符串转换为字节数组;另一方面,可以通过对 UTF-8 编码commitEvidence字符串应用 SHA-256 哈希函数来获取(作为字节数组)的哈希commitEvidence。

同样,叶节点哈希摘要可以通过将生成的字节串联后应用 SHA-256 哈希函数来计算。

根节点计算

第二步是在提交事务时计算 Merkle 树根的 SHA-256 哈希。 计算是通过迭代方式,将上一次迭代结果(从上一步计算的叶节点哈希开始)与收据的 proof 字段中提供的有序节点哈希连接起来并进行哈希来完成的。 该 proof 列表以有序列表的形式提供,并且其元素需要按给定顺序进行迭代。

需要根据 proof 字段中提供的对象(left 或 right)中指示的相对顺序对字节表示进行连接。

  • 如果当前元素 proof 的键位于 left其中,则应将上一次迭代的结果追加到当前元素值。
  • 如果当前元素 proof 的键位于 right其中,则应将上一次迭代的结果追加到当前元素值。

每次串联后,都需要应用 SHA-256 函数才能获取下一次迭代的输入。 此过程遵循标准步骤,根据计算所需的节点来计算 Merkle 树 数据结构的根节点。

验证根节点的签名

第三步是使用收据中的签名节点证书验证通过根节点哈希生成的加密签名是否有效。 验证过程遵循使用 椭圆曲线数字签名算法(ECDSA)对使用椭圆曲线数字签名算法(ECDSA)签名的消息进行数字签名验证的标准步骤。 更具体地说,步骤如下:

  1. 将 base64 字符串 signature 解码为字节数组。
  2. 从签名节点证书 cert中提取 ECDSA 公钥。
  3. 使用上一步提取的公钥验证基于 Merkle 树根的签名(使用上一个子节中的说明计算)是否真实。 此步骤有效地对应于使用 ECDSA 的标准 数字签名 验证过程。 在一些流行的编程语言中,有许多库可以使用公钥证书来验证某些数据上的 ECDSA 签名(例如,Python 的 cryptography 库)。

验证签名节点证书背书

除了上一步,还需要验证签名节点证书是否由当前账本证书背书(即已签名)。 此步骤不依赖于前三个步骤,可以独立于其他步骤执行。

颁发收据的当前服务标识可能不同于认可签名节点的服务标识(例如,由于证书续订)。 在这种情况下,需要验证从签名节点证书(即收据中的cert字段)到受信任的根证书颁发机构(CA)(即当前服务标识证书)的证书信任链。这一验证通过其他以前的服务标识进行(即收据中的serviceEndorsements列表字段)。 该 serviceEndorsements 列表作为从最早到最新服务标识的有序列表提供。

需要针对整个链验证证书认可,并遵循上一小节中概述的完全相同的数字签名验证过程。 有常用的开源加密库(例如 OpenSSL)可用于执行证书认可步骤。

验证应用程序声明摘要

作为一个可选步骤,如果收据附带了应用声明,则可以从已公开的声明(遵循特定算法)计算声明摘要,并验证该摘要是否与收据有效负载中的 claimsDigest 匹配。 若要从公开的声明对象中计算摘要值,请循环访问列表中的每个应用程序声明对象并检查其 kind 字段。

如果声明对象为类型 LedgerEntry,则应提取声明的账本集合 ID(collectionId)和内容(contents),并用于使用声明对象中指定的密钥(secretKey)计算其 HMAC 摘要。 然后将这两个摘要连接起来,计算连接后的 SHA-256 哈希值。 然后,将协议(protocol)和生成的声明数据摘要串联,并计算该串联结果的另一个 SHA-256 哈希以获取最终摘要。

如果声明对象为类型 ClaimDigest,则应提取声明摘要(value),并与协议(protocol)连接,并计算串联的 SHA-256 哈希以获取最终摘要。

在计算完每个单独的声明摘要后,有必要将每个应用程序声明对象的所有计算摘要连接起来(以与收据中显示的顺序相同)。 然后,连接前应加上处理的声明数量。 前面连接的 SHA-256 哈希产生最终声明摘要,该摘要应与收据对象中存在的 claimsDigest 匹配。

更多资源

有关 Azure 机密账本写入事务收据的内容以及各字段说明的详细信息,请参阅专题文章。 CCF 文档还包含以下链接中有关收据验证和其他相关资源的详细信息:

验证事务回执

收据验证实用工具

用于Python的Azure机密账本客户端库提供实用工具函数,用于验证写入事务收据,并从应用程序声明列表中计算声明摘要。 有关如何使用数据平面 SDK 和特定于收据的实用工具的详细信息,请参阅以下部分和 以下示例代码。

设置和先决条件

出于参考目的,我们在Python中提供了示例代码,以完全验证Azure机密账本写入事务回执,具体步骤如下。

若要运行完整的验证算法,需要当前服务网络证书和正在运行的Azure机密账本资源的写入事务收据。 有关如何从 Azure 机密账本实例提取写入事务收据和服务证书的详细信息,请参阅“获取写入事务收据”。

代码演练

以下代码可用于初始化所需的对象并运行收据验证算法。 单独的实用工具 (verify_receipt) 用于运行完整的验证算法,并接受响应中receipt字段的内容GET_RECEIPT作为字典,服务证书作为简单字符串。 如果收据无效或在处理过程中遇到任何错误,该函数将引发异常。

可以从文件加载回执和服务证书。 使用要验证的服务证书和回执的相应文件名,更新 service_certificate_file_name 和 receipt_file_name 两个常量。

import json 

# Constants
service_certificate_file_name = "<service-certificate-file>"
receipt_file_name = "<receipt-file>"

# Use the receipt and the service identity to verify the receipt content 
with open(service_certificate_file_name, "r") as service_certificate_file, open( 
    receipt_file_name, "r" 
) as receipt_file: 

    # Load relevant files content 
    receipt = json.loads(receipt_file.read())["receipt"] 
    service_certificate_cert = service_certificate_file.read() 

    try: 
        verify_receipt(receipt, service_certificate_cert) 
        print("Receipt verification succeeded") 

    except Exception as e: 
        print("Receipt verification failed") 

        # Raise caught exception to look at the error stack
        raise e 

由于验证过程需要一些加密和哈希基元,因此以下库用于促进计算。

  • CCF Python 库:模块提供了一组用于收据验证的工具。
  • Python加密库:一个广泛使用的库,其中包括各种加密算法和基元。
  • hashlib 模块是Python标准库的一部分:一个模块,为常用哈希算法提供通用接口。
from ccf.receipt import verify, check_endorsements, root 
from cryptography.x509 import load_pem_x509_certificate, Certificate 
from hashlib import sha256 
from typing import Dict, List, Any 

在函数中 verify_receipt ,我们检查给定收据是否有效,并包含所有必填字段。

# Check that all the fields are present in the receipt 
assert "cert" in receipt 
assert "leafComponents" in receipt 
assert "claimsDigest" in receipt["leafComponents"] 
assert "commitEvidence" in receipt["leafComponents"] 
assert "writeSetDigest" in receipt["leafComponents"] 
assert "proof" in receipt 
assert "signature" in receipt 

我们将初始化要在程序其余部分使用的变量。

# Set the variables 
node_cert_pem = receipt["cert"] 
claims_digest_hex = receipt["leafComponents"]["claimsDigest"] 
commit_evidence_str = receipt["leafComponents"]["commitEvidence"] 
write_set_digest_hex = receipt["leafComponents"]["writeSetDigest"] 
proof_list = receipt["proof"] 
service_endorsements_certs_pem = receipt.get("serviceEndorsements", [])
root_node_signature = receipt["signature"] 

我们可以使用加密库加载服务标识、签名节点和以前服务标识中的认可证书的 PEM 证书。

# Load service and node PEM certificates 
service_cert = load_pem_x509_certificate(service_cert_pem.encode()) 
node_cert = load_pem_x509_certificate(node_cert_pem.encode()) 

# Load service endorsements PEM certificates 
service_endorsements_certs = [ 
    load_pem_x509_certificate(pem.encode()) 
    for pem in service_endorsements_certs_pem 
] 

验证过程的第一步是计算叶节点的摘要。

# Compute leaf of the Merkle Tree corresponding to our transaction 
leaf_node_hex = compute_leaf_node( 
    claims_digest_hex, commit_evidence_str, write_set_digest_hex 
)

compute_leaf_node 函数接受收据的叶组件(即 claimsDigest、commitEvidence 和 writeSetDigest)作为参数,并以十六进制形式返回叶节点哈希。

如前所述,我们计算 commitEvidence 的摘要(使用 SHA-256 hashlib 函数)。 然后,我们将这两者writeSetDigestclaimsDigest转换为字节数组。 最后,连接三个数组,并使用 SHA256 函数消化结果。

def compute_leaf_node( 
    claims_digest_hex: str, commit_evidence_str: str, write_set_digest_hex: str 
) -> str: 
    """Function to compute the leaf node associated to a transaction 
    given its claims digest, commit evidence, and write set digest.""" 

    # Digest commit evidence string 
    commit_evidence_digest = sha256(commit_evidence_str.encode()).digest() 

    # Convert write set digest to bytes 
    write_set_digest = bytes.fromhex(write_set_digest_hex) 

    # Convert claims digest to bytes 
    claims_digest = bytes.fromhex(claims_digest_hex) 

    # Create leaf node by hashing the concatenation of its three components 
    # as bytes objects in the following order: 
    # 1. write_set_digest 
    # 2. commit_evidence_digest 
    # 3. claims_digest 
    leaf_node_digest = sha256( 
        write_set_digest + commit_evidence_digest + claims_digest 
    ).digest() 

    # Convert the result into a string of hexadecimal digits 
    return leaf_node_digest.hex() 

计算叶后,我们可以计算 Merkle 树的根。

# Compute root of the Merkle Tree 
root_node = root(leaf_node_hex, proof_list) 

我们使用作为 CCF Python 库的一部分提供的函数 root。 该函数依次将上一次迭代的结果与新元素 proof连接在一起,对串联进行摘要,然后对前面计算的摘要中的每个 proof 元素重复该步骤。 串联需要遵循 Merkle 树中节点的顺序,以确保正确重新计算根。

def root(leaf: str, proof: List[dict]): 
    """ 
    Recompute root of Merkle tree from a leaf and a proof of the form: 
    [{"left": digest}, {"right": digest}, ...] 
    """ 

    current = bytes.fromhex(leaf) 

    for n in proof: 
        if "left" in n: 
            current = sha256(bytes.fromhex(n["left"]) + current).digest() 
        else: 
            current = sha256(current + bytes.fromhex(n["right"])).digest() 
    return current.hex() 

计算根节点哈希后,我们可以通过根验证收据中包含的签名,以验证签名是否正确。

# Verify signature of the signing node over the root of the tree 
verify(root_node, root_node_signature, node_cert) 

同样,CCF 库提供了一个用于执行此验证的函数 verify 。 我们使用签名节点证书的 ECDSA 公钥来验证树根上的签名。

def verify(root: str, signature: str, cert: Certificate):
    """ 
    Verify signature over root of Merkle Tree 
    """ 

    sig = base64.b64decode(signature) 
    pk = cert.public_key() 
    assert isinstance(pk, ec.EllipticCurvePublicKey) 
    pk.verify( 
        sig, 
        bytes.fromhex(root), 
        ec.ECDSA(utils.Prehashed(hashes.SHA256())), 
    )

收据验证的最后一步是验证用于对 Merkle 树的根签名的证书。

# Verify node certificate is endorsed by the service certificates through endorsements 
check_endorsements(node_cert, service_cert, service_endorsements_certs) 

同样,我们也可以使用 CCF 实用工具 check_endorsements 来验证服务标识是否认可签名节点。 证书链可以由以前的服务证书组成;因此,如果 serviceEndorsements 不是空列表,则应验证认可是否可传递应用。

def check_endorsement(endorsee: Certificate, endorser: Certificate): 
    """ 
    Check endorser has endorsed endorsee 
    """ 

    digest_algo = endorsee.signature_hash_algorithm 
    assert digest_algo 
    digester = hashes.Hash(digest_algo) 
    digester.update(endorsee.tbs_certificate_bytes) 
    digest = digester.finalize() 
    endorser_pk = endorser.public_key() 
    assert isinstance(endorser_pk, ec.EllipticCurvePublicKey) 
    endorser_pk.verify( 
        endorsee.signature, digest, ec.ECDSA(utils.Prehashed(digest_algo)) 
    ) 

def check_endorsements( 
    node_cert: Certificate, service_cert: Certificate, endorsements: List[Certificate] 
): 
    """ 
    Check a node certificate is endorsed by a service certificate, transitively through a list of endorsements. 
    """ 

    cert_i = node_cert 
    for endorsement in endorsements: 
        check_endorsement(cert_i, endorsement) 
        cert_i = endorsement 
    check_endorsement(cert_i, service_cert) 

作为替代方法,我们还可以使用类似的方法使用 OpenSSL 库来验证证书。

from OpenSSL.crypto import ( 
    X509, 
    X509Store, 
    X509StoreContext, 
)

def verify_openssl_certificate( 
    node_cert: Certificate, 
    service_cert: Certificate, 
    service_endorsements_certs: List[Certificate], 
) -> None: 
    """Verify that the given node certificate is a valid OpenSSL certificate through 
    the service certificate and a list of endorsements certificates.""" 

    store = X509Store() 

    # pyopenssl does not support X509_V_FLAG_NO_CHECK_TIME. For recovery of expired 
    # services and historical receipts, we want to ignore the validity time. 0x200000 
    # is the bitmask for this option in more recent versions of OpenSSL. 
    X509_V_FLAG_NO_CHECK_TIME = 0x200000 
    store.set_flags(X509_V_FLAG_NO_CHECK_TIME) 

    # Add service certificate to the X.509 store 
    store.add_cert(X509.from_cryptography(service_cert)) 

    # Prepare X.509 endorsement certificates 
    certs_chain = [X509.from_cryptography(cert) for cert in service_endorsements_certs] 

    # Prepare X.509 node certificate 
    node_cert_pem = X509.from_cryptography(node_cert) 

    # Create X.509 store context and verify its certificate 
    ctx = X509StoreContext(store, node_cert_pem, certs_chain) 
    ctx.verify_certificate() 

代码示例

提供了代码演练中使用的完整示例代码。

主程序

import json 

# Use the receipt and the service identity to verify the receipt content 
with open("network_certificate.pem", "r") as service_certificate_file, open( 
    "receipt.json", "r" 
) as receipt_file: 

    # Load relevant files content 
    receipt = json.loads(receipt_file.read())["receipt"]
    service_certificate_cert = service_certificate_file.read()

    try: 
        verify_receipt(receipt, service_certificate_cert) 
        print("Receipt verification succeeded") 

    except Exception as e: 
        print("Receipt verification failed") 

        # Raise caught exception to look at the error stack 
        raise e 

收据验证

from cryptography.x509 import load_pem_x509_certificate, Certificate 
from hashlib import sha256 
from typing import Dict, List, Any 

from OpenSSL.crypto import ( 
    X509, 
    X509Store, 
    X509StoreContext, 
) 

from ccf.receipt import root, verify, check_endorsements 

def verify_receipt(receipt: Dict[str, Any], service_cert_pem: str) -> None: 
    """Function to verify that a given write transaction receipt is valid based 
    on its content and the service certificate. 
    Throws an exception if the verification fails.""" 

    # Check that all the fields are present in the receipt 
    assert "cert" in receipt 
    assert "leafComponents" in receipt 
    assert "claimsDigest" in receipt["leafComponents"] 
    assert "commitEvidence" in receipt["leafComponents"] 
    assert "writeSetDigest" in receipt["leafComponents"] 
    assert "proof" in receipt 
    assert "signature" in receipt 

    # Set the variables 
    node_cert_pem = receipt["cert"] 
    claims_digest_hex = receipt["leafComponents"]["claimsDigest"] 
    commit_evidence_str = receipt["leafComponents"]["commitEvidence"] 

    write_set_digest_hex = receipt["leafComponents"]["writeSetDigest"] 
    proof_list = receipt["proof"] 
    service_endorsements_certs_pem = receipt.get("serviceEndorsements", [])
    root_node_signature = receipt["signature"] 

    # Load service and node PEM certificates
    service_cert = load_pem_x509_certificate(service_cert_pem.encode()) 
    node_cert = load_pem_x509_certificate(node_cert_pem.encode()) 

    # Load service endorsements PEM certificates
    service_endorsements_certs = [ 
        load_pem_x509_certificate(pem.encode()) 
        for pem in service_endorsements_certs_pem 
    ] 

    # Compute leaf of the Merkle Tree 
    leaf_node_hex = compute_leaf_node( 
        claims_digest_hex, commit_evidence_str, write_set_digest_hex 
    ) 

    # Compute root of the Merkle Tree
    root_node = root(leaf_node_hex, proof_list) 

    # Verify signature of the signing node over the root of the tree
    verify(root_node, root_node_signature, node_cert) 

    # Verify node certificate is endorsed by the service certificates through endorsements
    check_endorsements(node_cert, service_cert, service_endorsements_certs) 

    # Alternative: Verify node certificate is endorsed by the service certificates through endorsements 
    verify_openssl_certificate(node_cert, service_cert, service_endorsements_certs) 

def compute_leaf_node( 
    claims_digest_hex: str, commit_evidence_str: str, write_set_digest_hex: str 
) -> str: 
    """Function to compute the leaf node associated to a transaction 
    given its claims digest, commit evidence, and write set digest.""" 

    # Digest commit evidence string
    commit_evidence_digest = sha256(commit_evidence_str.encode()).digest() 

    # Convert write set digest to bytes
    write_set_digest = bytes.fromhex(write_set_digest_hex) 

    # Convert claims digest to bytes
    claims_digest = bytes.fromhex(claims_digest_hex) 

    # Create leaf node by hashing the concatenation of its three components 
    # as bytes objects in the following order: 
    # 1. write_set_digest 
    # 2. commit_evidence_digest 
    # 3. claims_digest 
    leaf_node_digest = sha256( 
        write_set_digest + commit_evidence_digest + claims_digest 
    ).digest() 

    # Convert the result into a string of hexadecimal digits 
    return leaf_node_digest.hex() 

def verify_openssl_certificate( 
    node_cert: Certificate, 
    service_cert: Certificate, 
    service_endorsements_certs: List[Certificate], 
) -> None: 
    """Verify that the given node certificate is a valid OpenSSL certificate through 
    the service certificate and a list of endorsements certificates.""" 

    store = X509Store() 

    # pyopenssl does not support X509_V_FLAG_NO_CHECK_TIME. For recovery of expired 
    # services and historical receipts, we want to ignore the validity time. 0x200000 
    # is the bitmask for this option in more recent versions of OpenSSL. 
    X509_V_FLAG_NO_CHECK_TIME = 0x200000 
    store.set_flags(X509_V_FLAG_NO_CHECK_TIME) 

    # Add service certificate to the X.509 store
    store.add_cert(X509.from_cryptography(service_cert)) 

    # Prepare X.509 endorsement certificates
    certs_chain = [X509.from_cryptography(cert) for cert in service_endorsements_certs] 

    # Prepare X.509 node certificate
    node_cert_pem = X509.from_cryptography(node_cert) 

    # Create X.509 store context and verify its certificate
    ctx = X509StoreContext(store, node_cert_pem, certs_chain) 
    ctx.verify_certificate() 

后续步骤