import ctypes # 根据实际情况修改签名验签库名称 SIGN_LIB_NAME = 'libgmsign.so' VERIFY_LIB_NAME = 'libgmsign.so' def get_sign(raw_data: str) -> (str, str): """ 获取签名值 :param raw_data: 原文字符串 :return: tuple(str,str):(签名值base64字符串,公钥base64字符串) """ # 加载共享库 lib = ctypes.CDLL(SIGN_LIB_NAME) # 定义函数的参数和返回类型 # 签名函数签名如下: # int sign(char *key_value, char *hash_value, char *public_key) lib.sign.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] lib.sign.restype = ctypes.c_int key_value = raw_data.replace(" ", "").encode('utf-8') hash_value = ctypes.create_string_buffer(256) # 设置签名值输出缓冲区大小为 256 字节 public_key = ctypes.create_string_buffer(256) # 设置公钥输出缓冲区大小为 256 字节 result = lib.sign(key_value, hash_value, public_key) if result == 0: return hash_value.value.decode(), public_key.value.decode() else: return None, None def verify_sign(raw_data: str, sign_data: str, public_key: str) -> bool: """ 验证签名 :param raw_data: 原文字符串 :param sign_data: 签名值base64字符串 :param public_key: 公钥base64字符串 :return: """ # 加载共享库 lib = ctypes.CDLL(VERIFY_LIB_NAME) # 验签函数签名如下: # int sign_verify(char *content, char *sign_value, char *public_key) lib.sign_verify.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p] lib.sign_verify.restype = ctypes.c_int content = raw_data.replace(" ", "").encode('utf-8') sign_value = sign_data.encode('utf-8') public_key = public_key.encode('utf-8') verify_result = lib.sign_verify(content, sign_value, public_key) verify_result = True if verify_result == 1 else False return verify_result if __name__ == '__main__': raw_data = "hello world test sign" sign_data, public_key = get_sign(raw_data) print(f"sign_data: {sign_data}\npublic_key: {public_key}") verify_result = verify_sign(raw_data, sign_data, public_key) print(f"verify_result: {verify_result}")