forked from GmSSL/GmSSL-Python
-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy patheasy_sm2_key.py
More file actions
558 lines (491 loc) · 23.5 KB
/
easy_sm2_key.py
File metadata and controls
558 lines (491 loc) · 23.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
# @Time: 2024-12-21 14:31:17
from __future__ import annotations
import base64
import binascii
import ctypes
from enum import Enum
from typing import Dict, List, Literal, Tuple
from pyasn1.codec.der import decoder, encoder
from pyasn1.type import namedtype, univ
from .gmssl import NativeError, SM2_MAX_CIPHERTEXT_SIZE, SM2_MAX_PLAINTEXT_SIZE, Sm2Key
class SM2PubKeyASN1Sequence(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('oid-tags',
univ.Sequence(
componentType = namedtype.NamedTypes(
namedtype.NamedType('oid-1', univ.ObjectIdentifier()),
namedtype.NamedType('oid-2', univ.ObjectIdentifier())
)
)),
namedtype.NamedType('sm2_public_key', univ.BitString())
)
class SM2PubKeyRawData(object):
def __init__(self, oids: List[str], hex_data: str):
self.__oids = oids
self.__hex_data = hex_data
@property
def oids(self) -> List[str]:
return self.__oids
@property
def hex_data(self) -> str:
return self.__hex_data
class SM2CipherMode(Enum):
C1C3C2_ASN1 = 'C1C3C2_ASN1'
C1C3C2 = 'C1C3C2'
C1C2C3_ASN1 = 'C1C2C3_ASN1'
C1C2C3 = 'C1C2C3'
class SM2CipherFormat(Enum):
Base64Str = 'Base64'
HexStr = 'Hex'
class SM2CipherLength(Enum):
"""
SM2密文主要由C1、C2、C3三部分构成,
其中C1是随机数计算出的椭圆曲线、C2是密文数据、C3是SM3杂凑值,
C1固定为64字节,C2的长度与明文相同,C3的长度固定为32字节,
"""
C1LenInBytes = 64
C1XLenInBytes = 32
C1YLenInBytes = 32
C3LenInBytes = 32
def __easy_parse_sm2_pub_key__(base64_content: str) -> SM2PubKeyRawData:
try:
raw_bytes = base64.b64decode(base64_content)
ret_obj, _ = decoder.decode(raw_bytes, asn1Spec = SM2PubKeyASN1Sequence())
except Exception:
raise ValueError('invalid sm2 public key bytes')
else:
oid1 = ret_obj['oid-tags']['oid-1'].prettyPrint()
oid2 = ret_obj['oid-tags']['oid-2'].prettyPrint()
sm2_pub = ret_obj['sm2_public_key']
bit_string = sm2_pub.asOctets()
hex_string = binascii.hexlify(bit_string).decode('utf-8')
return SM2PubKeyRawData([oid1, oid2], hex_string)
def __check_private_key_password__(pri_key_password: str):
if len(pri_key_password) <= 0:
raise ValueError('empty password for sm2 private key')
if len(pri_key_password) > 32:
raise ValueError('sm2 private key password too long')
def __easy_read_sm2_pub_pem_file_lines__(pem_file: str) -> str:
"""
返回 base64 编码的公钥内容
"""
MAX_FILE_SIZE = 2048
file_size = 0
lines = []
try:
with open(pem_file, 'r') as pem_file:
for line in pem_file:
file_size += len(line)
if file_size > MAX_FILE_SIZE:
raise ValueError("PEM File Too Large")
lines.append(line.strip())
except FileNotFoundError:
raise FileNotFoundError("invalid file:{}".format(pem_file))
else:
content = ''
for i in lines:
i = i.strip()
if len(i) > 0:
content += i.strip()
content = content.replace('-----BEGIN PUBLIC KEY-----', '')
content = content.replace('-----END PUBLIC KEY-----', '')
if len(content) <= 0:
raise ValueError("invalid pem content")
return content
# 定义SM2 C1C3C2_ASN1 Ciphertext结构
class SM2_C1C3C2_ASN1_Ciphertext(univ.Sequence):
"""
c1x 和 c1y 分别代表 C1 点的 x 和 y 坐标
这个 C1 点是加密过程中随机生成的,用于与接收方的公钥进行交互以确保加密的安全性
C1 的坐标(c1x, c1y)与公钥的坐标(x, y)是不会相同的
在实际应用中,随机数 k 是每次加密时新生成的随机数,以确保加密的安全性
"""
componentType = namedtype.NamedTypes(
namedtype.NamedType('c1x', univ.Integer()),
namedtype.NamedType('c1y', univ.Integer()),
namedtype.NamedType('c3', univ.OctetString()),
namedtype.NamedType('c2', univ.OctetString())
)
# 定义SM2 C1C2C3_ASN1 Ciphertext结构
class SM2_C1C2C3_ASN1_Ciphertext(univ.Sequence):
componentType = namedtype.NamedTypes(
namedtype.NamedType('c1x', univ.Integer()),
namedtype.NamedType('c1y', univ.Integer()),
namedtype.NamedType('c2', univ.OctetString()),
namedtype.NamedType('c3', univ.OctetString())
)
def __check_raw_cipher_length__(raw_cipher: bytes):
min_length = SM2CipherLength.C1LenInBytes.value + SM2CipherLength.C3LenInBytes.value
if len(raw_cipher) < min_length:
raise ValueError('invalid cipher length, required at least:{} bytes'.format(min_length))
return
def __parse_sm2_asn1_cipher_bytes__(raw_cipher: bytes,
cipher_mode: Literal[
SM2CipherMode.C1C3C2_ASN1, SM2CipherMode.C1C2C3_ASN1] = SM2CipherMode.C1C3C2_ASN1) -> \
Tuple[
bytes, bytes, bytes, bytes]:
"""
解析 C1C3C2_ASN1 或 C1C2C3_ASN1 格式的密文数据,返回 C1X、C1Y、C3、C2 字节序列
"""
if cipher_mode not in [SM2CipherMode.C1C3C2_ASN1, SM2CipherMode.C1C2C3_ASN1]:
raise ValueError('invalid sm2 cipher mode:{}'.format(cipher_mode))
asn1SpecObj = SM2_C1C3C2_ASN1_Ciphertext()
if cipher_mode == SM2CipherMode.C1C2C3_ASN1:
asn1SpecObj = SM2_C1C2C3_ASN1_Ciphertext()
try:
__check_raw_cipher_length__(raw_cipher)
decoded, _ = decoder.decode(raw_cipher, asn1Spec = asn1SpecObj)
except Exception:
raise ValueError('invalid ASN1 cipher data')
else:
# print(decoded)
c1x = int(decoded['c1x']) # 大整数
c1y = int(decoded['c1y']) # 大整数
c2 = bytes(decoded['c2']) # 字节流
c3 = bytes(decoded['c3']) # 字节流
# 大端字节序
c1x_bytes = c1x.to_bytes(length = 32, byteorder = 'big')
c1y_bytes = c1y.to_bytes(length = 32, byteorder = 'big')
return c1x_bytes, c1y_bytes, c3, c2
def __encode_sm2_cipher_to_asn1_sequence__(cipher_c1c3c2: Tuple[bytes, bytes, bytes, bytes],
cipher_mode: Literal[
SM2CipherMode.C1C3C2_ASN1, SM2CipherMode.C1C2C3_ASN1] = SM2CipherMode.C1C3C2_ASN1) -> bytes:
if cipher_mode not in [SM2CipherMode.C1C3C2_ASN1, SM2CipherMode.C1C2C3_ASN1]:
raise ValueError('invalid sm2 cipher mode:{}'.format(cipher_mode))
try:
c1x = cipher_c1c3c2[0]
c1x_int = int.from_bytes(c1x, byteorder = 'big')
c1y = cipher_c1c3c2[1]
c1y_int = int.from_bytes(c1y, byteorder = 'big')
c3 = cipher_c1c3c2[2]
c2 = cipher_c1c3c2[3]
except Exception as e:
raise ValueError('invalid sm2 cipher data:{}'.format(e))
else:
ciphertext = SM2_C1C3C2_ASN1_Ciphertext()
if cipher_mode == SM2CipherMode.C1C2C3_ASN1:
ciphertext = SM2_C1C2C3_ASN1_Ciphertext()
ciphertext.setComponentByName('c1x', c1x_int)
ciphertext.setComponentByName('c1y', c1y_int)
ciphertext.setComponentByName('c3', c3)
ciphertext.setComponentByName('c2', c2)
encoded_ciphertext = encoder.encode(ciphertext)
return encoded_ciphertext
def __parse_sm2_c1c3c2_cipher_bytes__(raw_cipher: bytes) -> Tuple[bytes, bytes, bytes, bytes]:
"""
解析 C1C3C2 格式的密文数据,返回 C1X、C1Y、C3、C2 字节序列
"""
try:
__check_raw_cipher_length__(raw_cipher)
c1x_bytes = raw_cipher[:SM2CipherLength.C1XLenInBytes.value]
c1y_bytes = raw_cipher[
SM2CipherLength.C1XLenInBytes.value: SM2CipherLength.C1XLenInBytes.value + SM2CipherLength.C1YLenInBytes.value]
c3_bytes = raw_cipher[SM2CipherLength.C1XLenInBytes.value + SM2CipherLength.C1YLenInBytes.value:
SM2CipherLength.C1XLenInBytes.value + SM2CipherLength.C1YLenInBytes.value + SM2CipherLength.C3LenInBytes.value]
c2_bytes = raw_cipher[
SM2CipherLength.C1XLenInBytes.value + SM2CipherLength.C1YLenInBytes.value + SM2CipherLength.C3LenInBytes.value:]
except Exception as e:
raise ValueError('invalid sm2 cipher data:{}'.format(e))
else:
return c1x_bytes, c1y_bytes, c3_bytes, c2_bytes
def __parse_sm2_c1c2c3_bytes__(raw_cipher: bytes) -> Tuple[bytes, bytes, bytes, bytes]:
"""
解析 C1C2C3 格式的密文数据,返回 C1X、C1Y、C3、C2 字节序列
"""
try:
__check_raw_cipher_length__(raw_cipher)
c1x_bytes = raw_cipher[:SM2CipherLength.C1XLenInBytes.value]
c1y_bytes = raw_cipher[
SM2CipherLength.C1XLenInBytes.value: SM2CipherLength.C1XLenInBytes.value + SM2CipherLength.C1YLenInBytes.value]
c3_bytes = raw_cipher[len(raw_cipher) - SM2CipherLength.C3LenInBytes.value:]
c2_bytes = raw_cipher[SM2CipherLength.C1XLenInBytes.value + SM2CipherLength.C1YLenInBytes.value:len(
raw_cipher) - SM2CipherLength.C3LenInBytes.value]
except Exception as e:
raise ValueError('invalid sm2 cipher data:{}'.format(e))
else:
return c1x_bytes, c1y_bytes, c3_bytes, c2_bytes
def __encode_cipher__(target_mode: SM2CipherMode, cipher_c1c3c2: Tuple[bytes, bytes, bytes, bytes]) -> bytes:
"""
将 C1X C1Y C3 C2 密文字节序列编码成指定的 SM2 密文格式
如果是 ASN1 格式,则需要单独做二进制编码
如果是非 ASN1 格式,则只需要按照指定的顺序将 C1、C3、C2进行拼接
"""
try:
c1x = cipher_c1c3c2[0]
c1y = cipher_c1c3c2[1]
c3 = cipher_c1c3c2[2]
c2 = cipher_c1c3c2[3]
except Exception as e:
raise ValueError('invalid cipher data:{}'.format(e))
else:
ret = bytearray()
if target_mode == SM2CipherMode.C1C2C3:
ret.extend(c1x)
ret.extend(c1y)
ret.extend(c2)
ret.extend(c3)
return bytes(ret)
elif target_mode == SM2CipherMode.C1C3C2:
ret.extend(c1x)
ret.extend(c1y)
ret.extend(c3)
ret.extend(c2)
return bytes(ret)
else:
try:
if target_mode in [SM2CipherMode.C1C3C2_ASN1, SM2CipherMode.C1C2C3_ASN1]:
return __encode_sm2_cipher_to_asn1_sequence__(cipher_c1c3c2 = cipher_c1c3c2,
cipher_mode = target_mode)
else:
raise TypeError('invalid cipher mode:{}'.format(target_mode))
except Exception as e:
raise ValueError('encode cipher to asn1 mode:{} error:{}'.format(target_mode, e))
def __parse_and_repack_cipher__(cipher_mode: SM2CipherMode,
cipher_format: SM2CipherFormat,
c1c3c2_asn1_cipher: bytes) -> str:
if not isinstance(cipher_mode, SM2CipherMode):
raise TypeError('invalid cipher mode: {}'.format(cipher_mode))
if not isinstance(cipher_format, SM2CipherFormat):
raise TypeError('invalid cipher format: {}'.format(cipher_format))
encoded_cipher_bytes = c1c3c2_asn1_cipher
if cipher_mode != SM2CipherMode.C1C3C2_ASN1:
# 首先按照C1C3C2_ASN1格式解析原始的数据,获取到 C1X、C1Y、C3、C2这四部分数据
cipher_c1_c3_c2 = __parse_sm2_asn1_cipher_bytes__(raw_cipher = c1c3c2_asn1_cipher,
cipher_mode = SM2CipherMode.C1C3C2_ASN1)
encoded_cipher_bytes = __encode_cipher__(target_mode = cipher_mode, cipher_c1c3c2 = cipher_c1_c3_c2)
if cipher_format == SM2CipherFormat.Base64Str:
return base64.b64encode(encoded_cipher_bytes).decode('utf-8')
else:
return encoded_cipher_bytes.hex()
def __parse_raw_cipher_and_repack_to_c1c3c2_asn1__(cipher_mode: Literal[
SM2CipherMode.C1C3C2_ASN1,
SM2CipherMode.C1C3C2,
SM2CipherMode.C1C2C3_ASN1,
SM2CipherMode.C1C2C3],
raw_cipher_bytes: bytes) -> bytes:
"""
将不同模式下的密文数据统一转换为 C1C3C2_ASN1 模式的密文
"""
try:
__check_raw_cipher_length__(raw_cipher_bytes)
c1_c3_c2_bytes = bytes()
if cipher_mode == SM2CipherMode.C1C3C2_ASN1:
return raw_cipher_bytes
elif cipher_mode == SM2CipherMode.C1C2C3_ASN1:
c1_c3_c2_bytes = __parse_sm2_asn1_cipher_bytes__(raw_cipher = raw_cipher_bytes, cipher_mode = cipher_mode)
elif cipher_mode == SM2CipherMode.C1C2C3:
c1_c3_c2_bytes = __parse_sm2_c1c2c3_bytes__(raw_cipher = raw_cipher_bytes)
elif cipher_mode == SM2CipherMode.C1C3C2:
c1_c3_c2_bytes = __parse_sm2_c1c3c2_cipher_bytes__(raw_cipher = raw_cipher_bytes)
except Exception as e:
raise ValueError('invalid cipher data:{}, cipher mode = {}'.format(e, cipher_mode))
else:
return __encode_cipher__(target_mode = SM2CipherMode.C1C3C2_ASN1, cipher_c1c3c2 = c1_c3_c2_bytes)
class EasySm2Key(object):
"""
EasySM2Key 对象非线程安全,不可并发执行写操作
"""
def __init__(self):
self._point_x = ''
self._point_y = ''
self._private_key_hex = ''
self._sm2_raw_key = Sm2Key()
self.reset_key()
self.new_key()
def reset_key(self):
"""
清理 key 数据
清理后可以使用 new_key() 生成新的 SM2密钥对数据
"""
self.__clear_raw_key_data__()
def __clear_raw_key_data__(self):
# 清空数据
ctypes.memset(ctypes.byref(self._sm2_raw_key.public_key.x), 0, 32)
ctypes.memset(ctypes.byref(self._sm2_raw_key.public_key.y), 0, 32)
ctypes.memset(ctypes.byref(self._sm2_raw_key.private_key), 0, 32)
self._point_x = ''
self._point_y = ''
self._private_key_hex = ''
self._sm2_raw_key._has_public_key = False
self._sm2_raw_key._has_private_key = False
def __set_point_x_y_in_hex__(self):
if self._sm2_raw_key.has_public_key():
self._point_x = bytes(self._sm2_raw_key.public_key.x).hex()
self._point_y = bytes(self._sm2_raw_key.public_key.y).hex()
def __set_private_key_in_hex__(self):
if self._sm2_raw_key.has_private_key():
self._private_key_hex = bytes(self._sm2_raw_key.private_key).hex()
def new_key(self) -> EasySm2Key:
"""
用于在使用 reset_key() 后重新生成新的 SM2 密钥对
"""
self.__clear_raw_key_data__()
self._sm2_raw_key.generate_key()
self.__set_point_x_y_in_hex__()
self.__set_private_key_in_hex__()
return self
def export_to_pem_file(self, file_name_prefix: str, pri_key_password: str):
"""
输入:文件名前缀、私钥密码
假设文件名前缀为 test, 则生成的文件名为: test_sm2_public.pem、test_sm2_private.pem
私钥密码不能为空,最长允许 32 个字节
"""
if len(file_name_prefix) <= 0:
raise ValueError('empty sm2 file name prefix')
pub_key_file_name = f'{file_name_prefix}_sm2_public.pem'
pri_key_file_name = f'{file_name_prefix}_sm2_private.pem'
try:
__check_private_key_password__(pri_key_password)
self._sm2_raw_key.export_public_key_info_pem(pub_key_file_name)
self._sm2_raw_key.export_encrypted_private_key_info_pem(pri_key_file_name, pri_key_password)
except Exception as e:
raise e
def load_sm2_pub_key(self, pub_key_file: str) -> SM2PubKeyRawData:
"""
从 PEM 文件中加载 SM2 公钥
"""
try:
base64_content_data = __easy_read_sm2_pub_pem_file_lines__(pub_key_file)
sm2_pub_raw_data = __easy_parse_sm2_pub_key__(base64_content_data)
except Exception:
raise ValueError('invalid sm2 public key file')
else:
self.__clear_raw_key_data__()
self._sm2_raw_key.import_public_key_info_pem(pub_key_file)
self.__set_point_x_y_in_hex__()
assert sm2_pub_raw_data.hex_data == self.__get_pub_key_by_point__()
return sm2_pub_raw_data
def load_sm2_private_key(self, pri_key_file: str, password: str):
"""
从 PEM 文件中加载 SM2 私钥,加载的私钥必须要输入解密密码
加载密钥时会重置公钥和私钥数据
"""
try:
__check_private_key_password__(password)
self._sm2_raw_key.import_encrypted_private_key_info_pem(pri_key_file, password)
except NativeError as e:
raise ValueError('invalid sm2 private key file or password, {}'.format(e))
except Exception:
raise TypeError('sm2 pem private key imported failed')
else:
self.__set_point_x_y_in_hex__()
self.__set_private_key_in_hex__()
def __get_pub_key_by_point__(self, uncompressed: bool = True) -> str:
"""
在 SM2 公钥十六进制表示中,前导字节04表示该公钥是非压缩形式。
SM2 公钥是椭圆曲线上的一个点,由横坐标X和纵坐标Y两个分量组成。
非压缩形式的公钥直接存储了完整的X和Y坐标值,其格式为04||X||Y ,其中X和Y均为 32 字节
如果公钥是压缩形式,公钥的表示以字节 02 或者 03 开头
"""
if self._sm2_raw_key.has_public_key():
if uncompressed:
return '04' + self._point_x + self._point_y
else:
raise TypeError('SM2 Public Key in compressed form are not supported')
return ''
def get_sm2_public_key_in_hex(self) -> str:
"""
返回公钥的十六进制字符串
如果没有公钥, 则返回的字符串为空
"""
if self._sm2_raw_key.has_public_key():
return self.__get_pub_key_by_point__()
return ''
def get_sm2_private_key_in_hex(self) -> str:
"""
返回私钥的十六进制字符串
如果没有私钥,则返回的字符串为空
"""
if self._sm2_raw_key.has_public_key():
return self._private_key_hex
return ''
def get_point_in_hex(self) -> Dict[str, str]:
"""
返回 [X, Y] 坐标的十六进制字符串
如果没有公钥,则返回的坐标值为空
"""
if self._sm2_raw_key.has_public_key():
return {'X': self._point_x, 'Y': self._point_y}
return {'X': '', 'Y': ''}
class EasySm2EncryptionKey(EasySm2Key):
def __init__(self):
super().__init__()
def Encrypt(self, plain_data: bytes,
cipher_mode: Literal[
SM2CipherMode.C1C3C2_ASN1,
SM2CipherMode.C1C3C2,
SM2CipherMode.C1C2C3_ASN1,
SM2CipherMode.C1C2C3] = SM2CipherMode.C1C3C2_ASN1,
cipher_format: Literal[
SM2CipherFormat.Base64Str,
SM2CipherFormat.HexStr] = SM2CipherFormat.Base64Str) -> str:
if not isinstance(cipher_mode, SM2CipherMode):
raise TypeError('invalid cipher mode: {}'.format(cipher_mode))
if not isinstance(cipher_format, SM2CipherFormat):
raise TypeError('invalid cipher format: {}'.format(cipher_format))
if self._sm2_raw_key.has_public_key():
if len(plain_data) <= SM2_MAX_PLAINTEXT_SIZE:
c1c3c2_asn1_cipher_bytes: bytes = self._sm2_raw_key.encrypt(plain_data)
return __parse_and_repack_cipher__(cipher_mode, cipher_format, c1c3c2_asn1_cipher_bytes)
else:
raise ValueError('the maximum limit for the plaintext is {} bytes'.format(SM2_MAX_PLAINTEXT_SIZE))
else:
raise ValueError('empty sm2 public key')
def Decrypt(self, cipher_data: bytes,
cipher_mode: Literal[
SM2CipherMode.C1C3C2_ASN1,
SM2CipherMode.C1C3C2,
SM2CipherMode.C1C2C3_ASN1,
SM2CipherMode.C1C2C3] = SM2CipherMode.C1C3C2_ASN1) -> bytes:
"""
cipher_data: 密文数据
cipher_mode: 密文模式
返回明文的字节序列
"""
if not isinstance(cipher_mode, SM2CipherMode):
raise TypeError('invalid cipher mode: {}'.format(cipher_mode))
if not self._sm2_raw_key.has_private_key():
raise TypeError('no private key included, can not decrypt')
if len(cipher_data) > SM2_MAX_CIPHERTEXT_SIZE:
raise ValueError('cipher data too long, the maximum limit for the cipher is {} bytes'.format(SM2_MAX_CIPHERTEXT_SIZE))
try:
to_be_decrypted_cipher = __parse_raw_cipher_and_repack_to_c1c3c2_asn1__(cipher_mode = cipher_mode,
raw_cipher_bytes = cipher_data)
ret = bytes(self._sm2_raw_key.decrypt(to_be_decrypted_cipher))
except Exception as e:
raise ValueError('decrypt error:{}, cipher mode = {}'.format(e, cipher_mode))
else:
return ret
if __name__ == '__main__':
enc = EasySm2EncryptionKey()
enc.load_sm2_private_key('./test_keys/tmp_test_sm2_private.pem', '123456')
plain = 'hello,world'
print('明文:', plain.encode('utf-8').hex())
print('随机生成的公钥数据:', enc.get_sm2_public_key_in_hex())
print('随机生成的私钥数据:', enc.get_sm2_private_key_in_hex())
print('公钥 XY 坐标:', enc.get_point_in_hex())
print('-' * 32)
for mode in SM2CipherMode:
print(mode, '密文 in Hex:', enc.Encrypt('hello,world'.encode('utf-8'), mode, SM2CipherFormat.HexStr))
print('-' * 32)
# c1c3c2_asn1_cipher_hex = "307302202DDE3E3B518AE79A0DA24792AACCAF277C70D2BF094A721402F988ABF34D8A2B022045FF327DDDECEDB4A239BF262539A435AC4B5A2CD40496921A15C44DE4FD8ED60420EDDF4218FE658B672FC09E3F86676702EC380AAA4A9495C26BDAB191826FB547040BC6CF28A8BF426DF50F5E4F"
# c1c2c3_asn1_cipher_hex = "3074022100AEC56299468A3F0915D07607D25CE80091953530962F60CB953269AA17D1CC370220775B350FFF2F5E6593DDF289D74EF180D272EE27F7EFC7BF7E77FF760B26A376040B603717A97A68C54DD12D33042034049DB7F277C2E78E9984E01BB5B1F8718CA1CB4ADFB5DB567604A65E877C4E"
# c1c3c2_cipher_hex = "D3E1C15A8DE95D7213C916DAD6E416764910DC219F9E2E59283D55C6F124DEA845948F16201DA56B4072D7A63E81DB50993133338B6571C2D4FC4A6DA25C17D956508371AB83490E140E6445CC2A2224CB576D2711B698D67BCA38004119C91AD6F505BAC893ACBAE5B8B7"
# c1c2c3_cipher_hex = "F7F93B18B51DEE2384EF6EF4E45F5802FD980C0B00131CBE8006E89BA66D8E1241855F38293970306C974D4DD929A3D059BB9082DD7AA68420630B24A61E92754A4307FB47B3FEB7CB15E7D1F94CF4F99F8378548ED73D0EDD86418D823ACDB58F1802B7C8BB03F99112F7"
#
# tmp_ciphers = {
# SM2CipherMode.C1C3C2_ASN1: c1c3c2_asn1_cipher_hex,
# SM2CipherMode.C1C2C3_ASN1: c1c2c3_asn1_cipher_hex,
# SM2CipherMode.C1C2C3: c1c2c3_cipher_hex,
# SM2CipherMode.C1C3C2: c1c3c2_cipher_hex,
# }
#
# for mode, cipher in tmp_ciphers.items():
# try:
# plain_hex = enc.decrypt(bytes.fromhex(cipher), mode).hex()
# except Exception as e:
# print('decrypt failed, mode={}'.format(mode))
# else:
# print('mode={}, decrypt success:{}, 明文 in Hex:{}'.format(mode, plain_hex == plain.encode('utf-8').hex(), plain_hex))