CryptMessage.py 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. import hashlib
  2. import base64
  3. import struct
  4. from lib import sslcrypto
  5. from Crypt import Crypt
  6. curve = sslcrypto.ecc.get_curve("secp256k1")
  7. def eciesEncrypt(data, pubkey, ciphername="aes-256-cbc"):
  8. ciphertext, key_e = curve.encrypt(
  9. data,
  10. base64.b64decode(pubkey),
  11. algo=ciphername,
  12. derivation="sha512",
  13. return_aes_key=True
  14. )
  15. return key_e, ciphertext
  16. @Crypt.thread_pool_crypt.wrap
  17. def eciesDecryptMulti(encrypted_datas, privatekey):
  18. texts = [] # Decoded texts
  19. for encrypted_data in encrypted_datas:
  20. try:
  21. text = eciesDecrypt(encrypted_data, privatekey).decode("utf8")
  22. texts.append(text)
  23. except Exception:
  24. texts.append(None)
  25. return texts
  26. def eciesDecrypt(ciphertext, privatekey):
  27. return curve.decrypt(base64.b64decode(ciphertext), curve.wif_to_private(privatekey.encode()), derivation="sha512")
  28. def decodePubkey(pubkey):
  29. i = 0
  30. curve = struct.unpack('!H', pubkey[i:i + 2])[0]
  31. i += 2
  32. tmplen = struct.unpack('!H', pubkey[i:i + 2])[0]
  33. i += 2
  34. pubkey_x = pubkey[i:i + tmplen]
  35. i += tmplen
  36. tmplen = struct.unpack('!H', pubkey[i:i + 2])[0]
  37. i += 2
  38. pubkey_y = pubkey[i:i + tmplen]
  39. i += tmplen
  40. return curve, pubkey_x, pubkey_y, i
  41. def split(encrypted):
  42. iv = encrypted[0:16]
  43. curve, pubkey_x, pubkey_y, i = decodePubkey(encrypted[16:])
  44. ciphertext = encrypted[16 + i:-32]
  45. return iv, ciphertext