import binascii from gmssl import sm2 class ChisCryptoError(Exception): """Raised when CHIS crypto cannot encrypt a required field.""" def sm2_encrypt(public_key, raw_text): if not public_key: raise ChisCryptoError("CHIS public key is not configured") key = public_key if len(key) > 64 * 2: key = key[-64 * 2 :] try: text_bytes = str(raw_text).encode("utf-8") crypt_sm2 = sm2.CryptSM2(public_key=key, private_key="", mode=0) encrypted = crypt_sm2.encrypt(text_bytes) return "04" + binascii.hexlify(encrypted).decode("utf-8") except Exception as exc: raise ChisCryptoError("CHIS SM2 encryption failed") from exc