sign_verify.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. import ctypes
  2. # 根据实际情况修改签名验签库名称
  3. SIGN_LIB_NAME = 'libgmsign.so'
  4. VERIFY_LIB_NAME = 'libgmsign.so'
  5. def get_sign(raw_data: str) -> (str, str):
  6. """
  7. 获取签名值
  8. :param raw_data: 原文字符串
  9. :return: tuple(str,str):(签名值base64字符串,公钥base64字符串)
  10. """
  11. # 加载共享库
  12. lib = ctypes.CDLL(SIGN_LIB_NAME)
  13. # 定义函数的参数和返回类型
  14. # 签名函数签名如下:
  15. # int sign(char *key_value, char *hash_value, char *public_key)
  16. lib.sign.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
  17. lib.sign.restype = ctypes.c_int
  18. key_value = raw_data.replace(" ", "").encode('utf-8')
  19. hash_value = ctypes.create_string_buffer(256) # 设置签名值输出缓冲区大小为 256 字节
  20. public_key = ctypes.create_string_buffer(256) # 设置公钥输出缓冲区大小为 256 字节
  21. result = lib.sign(key_value, hash_value, public_key)
  22. if result == 0:
  23. return hash_value.value.decode(), public_key.value.decode()
  24. else:
  25. return None, None
  26. def verify_sign(raw_data: str, sign_data: str, public_key: str) -> bool:
  27. """
  28. 验证签名
  29. :param raw_data: 原文字符串
  30. :param sign_data: 签名值base64字符串
  31. :param public_key: 公钥base64字符串
  32. :return:
  33. """
  34. # 加载共享库
  35. lib = ctypes.CDLL(VERIFY_LIB_NAME)
  36. # 验签函数签名如下:
  37. # int sign_verify(char *content, char *sign_value, char *public_key)
  38. lib.sign_verify.argtypes = [ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p]
  39. lib.sign_verify.restype = ctypes.c_int
  40. content = raw_data.replace(" ", "").encode('utf-8')
  41. sign_value = sign_data.encode('utf-8')
  42. public_key = public_key.encode('utf-8')
  43. verify_result = lib.sign_verify(content, sign_value, public_key)
  44. verify_result = True if verify_result == 1 else False
  45. return verify_result
  46. if __name__ == '__main__':
  47. raw_data = "hello world test sign"
  48. sign_data, public_key = get_sign(raw_data)
  49. print(f"sign_data: {sign_data}\npublic_key: {public_key}")
  50. verify_result = verify_sign(raw_data, sign_data, public_key)
  51. print(f"verify_result: {verify_result}")