ynet-sdk-python 0.0.2__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
ynet_sdk/__init__.py ADDED
@@ -0,0 +1,50 @@
1
+ """Ynet 数据中心开放平台 Python SDK。
2
+
3
+ 当前版本(v0.0.2)提供 API 请求的**签名与验签**能力,对应 Java 版
4
+ ``com.belink.sdk.common.sign.OpenApiSignUtil``,两端签名结果逐字节一致。
5
+ 自 0.0.2 起,``dict`` / ``list`` 等复杂参数按 Java 版相同的 fastjson2 规则
6
+ 序列化为 JSON 后参与签名。
7
+
8
+ >>> from ynet_sdk import generate_sign
9
+ >>> generate_sign({"timestamp": "1", "nonce": "n"}, "MD5", "secret")
10
+ '8A9F...'
11
+ """
12
+
13
+ from __future__ import annotations
14
+
15
+ from ._version import __version__
16
+ from .common.sign import (
17
+ DEFAULT_EXCLUDE_FIELDS,
18
+ REQUIRED_PUBLIC_FIELDS,
19
+ OpenApiSignUtil,
20
+ SignType,
21
+ build_sign_content,
22
+ check_required_fields,
23
+ generate_sign,
24
+ verify_sign,
25
+ )
26
+ from .exceptions import (
27
+ OpenApiSignError,
28
+ SignDependencyError,
29
+ SignKeyError,
30
+ SignParameterError,
31
+ )
32
+
33
+ __all__ = [
34
+ "__version__",
35
+ # 核心 API
36
+ "generate_sign",
37
+ "verify_sign",
38
+ "build_sign_content",
39
+ "check_required_fields",
40
+ # 类型与常量
41
+ "SignType",
42
+ "OpenApiSignUtil",
43
+ "DEFAULT_EXCLUDE_FIELDS",
44
+ "REQUIRED_PUBLIC_FIELDS",
45
+ # 异常
46
+ "OpenApiSignError",
47
+ "SignParameterError",
48
+ "SignKeyError",
49
+ "SignDependencyError",
50
+ ]
ynet_sdk/__main__.py ADDED
@@ -0,0 +1,10 @@
1
+ """``python -m ynet_sdk`` 入口。"""
2
+
3
+ from __future__ import annotations
4
+
5
+ import sys
6
+
7
+ from .cli import main
8
+
9
+ if __name__ == "__main__":
10
+ sys.exit(main())
ynet_sdk/_version.py ADDED
@@ -0,0 +1,11 @@
1
+ """单一版本号来源。
2
+
3
+ 打包工具(hatchling)从本文件的 ``__version__`` 读取版本号,
4
+ ``ynet_sdk.__version__`` 也直接引用它,避免多处维护造成不一致。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ __version__ = "0.0.2"
10
+
11
+ __all__ = ["__version__"]
ynet_sdk/cli.py ADDED
@@ -0,0 +1,141 @@
1
+ """命令行工具:用于联调时快速计算 / 校验签名。
2
+
3
+ 安装后可直接使用 ``ynet-sign`` 命令,或 ``python -m ynet_sdk``。
4
+
5
+ 示例::
6
+
7
+ # 计算签名(key=value 形式,值按字符串处理)
8
+ ynet-sign sign --type HMAC_SHA256 --secret s3cr3t \\
9
+ --param appKey=YNET_123456 --param timestamp=1698765432100 --param nonce=abc
10
+
11
+ # 使用 JSON 传参(保留 number / bool 类型)
12
+ ynet-sign sign --type MD5 --secret s3cr3t --json '{"a": 1, "b": true}'
13
+
14
+ # 验签
15
+ ynet-sign verify --type MD5 --secret s3cr3t --sign 8A9F... \\
16
+ --param a=1 --param b=true
17
+
18
+ # 只打印待签名字符串
19
+ ynet-sign content --param b=2 --param a=1
20
+ """
21
+
22
+ from __future__ import annotations
23
+
24
+ import argparse
25
+ import json
26
+ import sys
27
+ from typing import Any, Dict, List, Optional
28
+
29
+ from ._version import __version__
30
+ from .common.sign import build_sign_content, generate_sign, normalize_sign_type, verify_sign
31
+ from .exceptions import OpenApiSignError
32
+
33
+ __all__ = ["main"]
34
+
35
+
36
+ def _parse_pairs(pairs: List[str]) -> Dict[str, Any]:
37
+ """把 ``key=value`` 列表解析为字典。"""
38
+ params: Dict[str, Any] = {}
39
+ for item in pairs:
40
+ if "=" not in item:
41
+ raise ValueError(f"参数格式应为 key=value,实际为 {item!r}")
42
+ key, value = item.split("=", 1)
43
+ if not key:
44
+ raise ValueError(f"参数名不能为空: {item!r}")
45
+ params[key] = value
46
+ return params
47
+
48
+
49
+ def _build_params(args: argparse.Namespace) -> Dict[str, Any]:
50
+ """合并 ``--json`` 与 ``--param``,``--param`` 优先级更高。"""
51
+ params: Dict[str, Any] = {}
52
+ if args.json:
53
+ payload = json.loads(args.json)
54
+ if not isinstance(payload, dict):
55
+ raise ValueError("--json 必须是 JSON 对象")
56
+ params.update(payload)
57
+ params.update(_parse_pairs(args.param or []))
58
+ return params
59
+
60
+
61
+ def build_parser() -> argparse.ArgumentParser:
62
+ """构造参数解析器。"""
63
+ parser = argparse.ArgumentParser(
64
+ prog="ynet-sign",
65
+ description="Ynet 开放平台签名工具(MD5 / HMAC_SHA256 / RSA2)",
66
+ )
67
+ parser.add_argument("--version", action="version", version=f"ynet-sdk-python {__version__}")
68
+ subparsers = parser.add_subparsers(dest="command", required=True)
69
+
70
+ def add_common(sub: argparse.ArgumentParser, *, with_secret: bool) -> None:
71
+ sub.add_argument("--param", "-p", action="append", metavar="KEY=VALUE",
72
+ help="参与签名的参数,可重复;值按字符串处理")
73
+ sub.add_argument("--json", "-j", metavar="JSON", help="以 JSON 对象提供参数")
74
+ sub.add_argument("--type", "-t", default="HMAC_SHA256",
75
+ help="签名算法:MD5 / HMAC_SHA256 / RSA2(默认 HMAC_SHA256)")
76
+ sub.add_argument("--no-required-fields", action="store_true",
77
+ help="不校验 timestamp / nonce 必传字段")
78
+ sub.add_argument("--exclude", action="append", metavar="FIELD",
79
+ help="额外排除的字段,可重复;会与默认排除字段合并")
80
+ if with_secret:
81
+ sub.add_argument("--secret", "-s", required=True,
82
+ help="AppSecret(对称)或 Base64 私钥/公钥(RSA2)")
83
+ sub.add_argument("--secret-file", metavar="PATH",
84
+ help="从文件读取密钥(适合 RSA 私钥),优先于 --secret")
85
+
86
+ sign_parser = subparsers.add_parser("sign", help="生成签名")
87
+ add_common(sign_parser, with_secret=True)
88
+
89
+ verify_parser = subparsers.add_parser("verify", help="校验签名")
90
+ add_common(verify_parser, with_secret=True)
91
+ verify_parser.add_argument("--sign", required=True, help="待校验的签名串")
92
+
93
+ content_parser = subparsers.add_parser("content", help="打印待签名字符串")
94
+ add_common(content_parser, with_secret=False)
95
+
96
+ return parser
97
+
98
+
99
+ def main(argv: Optional[List[str]] = None) -> int:
100
+ """CLI 入口,返回进程退出码:0 成功 / 1 验签失败 / 2 参数或运行错误。"""
101
+ parser = build_parser()
102
+ args = parser.parse_args(argv)
103
+
104
+ try:
105
+ params = _build_params(args)
106
+ except (ValueError, json.JSONDecodeError) as exc:
107
+ print(f"参数解析失败: {exc}", file=sys.stderr)
108
+ return 2
109
+
110
+ required_fields = None if args.no_required_fields else ("timestamp", "nonce")
111
+ exclude_fields = set(args.exclude) if args.exclude else None
112
+
113
+ try:
114
+ if args.command == "content":
115
+ print(build_sign_content(params, exclude_fields))
116
+ return 0
117
+
118
+ secret = args.secret
119
+ if getattr(args, "secret_file", None):
120
+ with open(args.secret_file, "r", encoding="utf-8") as handle:
121
+ # 只去掉行尾换行,保留密钥中可能有意义的其余空白
122
+ secret = handle.read().rstrip("\r\n")
123
+ sign_type = normalize_sign_type(args.type)
124
+
125
+ if args.command == "sign":
126
+ print(generate_sign(params, sign_type, secret, required_fields, exclude_fields))
127
+ return 0
128
+
129
+ ok = verify_sign(params, sign_type, secret, args.sign, required_fields, exclude_fields)
130
+ print("验签通过" if ok else "验签失败")
131
+ return 0 if ok else 1
132
+ except OpenApiSignError as exc:
133
+ print(f"{type(exc).__name__}: {exc}", file=sys.stderr)
134
+ return 2
135
+ except OSError as exc:
136
+ print(f"读取密钥文件失败: {exc}", file=sys.stderr)
137
+ return 2
138
+
139
+
140
+ if __name__ == "__main__": # pragma: no cover
141
+ raise SystemExit(main())
@@ -0,0 +1,9 @@
1
+ """通用能力子包。
2
+
3
+ 当前仅包含签名模块 :mod:`ynet_sdk.common.sign`;后续版本的统一 HTTP 客户端、
4
+ 加解密工具等也会放在本子包下,与 Java 版的包结构保持一致。
5
+ """
6
+
7
+ from __future__ import annotations
8
+
9
+ __all__: list[str] = []
@@ -0,0 +1,40 @@
1
+ """开放平台签名模块。
2
+
3
+ 与 Java 版 ``com.belink.sdk.common.sign`` 包一一对应。
4
+ """
5
+
6
+ from __future__ import annotations
7
+
8
+ from .constants import (
9
+ DEFAULT_EXCLUDE_FIELDS,
10
+ REQUIRED_PUBLIC_FIELDS,
11
+ SIGN_TYPE_HMAC_SHA256,
12
+ SIGN_TYPE_MD5,
13
+ SIGN_TYPE_RSA2,
14
+ SUPPORTED_SIGN_TYPES,
15
+ SignType,
16
+ normalize_sign_type,
17
+ )
18
+ from .open_api_sign import (
19
+ OpenApiSignUtil,
20
+ build_sign_content,
21
+ check_required_fields,
22
+ generate_sign,
23
+ verify_sign,
24
+ )
25
+
26
+ __all__ = [
27
+ "generate_sign",
28
+ "verify_sign",
29
+ "build_sign_content",
30
+ "check_required_fields",
31
+ "OpenApiSignUtil",
32
+ "SignType",
33
+ "normalize_sign_type",
34
+ "DEFAULT_EXCLUDE_FIELDS",
35
+ "REQUIRED_PUBLIC_FIELDS",
36
+ "SUPPORTED_SIGN_TYPES",
37
+ "SIGN_TYPE_MD5",
38
+ "SIGN_TYPE_HMAC_SHA256",
39
+ "SIGN_TYPE_RSA2",
40
+ ]
@@ -0,0 +1,154 @@
1
+ """三种签名算法的底层实现(与 Java 版实现逐位对齐)。
2
+
3
+ - ``MD5``:``md5(content + secret)`` 的 32 位大写十六进制串;
4
+ - ``HMAC_SHA256``:HMAC-SHA256 的 64 位小写十六进制串;
5
+ - ``RSA2``:``SHA256withRSA``(PKCS#1 v1.5 填充 + SHA-256 摘要),Base64 输出。
6
+
7
+ RSA2 依赖可选的 ``cryptography`` 包,采用**惰性导入**:只有真正调用 RSA2 时才会
8
+ 加载,从而保证 ``MD5`` / ``HMAC_SHA256`` 场景下 SDK 零第三方依赖。
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import base64
14
+ import binascii
15
+ import hashlib
16
+ import hmac
17
+ import re
18
+ from typing import Any, Union
19
+
20
+ from ...exceptions import SignDependencyError, SignKeyError
21
+
22
+ __all__ = [
23
+ "md5_hex",
24
+ "hmac_sha256_hex",
25
+ "rsa2_sign",
26
+ "rsa2_verify",
27
+ ]
28
+
29
+ #: 密钥既可以是文本(Base64/PEM),也可以是原始 DER 字节
30
+ KeyMaterial = Union[str, bytes, bytearray]
31
+
32
+ #: 匹配任意 PEM 头尾行,如 ``-----BEGIN PRIVATE KEY-----``
33
+ _PEM_BOUNDARY = re.compile(r"-----(?:BEGIN|END)[^-]*-----", re.IGNORECASE)
34
+
35
+ _CRYPTO_REQUIRED_MESSAGE = (
36
+ "RSA2 签名需要可选依赖 cryptography,请先安装:pip install 'ynet-sdk-python[rsa]'"
37
+ )
38
+
39
+
40
+ def _load_cryptography() -> Any:
41
+ """惰性导入 cryptography,缺失时抛出带安装提示的异常。"""
42
+ try:
43
+ from cryptography.hazmat.primitives import hashes, serialization
44
+ from cryptography.hazmat.primitives.asymmetric import padding, rsa
45
+ except ImportError as exc: # pragma: no cover - 仅在未安装可选依赖时触发
46
+ raise SignDependencyError(_CRYPTO_REQUIRED_MESSAGE) from exc
47
+ return hashes, serialization, padding, rsa
48
+
49
+
50
+ def md5_hex(content: str) -> str:
51
+ """计算字符串的 MD5 摘要(32 位小写十六进制,UTF-8 编码)。"""
52
+ return hashlib.md5(content.encode("utf-8")).hexdigest()
53
+
54
+
55
+ def hmac_sha256_hex(content: str, secret: str) -> str:
56
+ """计算 HMAC-SHA256 摘要(64 位小写十六进制,UTF-8 编码)。"""
57
+ return hmac.new(
58
+ secret.encode("utf-8"), content.encode("utf-8"), hashlib.sha256
59
+ ).hexdigest()
60
+
61
+
62
+ # --------------------------------------------------------------------------- #
63
+ # 密钥解析
64
+ # --------------------------------------------------------------------------- #
65
+
66
+
67
+ def _decode_key_material(material: KeyMaterial, *, label: str) -> bytes:
68
+ """把 Base64 / PEM 文本或原始字节统一解析为 DER 字节。"""
69
+ if isinstance(material, (bytes, bytearray, memoryview)):
70
+ return bytes(material)
71
+ if not isinstance(material, str):
72
+ raise SignKeyError(
73
+ f"{label}必须是 str(Base64/PEM 文本)或 bytes(DER 字节),"
74
+ f"实际传入 {type(material).__name__}"
75
+ )
76
+
77
+ compact = re.sub(r"\s+", "", _PEM_BOUNDARY.sub("", material))
78
+ if not compact:
79
+ raise SignKeyError(f"{label}为空,请检查配置")
80
+
81
+ # 容忍缺失的 Base64 填充符(Java 的 Base64.getDecoder() 不容忍)
82
+ compact += "=" * (-len(compact) % 4)
83
+ try:
84
+ return base64.b64decode(compact, validate=True)
85
+ except (binascii.Error, ValueError) as exc:
86
+ raise SignKeyError(f"{label}不是合法的 Base64 编码: {exc}") from exc
87
+
88
+
89
+ def load_private_key(material: KeyMaterial) -> Any:
90
+ """解析 RSA 私钥(支持 PKCS#8 与 PKCS#1,PEM 或裸 Base64 均可)。"""
91
+ _, serialization, _, rsa = _load_cryptography()
92
+ der = _decode_key_material(material, label="私钥")
93
+ try:
94
+ key = serialization.load_der_private_key(der, password=None)
95
+ except Exception as exc:
96
+ raise SignKeyError(
97
+ "无法解析 RSA 私钥,请确认是 PKCS#8(或 PKCS#1)格式的 DER/Base64 内容"
98
+ ) from exc
99
+ if not isinstance(key, rsa.RSAPrivateKey):
100
+ raise SignKeyError(f"RSA2 仅支持 RSA 私钥,实际为 {type(key).__name__}")
101
+ return key
102
+
103
+
104
+ def load_public_key(material: KeyMaterial) -> Any:
105
+ """解析 RSA 公钥(支持 X.509 SubjectPublicKeyInfo 与 PKCS#1)。"""
106
+ _, serialization, _, rsa = _load_cryptography()
107
+ der = _decode_key_material(material, label="公钥")
108
+ try:
109
+ key = serialization.load_der_public_key(der)
110
+ except Exception as exc:
111
+ raise SignKeyError(
112
+ "无法解析 RSA 公钥,请确认是 X.509(或 PKCS#1)格式的 DER/Base64 内容"
113
+ ) from exc
114
+ if not isinstance(key, rsa.RSAPublicKey):
115
+ raise SignKeyError(f"RSA2 仅支持 RSA 公钥,实际为 {type(key).__name__}")
116
+ return key
117
+
118
+
119
+ # --------------------------------------------------------------------------- #
120
+ # RSA2
121
+ # --------------------------------------------------------------------------- #
122
+
123
+
124
+ def rsa2_sign(content: str, private_key: KeyMaterial) -> str:
125
+ """使用私钥生成 RSA2 签名,返回 Base64 字符串。"""
126
+ hashes, _, padding, _ = _load_cryptography()
127
+ key = load_private_key(private_key)
128
+ signature = key.sign(
129
+ content.encode("utf-8"),
130
+ padding.PKCS1v15(),
131
+ hashes.SHA256(),
132
+ )
133
+ return base64.b64encode(signature).decode("ascii")
134
+
135
+
136
+ def rsa2_verify(content: str, public_key: KeyMaterial, signature_base64: str) -> bool:
137
+ """使用公钥验证 RSA2 签名。
138
+
139
+ 与 Java 版一致:任何异常(含公钥格式错误)都返回 ``False``,不抛异常,
140
+ 避免把密钥配置细节暴露给调用方。若需区分“验签失败”与“配置错误”,
141
+ 可先自行调用 :func:`load_public_key`。
142
+ """
143
+ hashes, _, padding, _ = _load_cryptography()
144
+ try:
145
+ key = load_public_key(public_key)
146
+ key.verify(
147
+ base64.b64decode(signature_base64, validate=False),
148
+ content.encode("utf-8"),
149
+ padding.PKCS1v15(),
150
+ hashes.SHA256(),
151
+ )
152
+ return True
153
+ except Exception:
154
+ return False