pytest-api-framework-alpha 1.0.5__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.
Files changed (48) hide show
  1. framework/__init__.py +1 -0
  2. framework/assertion/__init__.py +3 -0
  3. framework/assertion/retry_assert.py +67 -0
  4. framework/assertion/webhook_assert.py +129 -0
  5. framework/client/__init__.py +3 -0
  6. framework/client/crrm_client.py +155 -0
  7. framework/client/http_client.py +340 -0
  8. framework/client/mq_client.py +178 -0
  9. framework/client/websocket_client.py +414 -0
  10. framework/conftest.py +526 -0
  11. framework/core/__init__.py +3 -0
  12. framework/core/base_class.py +871 -0
  13. framework/core/extract.py +185 -0
  14. framework/core/global_attribute.py +187 -0
  15. framework/core/hooks/__init__.py +3 -0
  16. framework/core/hooks/filters.py +217 -0
  17. framework/core/hooks/reporter.py +228 -0
  18. framework/core/hooks/session.py +345 -0
  19. framework/core/hooks/sorting.py +84 -0
  20. framework/core/models.py +82 -0
  21. framework/core/render_data.py +309 -0
  22. framework/core/validate.py +648 -0
  23. framework/db/__init__.py +3 -0
  24. framework/db/mysql_db.py +226 -0
  25. framework/db/redis_db.py +319 -0
  26. framework/exceptions.py +22 -0
  27. framework/exit_code.py +20 -0
  28. framework/gen/__init__.py +3 -0
  29. framework/gen/case_gen.py +1268 -0
  30. framework/gen/create_app.py +265 -0
  31. framework/report.py +111 -0
  32. framework/script.py +35 -0
  33. framework/settings.py +93 -0
  34. framework/utils/__init__.py +3 -0
  35. framework/utils/cognito_util.py +348 -0
  36. framework/utils/common.py +298 -0
  37. framework/utils/date_util.py +218 -0
  38. framework/utils/encrypt.py +448 -0
  39. framework/utils/lark_util.py +167 -0
  40. framework/utils/log_util.py +10 -0
  41. framework/utils/mock_util.py +236 -0
  42. framework/utils/yaml_util.py +169 -0
  43. framework/ws_server.py +167 -0
  44. pytest_api_framework_alpha-1.0.5.dist-info/METADATA +98 -0
  45. pytest_api_framework_alpha-1.0.5.dist-info/RECORD +48 -0
  46. pytest_api_framework_alpha-1.0.5.dist-info/WHEEL +5 -0
  47. pytest_api_framework_alpha-1.0.5.dist-info/licenses/LICENSE +21 -0
  48. pytest_api_framework_alpha-1.0.5.dist-info/top_level.txt +1 -0
