Skip to content

Commit 700b018

Browse files
committed
Support importing sm2 curve
1 parent bef03fc commit 700b018

File tree

1 file changed

+51
-0
lines changed

1 file changed

+51
-0
lines changed

lib/Crypto/PublicKey/ECC.py

Lines changed: 51 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -456,6 +456,52 @@ def init_ed448():
456456
del init_ed448
457457

458458

459+
sm2_names = ["sm2", "sm2p256v1"]
460+
461+
462+
def init_sm2p256v1():
463+
p = 0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF
464+
b = 0x28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93
465+
order = 0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123
466+
Gx = 0x32c4ae2c1f1981195f9904466a39c9948fe30bbff2660be1715a4589334c74c7
467+
Gy = 0xbc3736a2f4f6779c59bdcee36b692153d0a9877cc62a474002df32e52139f0a0
468+
469+
p256_modulus = long_to_bytes(p, 32)
470+
p256_b = long_to_bytes(b, 32)
471+
p256_order = long_to_bytes(order, 32)
472+
473+
ec_p256_context = VoidPointer()
474+
result = _ec_lib.ec_ws_new_context(ec_p256_context.address_of(),
475+
c_uint8_ptr(p256_modulus),
476+
c_uint8_ptr(p256_b),
477+
c_uint8_ptr(p256_order),
478+
c_size_t(len(p256_modulus)),
479+
c_ulonglong(getrandbits(64))
480+
)
481+
if result:
482+
raise ImportError("Error %d initializing sm2p256v1 context" % result)
483+
484+
context = SmartPointer(ec_p256_context.get(), _ec_lib.ec_free_context)
485+
p256 = _Curve(Integer(p),
486+
Integer(b),
487+
Integer(order),
488+
Integer(Gx),
489+
Integer(Gy),
490+
None,
491+
256,
492+
"1.2.156.10197.1.301", # China GM Standards Committee
493+
context,
494+
"sm2p256v1",
495+
None,
496+
"sm2")
497+
global sm2_names
498+
_curves.update(dict.fromkeys(sm2_names, p256))
499+
500+
501+
init_sm2p256v1()
502+
del init_sm2p256v1
503+
504+
459505
class UnsupportedEccFeature(ValueError):
460506
pass
461507

@@ -701,6 +747,11 @@ def __rmul__(self, left_hand):
701747
_curves.update(dict.fromkeys(ed448_names, ed448))
702748
del ed448_G, ed448, ed448_names
703749

750+
sm2p256_G = EccPoint(_curves['sm2'].Gx, _curves['sm2'].Gy, "sm2")
751+
sm2p256 = _curves['sm2']._replace(G=sm2p256_G)
752+
_curves.update(dict.fromkeys(sm2_names, sm2p256))
753+
del sm2p256_G, sm2p256, sm2_names
754+
704755

705756
class EccKey(object):
706757
r"""Class defining an ECC key.

0 commit comments

Comments
 (0)