Legrandin / pycryptodome

A self-contained cryptographic library for Python
https://www.pycryptodome.org
Other
2.85k stars 503 forks source link

suggest to add sm4 encrypt and decrypt #455

Open l1t1 opened 4 years ago

l1t1 commented 4 years ago

the pure python version(pysm4 on github) is very slow, i cannot port the c version into python by myself.

l1t1 commented 4 years ago
def test_SM4_ECB(n):
 #from Crypto.Cipher import AES
 from pysm4 import encrypt_ecb, decrypt_ecb
 import time
 #obj = AES.new('This is a key123', AES.MODE_ECB, 'This is an IV456')
 message = 'a' * 160
 t1 = time.time()
 key='This is a key123'
 for i in xrange(10000*n):
     ciphertext = encrypt_ecb(message,key)
     #obj2 = AES.new('This is a key123', AES.MODE_ECB, 'This is an IV456')
     text = decrypt_ecb(ciphertext,key)
     #print text
 t2 = time.time()
 print (t2 - t1)

def test_AES_ECB(n):
 from Crypto.Cipher import AES
 import time
 obj = AES.new('This is a key123', AES.MODE_ECB, 'This is an IV456')
 message = 'a' * 160
 t1 = time.time()
 for i in xrange(10000*n):
     ciphertext = obj.encrypt(message)
     obj2 = AES.new('This is a key123', AES.MODE_ECB, 'This is an IV456')
     text = obj2.decrypt(ciphertext)
     #print text
 t2 = time.time()
 print (t2 - t1)

test_SM4_ECB(1) costs 600 s, while test_ASE_ECB(1) costs 0.1 s

l1t1 commented 4 years ago

the c code https://github.com/NEWPLAN/SMx/tree/master/SM4/Linux

l1t1 commented 4 years ago

my test of sm4 vs aes(https://github.com/zhouyangchao/AES) encrpt 1000000 times

aes
real    0m20.359s
user    0m6.748s
sys     0m0.008s

sm4
real    0m0.796s
user    0m0.266s
sys     0m0.001s
l1t1 commented 4 years ago

i run this code on pypy, 3 time faster than the original python

def test_SM4_ECB(n):
  #from pysm4 import encrypt_ecb, decrypt_ecb
  import time
  message = 'a' * 16
  t1 = time.time()
  key='This is a key123'
  for i in xrange(10000*n):ciphertext = encrypt_ecb(message,key)
  t2 = time.time()
  print (t2 - t1)

>>>> test_SM4_ECB(1)
9.86400008202
>>>> test_SM4_ECB(10)
84.7309999466
#python 3.5
>>> def test_SM4_ECB(n):
...   #from pysm4 import encrypt_ecb, decrypt_ecb
...   import time
...   message = 'a' * 16
...   t1 = time.time()
...   key='This is a key123'
...   for i in range(10000*n):ciphertext = encrypt_ecb(message,key)
...   t2 = time.time()
...   print (t2 - t1)
...
>>> test_SM4_ECB(1)
29.570343494415283
texadactyl commented 4 years ago

@l1t1

I am guessing that you need to interface to a China system that is employing SM4, Otherwise, you should be using an international standard like AES.

You could clone one of the github SM4 implementations and adapt numba (JIT compilation) or cython (conventional compilation) to it. Try this search on github: https://github.com/search?o=desc&q=sm4&s=updated&type=Repositories

l1t1 commented 3 years ago

@texadactyl thanks, I will try numba

l1t1 commented 3 years ago

i found this https://github.com/pyca/pyopenssl docs https://www.pyopenssl.org/en/stable/