@@ -0,0 +1,218 @@
1
+ """
2
+ 日期时间工具模块
3
+
4
+ 提供日期时间的常用操作封装,包括:
5
+ - 时间戳获取(秒级/毫秒级)
6
+ - 时间戳与日期时间的互转
7
+ - GMT 格式解析
8
+ - 日期时间的加减运算
9
+ - 日期差、时间差计算
10
+ - 日期格式转换
11
+ """
12
+
13
+ import time
14
+ from datetime import datetime, timedelta
15
+
16
+
17
+ class DateUtil(object):
18
+ """日期时间工具类,所有方法均为静态方法"""
19
+ """日期时间工具类,所有方法均为静态方法"""
20
+
21
+ @staticmethod
22
+ def get_long_timestamp(int_type: bool = False) -> int | str:
23
+ """
24
+ 获取毫秒级时间戳
25
+ @param int_type: 若为 True 返回 int 类型,否则返回 str 类型(默认)
26
+ @return: 毫秒级时间戳
27
+ """
28
+ ts = int(time.time() * 1000)
29
+ return ts if int_type else str(ts)
30
+
31
+ @staticmethod
32
+ def get_short_timestamp(int_type: bool = False) -> int | str:
33
+ """
34
+ 获取秒级时间戳
35
+ @param int_type: 若为 True 返回 int 类型,否则返回 str 类型(默认)
36
+ @return: 秒级时间戳
37
+ """
38
+ ts = int(time.time())
39
+ return ts if int_type else str(ts)
40
+
41
+ @staticmethod
42
+ def get_current_datetime(fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
43
+ """
44
+ 获取当前日期和时间,默认格式 2023-02-19 08:31:51
45
+ @param fmt: 日期时间格式,默认为 "%Y-%m-%d %H:%M:%S"
46
+ @return: 格式化后的日期时间字符串
47
+ """
48
+ return datetime.now().strftime(fmt)
49
+
50
+ @staticmethod
51
+ def get_current_time(fmt: str = "%H:%M:%S") -> str:
52
+ """
53
+ 获取当前时间,默认格式 08:30:57
54
+ @param fmt: 时间格式,默认为 "%H:%M:%S"
55
+ @return: 格式化后的时间字符串
56
+ """
57
+ return datetime.now().strftime(fmt)
58
+
59
+ @staticmethod
60
+ def get_current_date(fmt: str = "%Y-%m-%d") -> str:
61
+ """
62
+ 获取当前日期,默认格式 2023-02-19
63
+ @param fmt: 日期格式,默认为 "%Y-%m-%d"
64
+ @return: 格式化后的日期字符串
65
+ """
66
+ return datetime.now().strftime(fmt)
67
+
68
+ @staticmethod
69
+ def timestamp2datetime(timestamp: int | str, fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
70
+ """
71
+ 时间戳转日期时间字符串
72
+ @param timestamp: 时间戳(int 或 str 类型),若为字符串自动截取前10位
73
+ @param fmt: 输出格式
74
+ @return: 格式化后的日期时间字符串
75
+ """
76
+ if isinstance(timestamp, str):
77
+ timestamp = int(timestamp[:10]) # 截取前10位(秒级)
78
+ return datetime.fromtimestamp(timestamp).strftime(fmt)
79
+
80
+ @staticmethod
81
+ def timestamp2date(timestamp: int | str, fmt: str = "%Y-%m-%d") -> str:
82
+ """
83
+ 时间戳转日期字符串
84
+ @param timestamp: 时间戳(int 或 str 类型),若为字符串自动截取前10位
85
+ @param fmt: 输出格式
86
+ @return: 格式化后的日期字符串
87
+ """
88
+ if isinstance(timestamp, str):
89
+ timestamp = int(timestamp[:10]) # 截取前10位(秒级)
90
+ return datetime.fromtimestamp(timestamp).strftime(fmt)
91
+
92
+ @staticmethod
93
+ def datetime2timestamp(date_str: str, fmt: str = "%Y-%m-%d %H:%M:%S", millisecond: bool = False, int_type: bool = False) -> int | str:
94
+ """
95
+ 日期时间字符串转时间戳
96
+ @param date_str: 日期时间字符串
97
+ @param fmt: 输入格式
98
+ @param millisecond: 若为 True,返回毫秒级时间戳
99
+ @param int_type: 若为 True 返回 int 类型,否则返回 str 类型(默认)
100
+ @return: 时间戳
101
+ """
102
+ ts = int(time.mktime(time.strptime(date_str, fmt)))
103
+ if millisecond:
104
+ return ts if int_type else str(ts * 1000)
105
+ return ts if int_type else str(ts * 1000)
106
+
107
+ @staticmethod
108
+ def date2timestamp(date_str: str, fmt: str = "%Y-%m-%d", millisecond: bool = False, int_type: bool = False) -> int | str:
109
+ """
110
+ 日期字符串转时间戳
111
+ @param date_str: 日期字符串
112
+ @param fmt: 输入格式
113
+ @param millisecond: 若为 True,返回毫秒级时间戳
114
+ @param int_type: 若为 True 返回 int 类型,否则返回 str 类型(默认)
115
+ @return: 时间戳
116
+ """
117
+ ts = int(time.mktime(time.strptime(date_str, fmt)))
118
+ if millisecond:
119
+ return ts if int_type else str(ts * 1000)
120
+ return ts if int_type else str(ts * 1000)
121
+
122
+ @staticmethod
123
+ def GMT2date(GMT: str, fmt: str = '%a %b %d %Y') -> str:
124
+ """
125
+ GMT 格式转日期字符串(忽略时间部分)
126
+ @param GMT: GMT 格式字符串,如 'Mon Feb 19 2023'
127
+ @param fmt: 输入格式
128
+ @return: 日期字符串,如 '2023-02-19'
129
+ """
130
+ return datetime.strptime(GMT, fmt).strftime("%Y-%m-%d")
131
+
132
+ @staticmethod
133
+ def GMT2datetime(GMT: str, fmt: str = '%a %b %d %H:%M:%S %Y') -> str:
134
+ """
135
+ GMT 格式转日期时间字符串
136
+ @param GMT: GMT 格式字符串,如 'Mon Feb 19 08:31:51 2023'
137
+ @param fmt: 输入格式
138
+ @return: 日期时间字符串,如 '2023-02-19 08:31:51'
139
+ """
140
+ return datetime.strptime(GMT, fmt).strftime("%Y-%m-%d %H:%M:%S")
141
+
142
+ @staticmethod
143
+ def add_days(days: int, base_date: str | None = None, fmt: str = "%Y-%m-%d") -> str:
144
+ """
145
+ 日期加指定天数
146
+ @param days: 要加的天数(可为负数,相当于减)
147
+ @param base_date: 基准日期字符串,默认为当前日期
148
+ @param fmt: 日期格式
149
+ @return: 计算后的日期字符串
150
+ """
151
+ if base_date:
152
+ dt = datetime.strptime(base_date, fmt)
153
+ else:
154
+ dt = datetime.now()
155
+ return (dt + timedelta(days=days)).strftime(fmt)
156
+
157
+ @staticmethod
158
+ def sub_days(days: int, base_date: str | None = None, fmt: str = "%Y-%m-%d") -> str:
159
+ """
160
+ 日期减指定天数(等价于 add_days(-days))
161
+ @param days: 要减的天数
162
+ @param base_date: 基准日期字符串,默认为当前日期
163
+ @param fmt: 日期格式
164
+ @return: 计算后的日期字符串
165
+ """
166
+ return DateUtil.add_days(-days, base_date, fmt)
167
+
168
+ @staticmethod
169
+ def add_seconds(seconds: int, base_datetime: str | None = None, fmt: str = "%Y-%m-%d %H:%M:%S") -> str:
170
+ """
171
+ 日期时间加减指定秒数
172
+ @param seconds: 要加减的秒数(负数表示减)
173
+ @param base_datetime: 基准日期时间字符串,默认为当前时间
174
+ @param fmt: 日期时间格式
175
+ @return: 计算后的日期时间字符串
176
+ """
177
+ if base_datetime:
178
+ dt = datetime.strptime(base_datetime, fmt)
179
+ else:
180
+ dt = datetime.now()
181
+ return (dt + timedelta(seconds=seconds)).strftime(fmt)
182
+
183
+ @staticmethod
184
+ def diff_days(date1: str, date2: str, fmt: str = "%Y-%m-%d") -> int:
185
+ """
186
+ 计算两个日期相差的天数(绝对值)
187
+ @param date1: 第一个日期字符串
188
+ @param date2: 第二个日期字符串
189
+ @param fmt: 日期格式
190
+ @return: 相差的天数
191
+ """
192
+ d1 = datetime.strptime(date1, fmt)
193
+ d2 = datetime.strptime(date2, fmt)
194
+ return abs((d1 - d2).days)
195
+
196
+ @staticmethod
197
+ def diff_seconds(dt1: str, dt2: str, fmt: str = "%Y-%m-%d %H:%M:%S") -> int:
198
+ """
199
+ 计算两个日期时间相差的秒数(绝对值)
200
+ @param dt1: 第一个日期时间字符串
201
+ @param dt2: 第二个日期时间字符串
202
+ @param fmt: 日期时间格式
203
+ @return: 相差的秒数
204
+ """
205
+ d1 = datetime.strptime(dt1, fmt)
206
+ d2 = datetime.strptime(dt2, fmt)
207
+ return abs(int((d1 - d2).total_seconds()))
208
+
209
+ @staticmethod
210
+ def format_datetime(date_str: str, from_fmt: str, to_fmt: str) -> str:
211
+ """
212
+ 日期时间格式转换,如 '20230922' 转为 '2023-09-22'
213
+ @param date_str: 原始日期时间字符串
214
+ @param from_fmt: 原始格式
215
+ @param to_fmt: 目标格式
216
+ @return: 转换后的日期时间字符串
217
+ """
218
+ return datetime.strptime(date_str, from_fmt).strftime(to_fmt)
@@ -0,0 +1,448 @@
1
+ """
2
+ 加密/解密工具模块
3
+
4
+ 提供常用的加密和解密函数封装,包括:
5
+ - MD5 哈希
6
+ - SHA 系列哈希(SHA1, SHA256, SHA512, Shake 等)
7
+ - Base64 编解码
8
+ - RSA 公钥加密
9
+ - AES 加密/解密(支持 CBC/ECB/CFB/OFB/CTR 等多种模式)
10
+ - DES 加密/解密(支持 CBC/ECB/CFB/OFB/CTR 等多种模式)
11
+ - 3DES 加密/解密(支持 CBC/ECB/CFB/OFB/CTR 等多种模式)
12
+ """
13
+
14
+ import json
15
+ import base64
16
+ import hashlib
17
+
18
+ from Crypto.PublicKey import RSA
19
+ from Crypto.Util.Padding import pad, unpad
20
+ from Crypto.Cipher import AES, DES, DES3, PKCS1_v1_5 as PKCS1_cipher
21
+ from typing import Any
22
+ from framework.utils.common import valid_hex_format, valid_b64_format, hex_to_bytes, bytes_to_hex
23
+
24
+
25
+ def md5(string: str | bytes, byte: bool = False, encoding: str = "utf-8") -> str | bytes:
26
+ """
27
+ MD5 哈希计算
28
+ @param string: 待加密内容(字符串或字节串)
29
+ @param byte: 若为 True 返回原始字节,否则返回 16 进制字符串(默认)
30
+ @param encoding: 编码格式
31
+ @return: MD5 哈希值
32
+ """
33
+ md_obj = hashlib.md5()
34
+ if isinstance(string, str):
35
+ string = string.encode(encoding=encoding)
36
+ md_obj.update(string)
37
+ if byte:
38
+ return md_obj.digest() # 返回原始字节
39
+ return md_obj.hexdigest() # 返回 16 进制字符串
40
+
41
+
42
+ def sha(str_list: list[str | bytes], mode: str, byte: bool = False, length: int | None = None, encoding: str = "utf-8") -> str | bytes:
43
+ """
44
+ SHA 系列哈希计算(支持 SHA1/SHA256/SHA512/Shake 等)
45
+
46
+ @param str_list: 待加密内容列表,元素为字符串或字节串
47
+ @param mode: SHA 算法名称,如 'sha256', 'sha512', 'shake_128'
48
+ @param byte: 若为 True 返回原始字节,否则返回 16 进制字符串(默认)
49
+ @param length: 仅 'shake_128' 和 'shake_256' 需要指定输出长度
50
+ @param encoding: 编码格式
51
+ @return: SHA 哈希值
52
+ @raises Exception: 参数类型校验失败时抛出
53
+ """
54
+ sha_obj = hashlib.new(mode)
55
+ if not isinstance(str_list, list):
56
+ raise Exception(f"{str_list} 必须是list类型")
57
+ for i in str_list:
58
+ if not isinstance(i, (str, bytes)):
59
+ raise Exception(f"{i} 必须是str或bytes类型")
60
+ if isinstance(i, str):
61
+ i = i.encode(encoding=encoding)
62
+ sha_obj.update(i)
63
+
64
+ if mode in ['shake_128', 'shake_256']:
65
+ if byte:
66
+ return sha_obj.digest(length)
67
+ return sha_obj.hexdigest(length)
68
+ else:
69
+ if byte:
70
+ return sha_obj.digest()
71
+ return sha_obj.hexdigest()
72
+
73
+
74
+ def b64_encode(bs: bytes, byte: bool = False, encoding: str = "utf-8") -> str | bytes:
75
+ """
76
+ Base64 编码(bytes -> b64 字符串/字节)
77
+
78
+ @param bs: 待编码的二进制字节串
79
+ @param byte: 若为 True 返回二进制字节,否则返回 b64 字符串(默认)
80
+ @param encoding: 编码格式
81
+ @return: Base64 编码结果
82
+ @raises Exception: 参数类型校验失败时抛出
83
+ """
84
+ if not isinstance(bs, bytes):
85
+ raise Exception(f"{bs} 必须是bytes类型")
86
+ if byte:
87
+ return base64.b64encode(bs)
88
+ return base64.b64encode(bs).decode(encoding)
89
+
90
+
91
+ def b64_decode(string: str, byte: bool = True, encoding: str = "utf-8") -> str | bytes:
92
+ """
93
+ Base64 解码(b64 字符串 -> bytes/字符串)
94
+
95
+ @param string: Base64 编码的字符串
96
+ @param byte: 若为 True 返回二进制字节(默认),否则返回字符串
97
+ @param encoding: 编码格式
98
+ @return: 解码结果
99
+ @raises Exception: 参数类型校验失败时抛出
100
+ """
101
+ if not isinstance(string, str):
102
+ raise Exception(f"{string} 必须是b64字符串")
103
+
104
+ # 补齐 padding(Base64 要求长度为 4 的倍数)
105
+ missing_padding = 4 - len(string) % 4
106
+ if missing_padding:
107
+ string += '=' * missing_padding
108
+ if byte:
109
+ return base64.b64decode(string)
110
+ return base64.b64decode(string).decode(encoding=encoding)
111
+
112
+
113
+ class RsaByPubKey(object):
114
+ """RSA 公钥加密工具类"""
115
+
116
+ def __init__(self, pub_key: str) -> None:
117
+ """
118
+ 初始化 RSA 加密器
119
+
120
+ @param pub_key: 公钥,可以是 16 进制字符串或 Base64 字符串
121
+ """
122
+ self.pub_key = pub_key
123
+
124
+ def encrypt(self, data: str | bytes, b64: bool = False, encoding: str = "utf-8") -> str:
125
+ """
126
+ RSA 公钥加密
127
+
128
+ @param data: 要加密的数据(字符串或字节串)
129
+ @param b64: 若为 True 返回 Base64 编码字符串,否则返回 16 进制字符串(默认)
130
+ @param encoding: 编码格式
131
+ @return: 加密后的字符串
132
+ @raises Exception: 公钥格式无效时抛出
133
+ """
134
+
135
+ # 自动识别并转换公钥格式:16 进制或 Base64
136
+ if valid_hex_format(self.pub_key):
137
+ self.pub_key = hex_to_bytes(self.pub_key)
138
+
139
+ elif valid_b64_format(self.pub_key):
140
+ self.pub_key = b64_decode(self.pub_key)
141
+
142
+ else:
143
+ raise Exception("pub_key参数必须是16进制字符串或b64字符串")
144
+
145
+ # 将数据转为字节类型
146
+ if not isinstance(data, bytes):
147
+ data = data.encode(encoding=encoding)
148
+ cipher = PKCS1_cipher.new(RSA.import_key(self.pub_key))
149
+ encrypt_text = cipher.encrypt(data)
150
+ if b64:
151
+ return b64_encode(cipher.encrypt(data)) # 转成 Base64 字符串
152
+ return bytes_to_hex(encrypt_text).decode(encoding=encoding) # 转成 16 进制字符串
153
+
154
+
155
+ class Aes(object):
156
+ """AES 加密/解密工具类,支持多种模式"""
157
+
158
+ AES_MODE_MAP = {
159
+ "CBC": AES.MODE_CBC,
160
+ "ECB": AES.MODE_ECB,
161
+ "CFB": AES.MODE_CFB,
162
+ "OFB": AES.MODE_OFB,
163
+ "CTR": AES.MODE_CTR,
164
+ "OPENPGP": AES.MODE_OPENPGP,
165
+ "CCM": AES.MODE_CCM,
166
+ "EAX": AES.MODE_EAX,
167
+ "SIV": AES.MODE_SIV,
168
+ "GCM": AES.MODE_GCM,
169
+ "OCB": AES.MODE_OCB
170
+ }
171
+ """AES 加密模式映射字典"""
172
+
173
+ def __init__(self, key: str | bytes, mode: str, iv: str | bytes | None = None, encoding: str = "utf-8") -> None:
174
+ """
175
+ 初始化 AES 加密器
176
+
177
+ @param key: 密钥,必须是 16、24 或 32 字节长度
178
+ @param mode: 加密模式,如 'CBC', 'ECB', 'CFB' 等
179
+ @param iv: 初始化向量,CBC/CFB/OFB 模式下必须是 16 字节
180
+ @param encoding: 编码格式
181
+ @raises Exception: 参数校验失败时抛出
182
+ """
183
+ self.iv = iv
184
+ self.key = key
185
+ self.mode = mode.upper()
186
+ self.encoding = encoding
187
+ # CBC/CFB/OFB 模式需要 IV 参数
188
+ if self.mode in ["CBC", "CFB", "OFB"]:
189
+ if not self.iv or len(self.iv) != 16:
190
+ raise Exception(f"{iv} 必须是16字节长度")
191
+
192
+ if len(self.key) not in [16, 24, 32]:
193
+ raise Exception(f"{self.key} 必须是16、24或32字节长度")
194
+
195
+ if not isinstance(self.key, bytes):
196
+ self.key = self.key.encode(encoding=self.encoding)
197
+
198
+ if self.iv:
199
+ if not isinstance(self.iv, bytes):
200
+ self.iv = self.iv.encode(encoding=self.encoding)
201
+ self.mode = self.AES_MODE_MAP.get(mode)
202
+
203
+ def new_aes(self) -> Any:
204
+ """创建 AES 加密器对象(根据是否有 IV 选择不同构造方式)"""
205
+ if self.iv:
206
+ return AES.new(key=self.key, mode=self.mode, IV=self.iv)
207
+ return AES.new(key=self.key, mode=self.mode)
208
+
209
+ def encrypt(self, data: str | bytes | dict, byte: bool = False, separate: bool = False) -> str | bytes:
210
+ """
211
+ AES 加密:字符串/字节 -> 加密 -> Base64 字符串
212
+
213
+ @param data: 加密内容,可以是字符串、字节串或字典
214
+ @param byte: 若为 True 返回原始字节,否则返回 Base64 字符串(默认)
215
+ @param separate: 若为 True,序列化字典时使用紧凑格式(无多余空格)
216
+ @return: 加密后的 Base64 字符串或字节
217
+ """
218
+
219
+ aes_obj = self.new_aes()
220
+ if isinstance(data, dict):
221
+ if separate:
222
+ data = json.dumps(data, separators=(',', ':')).encode(encoding=self.encoding)
223
+ else:
224
+ data = json.dumps(data).encode(encoding=self.encoding)
225
+ else:
226
+ data = str(data).encode(encoding=self.encoding)
227
+ data = pad(data, 16) # AES 块填充(块大小 16 字节)
228
+ if byte:
229
+ return aes_obj.encrypt(data)
230
+ return b64_encode(aes_obj.encrypt(data))
231
+
232
+ def decrypt(self, data: str | bytes, byte: bool = False) -> str | bytes | dict:
233
+ """
234
+ AES 解密:Base64 字符串 -> 解密 -> 字符串/字节
235
+
236
+ @param data: 解密内容,字节串或 Base64 字符串
237
+ @param byte: 若为 True 返回原始字节,否则返回字符串(默认)
238
+ @return: 解密后的字符串或字节
239
+ """
240
+ aes_obj = self.new_aes()
241
+ if not isinstance(data, bytes):
242
+ data = b64_decode(data) # Base64 解码为字节
243
+ if byte:
244
+ return unpad(aes_obj.decrypt(data), 16)
245
+ try:
246
+ # 尝试按 JSON 解析
247
+ return json.loads(unpad(aes_obj.decrypt(data), 16).decode(encoding=self.encoding))
248
+ except Exception:
249
+ # JSON 解析失败则直接返回字符串
250
+ return unpad(aes_obj.decrypt(data), 16).decode(encoding=self.encoding)
251
+
252
+
253
+ class Des(object):
254
+ """DES 加密/解密工具类,支持多种模式"""
255
+
256
+ DES_MODE_MAP = {
257
+ "CBC": DES.MODE_CBC,
258
+ "ECB": DES.MODE_ECB,
259
+ "CFB": DES.MODE_CFB,
260
+ "OFB": DES.MODE_OFB,
261
+ "CTR": DES.MODE_CTR,
262
+ "OPENPGP": DES.MODE_OPENPGP,
263
+ "EAX": DES.MODE_EAX
264
+ }
265
+ """DES 加密模式映射字典"""
266
+
267
+ def __init__(self, key: str | bytes, mode: str, iv: str | bytes | None = None, encoding: str = "utf-8") -> None:
268
+ """
269
+ 初始化 DES 加密器
270
+
271
+ @param key: 密钥,必须是 8 字节长度
272
+ @param mode: 加密模式,如 'CBC', 'ECB', 'CFB' 等
273
+ @param iv: 初始化向量,CBC/CFB/OFB 模式下必须是 8 字节
274
+ @param encoding: 编码格式
275
+ @raises Exception: 参数校验失败时抛出
276
+ """
277
+ self.iv = iv
278
+ self.key = key
279
+ self.mode = mode.upper()
280
+ self.encoding = encoding
281
+ # CBC/CFB/OFB 模式需要 IV 参数
282
+ if self.mode in ["CBC", "CFB", "OFB"]:
283
+ if not self.iv or len(self.iv) != 8:
284
+ raise Exception(f"{self.iv} 必须是8字节长度")
285
+
286
+ if len(self.key) != 8:
287
+ raise Exception(f"{self.key} 必须是8字节长度")
288
+
289
+ if not isinstance(self.key, bytes):
290
+ self.key = self.key.encode(encoding=self.encoding)
291
+
292
+ if self.iv:
293
+ if not isinstance(self.iv, bytes):
294
+ self.iv = self.iv.encode(encoding=self.encoding)
295
+
296
+ self.mode = self.DES_MODE_MAP.get(mode)
297
+
298
+ def new_des(self) -> Any:
299
+ """创建 DES 加密器对象(根据是否有 IV 选择不同构造方式)"""
300
+ if self.iv:
301
+ return DES.new(key=self.key, mode=self.mode, IV=self.iv)
302
+ return DES.new(key=self.key, mode=self.mode)
303
+
304
+ def encrypt(self, data: str | bytes | dict, byte: bool = False, separate: bool = False) -> str | bytes:
305
+ """
306
+ DES 加密:字符串/字节 -> 加密 -> Base64 字符串
307
+
308
+ @param data: 加密内容,可以是字符串、字节串或字典
309
+ @param byte: 若为 True 返回原始字节,否则返回 Base64 字符串(默认)
310
+ @param separate: 若为 True,序列化字典时使用紧凑格式(无多余空格)
311
+ @return: 加密后的 Base64 字符串或字节
312
+ """
313
+ des_obj = self.new_des()
314
+ if isinstance(data, dict):
315
+ if separate:
316
+ data = json.dumps(data, separators=(',', ':')).encode(encoding=self.encoding)
317
+ else:
318
+ data = json.dumps(data).encode(encoding=self.encoding)
319
+ else:
320
+ data = str(data).encode(encoding=self.encoding)
321
+ data = pad(data, 8) # DES 块填充(块大小 8 字节)
322
+ if byte:
323
+ return des_obj.encrypt(data)
324
+ return b64_encode(des_obj.encrypt(data))
325
+
326
+ def decrypt(self, data: str | bytes, byte: bool = False) -> str | bytes | dict:
327
+ """
328
+ DES 解密:Base64 字符串 -> 解密 -> 字符串/字节
329
+
330
+ @param data: 解密内容,字节串或 Base64 字符串
331
+ @param byte: 若为 True 返回原始字节,否则返回字符串(默认)
332
+ @return: 解密后的字符串或字节
333
+ """
334
+ des_obj = self.new_des()
335
+ if not isinstance(data, bytes):
336
+ data = b64_decode(data) # Base64 解码为字节
337
+ if byte:
338
+ return unpad(des_obj.decrypt(data), 8)
339
+ try:
340
+ # 尝试按 JSON 解析
341
+ return json.loads(unpad(des_obj.decrypt(data), 8).decode(encoding=self.encoding))
342
+ except Exception:
343
+ # JSON 解析失败则直接返回字符串
344
+ return unpad(des_obj.decrypt(data), 8).decode(encoding=self.encoding)
345
+
346
+
347
+ class Des3(object):
348
+ """3DES(Triple DES)加密/解密工具类,支持多种模式"""
349
+
350
+ DES3_MODE_MAP = {
351
+ "CBC": DES3.MODE_CBC,
352
+ "ECB": DES3.MODE_ECB,
353
+ "CFB": DES3.MODE_CFB,
354
+ "OFB": DES3.MODE_OFB,
355
+ "CTR": DES3.MODE_CTR,
356
+ "OPENPGP": DES3.MODE_OPENPGP,
357
+ "EAX": DES3.MODE_EAX
358
+ }
359
+ """3DES 加密模式映射字典"""
360
+
361
+ def __init__(self, key: str | bytes, mode: str, iv: str | bytes | None = None, encoding: str = "utf-8") -> None:
362
+ """
363
+ 初始化 3DES 加密器
364
+
365
+ @param key: 密钥,必须是 16 或 24 字节长度
366
+ @param mode: 加密模式,如 'CBC', 'ECB', 'CFB' 等
367
+ @param iv: 初始化向量,CBC/CFB/OFB 模式下必须是 8 字节
368
+ @param encoding: 编码格式
369
+ @raises Exception: 参数校验失败时抛出
370
+ """
371
+ self.iv = iv
372
+ self.key = key
373
+ self.mode = mode.upper()
374
+ self.encoding = encoding
375
+
376
+ # CBC/CFB/OFB 模式需要 IV 参数
377
+ if self.mode in ["CBC", "CFB", "OFB"]:
378
+ if not self.iv or len(self.iv) != 8:
379
+ raise Exception(f"{self.iv} 必须是8字节长度")
380
+
381
+ if len(self.key) not in [16, 24]:
382
+ raise Exception(f"{self.key} 必须是16或24字节长度")
383
+
384
+ if not isinstance(self.key, bytes):
385
+ self.key = self.key.encode(encoding=self.encoding)
386
+
387
+ if self.iv:
388
+ if not isinstance(iv, bytes):
389
+ self.iv = self.iv.encode(encoding=self.encoding)
390
+
391
+ self.mode = self.DES3_MODE_MAP.get(mode)
392
+
393
+ def new_des3(self) -> Any:
394
+ """创建 3DES 加密器对象(根据是否有 IV 选择不同构造方式)"""
395
+ if self.iv:
396
+ return DES3.new(key=self.key, mode=self.mode, IV=self.iv)
397
+ return DES3.new(key=self.key, mode=self.mode)
398
+
399
+ def encrypt(self, data: str | bytes | dict, byte: bool = False, separate: bool = False) -> str | bytes:
400
+ """
401
+ 3DES 加密:字符串/字节 -> 加密 -> Base64 字符串
402
+
403
+ @param data: 加密内容,可以是字符串、字节串或字典
404
+ @param byte: 若为 True 返回原始字节,否则返回 Base64 字符串(默认)
405
+ @param separate: 若为 True,序列化字典时使用紧凑格式(无多余空格)
406
+ @return: 加密后的 Base64 字符串或字节
407
+ """
408
+ des3_obj = self.new_des3()
409
+ if isinstance(data, dict):
410
+ if separate:
411
+ data = json.dumps(data, separators=(',', ':')).encode(encoding=self.encoding)
412
+ else:
413
+ data = json.dumps(data).encode(encoding=self.encoding)
414
+ else:
415
+ data = str(data).encode(encoding=self.encoding)
416
+ data = pad(data, 8) # 3DES 块填充(块大小 8 字节)
417
+ if byte:
418
+ return des3_obj.encrypt(data)
419
+ else:
420
+ return b64_encode(des3_obj.encrypt(data))
421
+
422
+ def decrypt(self, data: str | bytes, byte: bool = False) -> str | bytes | dict:
423
+ """
424
+ 3DES 解密:Base64 字符串 -> 解密 -> 字符串/字节
425
+
426
+ @param data: 解密内容,字节串或 Base64 字符串
427
+ @param byte: 若为 True 返回原始字节,否则返回字符串(默认)
428
+ @return: 解密后的字符串或字节
429
+ """
430
+ des3_obj = self.new_des3()
431
+ if not isinstance(data, bytes):
432
+ data = b64_decode(data) # Base64 解码为字节
433
+ if byte:
434
+ return unpad(des3_obj.decrypt(data), 8)
435
+ else:
436
+ try:
437
+ # 尝试按 JSON 解析
438
+ return json.loads(unpad(des3_obj.decrypt(data), 8).decode(encoding=self.encoding))
439
+ except Exception:
440
+ # JSON 解析失败则直接返回字符串
441
+ return unpad(des3_obj.decrypt(data), 8).decode(encoding=self.encoding)
442
+
443
+
444
+ if __name__ == '__main__':
445
+ key = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCqJA8yliEYgp9aorMNzayIyJex4ukgwEXi+Us2xVJlttB2Uy9Bsh9ugTqNcc1bf7R5WW/QIN/EbA+yJC1FCqZHzZdYw54O+IN9oV9I+pE2ziK6vlOjUYmKbi2NO84xAYW83uaWee6MkH8m87qn5hrd7JzksPJS3HdHNZCcOOOemwIDAQAB"
446
+ rsa = RsaByPubKey(pub_key=key)
447
+ a = rsa.encrypt(test_data="password", b64=True)
448
+ print(a)