CryptMessage.py 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. from lib.pybitcointools import bitcoin as btctools
  2. import hashlib
  3. ecc_cache = {}
  4. def encrypt(data, pubkey, ephemcurve=None, ciphername='aes-256-cbc'):
  5. from lib import pyelliptic
  6. curve, pubkey_x, pubkey_y, i = pyelliptic.ECC._decode_pubkey(pubkey)
  7. if ephemcurve is None:
  8. ephemcurve = curve
  9. ephem = pyelliptic.ECC(curve=ephemcurve)
  10. key = hashlib.sha512(ephem.raw_get_ecdh_key(pubkey_x, pubkey_y)).digest()
  11. key_e, key_m = key[:32], key[32:]
  12. pubkey = ephem.get_pubkey()
  13. iv = pyelliptic.OpenSSL.rand(pyelliptic.OpenSSL.get_cipher(ciphername).get_blocksize())
  14. ctx = pyelliptic.Cipher(key_e, iv, 1, ciphername)
  15. ciphertext = iv + pubkey + ctx.ciphering(data)
  16. mac = pyelliptic.hmac_sha256(key_m, ciphertext)
  17. return key_e, ciphertext + mac
  18. def split(encrypted):
  19. iv = encrypted[0:16]
  20. ciphertext = encrypted[16+70:-32]
  21. return iv, ciphertext
  22. def getEcc(privatekey=None):
  23. from lib import pyelliptic
  24. global eccs
  25. if privatekey not in ecc_cache:
  26. if privatekey:
  27. publickey_bin = btctools.encode_pubkey(btctools.privtopub(privatekey), "bin")
  28. publickey_openssl = toOpensslPublickey(publickey_bin)
  29. privatekey_openssl = toOpensslPrivatekey(privatekey)
  30. ecc_cache[privatekey] = pyelliptic.ECC(curve='secp256k1', privkey=privatekey_openssl, pubkey=publickey_openssl)
  31. else:
  32. ecc_cache[None] = pyelliptic.ECC()
  33. return ecc_cache[privatekey]
  34. def toOpensslPrivatekey(privatekey):
  35. privatekey_bin = btctools.encode_privkey(privatekey, "bin")
  36. return '\x02\xca\x00\x20' + privatekey_bin
  37. def toOpensslPublickey(publickey):
  38. publickey_bin = btctools.encode_pubkey(publickey, "bin")
  39. publickey_bin = publickey_bin[1:]
  40. publickey_openssl = '\x02\xca\x00 ' + publickey_bin[:32] + '\x00 ' + publickey_bin[32:]
  41. return publickey_openssl