|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Fix SM2 certificate SubjectPublicKeyInfo algorithm OID. |
| 3 | +
|
| 4 | +OpenSSL 3.x encodes SM2 keys using the generic id-ecPublicKey OID |
| 5 | +(1.2.840.10045.2.1) instead of the SM2-specific OID (1.2.156.10197.1.301). |
| 6 | +This script patches the SPKI algorithm OID back to SM2 and re-signs the |
| 7 | +certificate. |
| 8 | +
|
| 9 | +Usage: fix_sm2_spki.py <cert.pem> <signing-key.pem> <output.pem> |
| 10 | +""" |
| 11 | + |
| 12 | +import base64 |
| 13 | +import subprocess |
| 14 | +import sys |
| 15 | +import os |
| 16 | +import tempfile |
| 17 | + |
| 18 | +EC_PUBKEY_OID = bytes([0x06, 0x07, 0x2a, 0x86, 0x48, 0xce, 0x3d, 0x02, 0x01]) |
| 19 | +SM2_ALGO_OID = bytes([0x06, 0x08, 0x2a, 0x81, 0x1c, 0xcf, 0x55, 0x01, 0x82, 0x2d]) |
| 20 | +SM2_WITH_SM3 = bytes([0x30, 0x0a, 0x06, 0x08, |
| 21 | + 0x2a, 0x81, 0x1c, 0xcf, 0x55, 0x01, 0x83, 0x75]) |
| 22 | + |
| 23 | + |
| 24 | +def read_der_length(data, offset): |
| 25 | + b = data[offset] |
| 26 | + if b < 0x80: |
| 27 | + return b, 1 |
| 28 | + num_bytes = b & 0x7f |
| 29 | + length = 0 |
| 30 | + for i in range(num_bytes): |
| 31 | + length = (length << 8) | data[offset + 1 + i] |
| 32 | + return length, 1 + num_bytes |
| 33 | + |
| 34 | + |
| 35 | +def encode_der_length(length): |
| 36 | + if length < 0x80: |
| 37 | + return bytes([length]) |
| 38 | + elif length < 0x100: |
| 39 | + return bytes([0x81, length]) |
| 40 | + elif length < 0x10000: |
| 41 | + return bytes([0x82, length >> 8, length & 0xff]) |
| 42 | + else: |
| 43 | + raise ValueError("Length too large: %d" % length) |
| 44 | + |
| 45 | + |
| 46 | +def find_enclosing_sequences(data, target_pos): |
| 47 | + """Find length-field offsets of all SEQUENCEs enclosing target_pos.""" |
| 48 | + results = [] |
| 49 | + |
| 50 | + def scan(offset, end): |
| 51 | + while offset < end: |
| 52 | + tag = data[offset] |
| 53 | + offset += 1 |
| 54 | + length, len_bytes = read_der_length(data, offset) |
| 55 | + len_offset = offset |
| 56 | + offset += len_bytes |
| 57 | + content_start = offset |
| 58 | + content_end = offset + length |
| 59 | + |
| 60 | + if tag == 0x30 and content_start <= target_pos < content_end: |
| 61 | + results.append((len_offset, length, len_bytes)) |
| 62 | + scan(content_start, content_end) |
| 63 | + return |
| 64 | + offset = content_end |
| 65 | + |
| 66 | + scan(0, len(data)) |
| 67 | + return results |
| 68 | + |
| 69 | + |
| 70 | +def patch_tbs_spki_oid(tbs_der): |
| 71 | + """Replace id-ecPublicKey with SM2 OID in TBS SubjectPublicKeyInfo.""" |
| 72 | + oid_pos = tbs_der.find(EC_PUBKEY_OID) |
| 73 | + if oid_pos == -1: |
| 74 | + return None # Already has SM2 OID or no EC key |
| 75 | + |
| 76 | + enclosing = find_enclosing_sequences(tbs_der, oid_pos) |
| 77 | + size_diff = len(SM2_ALGO_OID) - len(EC_PUBKEY_OID) |
| 78 | + |
| 79 | + result = bytearray( |
| 80 | + tbs_der[:oid_pos] + SM2_ALGO_OID + tbs_der[oid_pos + len(EC_PUBKEY_OID):] |
| 81 | + ) |
| 82 | + |
| 83 | + for len_offset, old_length, old_len_bytes in enclosing: |
| 84 | + new_length = old_length + size_diff |
| 85 | + new_len_encoded = encode_der_length(new_length) |
| 86 | + if len(new_len_encoded) == old_len_bytes: |
| 87 | + result[len_offset:len_offset + old_len_bytes] = new_len_encoded |
| 88 | + else: |
| 89 | + result[len_offset:len_offset + old_len_bytes] = new_len_encoded |
| 90 | + size_diff += len(new_len_encoded) - old_len_bytes |
| 91 | + |
| 92 | + return bytes(result) |
| 93 | + |
| 94 | + |
| 95 | +def pem_to_der(pem_text): |
| 96 | + b64 = ''.join( |
| 97 | + line for line in pem_text.split('\n') |
| 98 | + if not line.startswith('-----') and line.strip() |
| 99 | + ) |
| 100 | + return base64.b64decode(b64) |
| 101 | + |
| 102 | + |
| 103 | +def der_to_pem(der_data, label="CERTIFICATE"): |
| 104 | + b64 = base64.b64encode(der_data).decode() |
| 105 | + lines = [b64[i:i+64] for i in range(0, len(b64), 64)] |
| 106 | + return ('-----BEGIN %s-----\n' % label + |
| 107 | + '\n'.join(lines) + |
| 108 | + '\n-----END %s-----\n' % label) |
| 109 | + |
| 110 | + |
| 111 | +def extract_tbs(cert_der): |
| 112 | + assert cert_der[0] == 0x30 |
| 113 | + outer_len, outer_len_bytes = read_der_length(cert_der, 1) |
| 114 | + tbs_offset = 1 + outer_len_bytes |
| 115 | + tbs_len, tbs_len_bytes = read_der_length(cert_der, tbs_offset + 1) |
| 116 | + tbs_total = 1 + tbs_len_bytes + tbs_len |
| 117 | + return cert_der[tbs_offset:tbs_offset + tbs_total] |
| 118 | + |
| 119 | + |
| 120 | +def sign_tbs(tbs_der, key_pem_path): |
| 121 | + """Sign TBS with SM2-with-SM3 using openssl dgst.""" |
| 122 | + with tempfile.NamedTemporaryFile(suffix='.der', delete=False) as tbs_f: |
| 123 | + tbs_f.write(tbs_der) |
| 124 | + tbs_path = tbs_f.name |
| 125 | + |
| 126 | + sig_path = tbs_path + '.sig' |
| 127 | + try: |
| 128 | + result = subprocess.run( |
| 129 | + ['openssl', 'dgst', '-sm3', '-sign', key_pem_path, |
| 130 | + '-out', sig_path, tbs_path], |
| 131 | + capture_output=True, text=True |
| 132 | + ) |
| 133 | + if result.returncode != 0: |
| 134 | + raise RuntimeError("openssl dgst failed: " + result.stderr) |
| 135 | + |
| 136 | + with open(sig_path, 'rb') as f: |
| 137 | + return f.read() |
| 138 | + finally: |
| 139 | + os.unlink(tbs_path) |
| 140 | + if os.path.exists(sig_path): |
| 141 | + os.unlink(sig_path) |
| 142 | + |
| 143 | + |
| 144 | +def build_cert(tbs_der, sig_der): |
| 145 | + bit_string = bytes([0x03, len(sig_der) + 1, 0x00]) + sig_der |
| 146 | + cert_body = tbs_der + SM2_WITH_SM3 + bit_string |
| 147 | + return bytes([0x30]) + encode_der_length(len(cert_body)) + cert_body |
| 148 | + |
| 149 | + |
| 150 | +def fix_sm2_cert(cert_pem_path, key_pem_path, output_pem_path): |
| 151 | + with open(cert_pem_path, 'r') as f: |
| 152 | + cert_pem = f.read() |
| 153 | + |
| 154 | + cert_der = pem_to_der(cert_pem) |
| 155 | + tbs = extract_tbs(cert_der) |
| 156 | + |
| 157 | + new_tbs = patch_tbs_spki_oid(tbs) |
| 158 | + if new_tbs is None: |
| 159 | + print(" Already has SM2 OID, no patching needed") |
| 160 | + if cert_pem_path != output_pem_path: |
| 161 | + with open(output_pem_path, 'w') as f: |
| 162 | + f.write(cert_pem) |
| 163 | + return |
| 164 | + |
| 165 | + sig = sign_tbs(new_tbs, key_pem_path) |
| 166 | + new_cert_der = build_cert(new_tbs, sig) |
| 167 | + |
| 168 | + with open(output_pem_path, 'w') as f: |
| 169 | + f.write(der_to_pem(new_cert_der)) |
| 170 | + |
| 171 | + print(" Patched SPKI algorithm OID to SM2") |
| 172 | + |
| 173 | + |
| 174 | +if __name__ == '__main__': |
| 175 | + if len(sys.argv) != 4: |
| 176 | + print("Usage: %s <cert.pem> <signing-key.pem> <output.pem>" % sys.argv[0]) |
| 177 | + sys.exit(1) |
| 178 | + |
| 179 | + fix_sm2_cert(sys.argv[1], sys.argv[2], sys.argv[3]) |
0 commit comments