Asymmetric encryption with Elliptic Curve Cryptography (ECC) ECDH, ECDSA and ECIES import pyelliptic alice = pyelliptic.ECC() # default curve: sect283r1 bob = pyelliptic.ECC(curve='sect571r1') ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey())
| 12 | |
| 13 | |
| 14 | class ECC: |
| 15 | """ |
| 16 | Asymmetric encryption with Elliptic Curve Cryptography (ECC) |
| 17 | ECDH, ECDSA and ECIES |
| 18 | |
| 19 | import pyelliptic |
| 20 | |
| 21 | alice = pyelliptic.ECC() # default curve: sect283r1 |
| 22 | bob = pyelliptic.ECC(curve='sect571r1') |
| 23 | |
| 24 | ciphertext = alice.encrypt("Hello Bob", bob.get_pubkey()) |
| 25 | print bob.decrypt(ciphertext) |
| 26 | |
| 27 | signature = bob.sign("Hello Alice") |
| 28 | # alice's job : |
| 29 | print pyelliptic.ECC( |
| 30 | pubkey=bob.get_pubkey()).verify(signature, "Hello Alice") |
| 31 | |
| 32 | # ERROR !!! |
| 33 | try: |
| 34 | key = alice.get_ecdh_key(bob.get_pubkey()) |
| 35 | except: print("For ECDH key agreement,\ |
| 36 | the keys must be defined on the same curve !") |
| 37 | |
| 38 | alice = pyelliptic.ECC(curve='sect571r1') |
| 39 | print alice.get_ecdh_key(bob.get_pubkey()).encode('hex') |
| 40 | print bob.get_ecdh_key(alice.get_pubkey()).encode('hex') |
| 41 | |
| 42 | """ |
| 43 | def __init__(self, pubkey=None, privkey=None, pubkey_x=None, |
| 44 | pubkey_y=None, raw_privkey=None, curve='sect283r1'): |
| 45 | """ |
| 46 | For a normal and High level use, specifie pubkey, |
| 47 | privkey (if you need) and the curve |
| 48 | """ |
| 49 | if type(curve) == str: |
| 50 | self.curve = OpenSSL.get_curve(curve) |
| 51 | else: |
| 52 | self.curve = curve |
| 53 | |
| 54 | if pubkey_x is not None and pubkey_y is not None: |
| 55 | self._set_keys(pubkey_x, pubkey_y, raw_privkey) |
| 56 | elif pubkey is not None: |
| 57 | curve, pubkey_x, pubkey_y, i = ECC._decode_pubkey(pubkey) |
| 58 | if privkey is not None: |
| 59 | curve2, raw_privkey, i = ECC._decode_privkey(privkey) |
| 60 | if curve != curve2: |
| 61 | raise Exception("Bad ECC keys ...") |
| 62 | self.curve = curve |
| 63 | self._set_keys(pubkey_x, pubkey_y, raw_privkey) |
| 64 | else: |
| 65 | self.privkey, self.pubkey_x, self.pubkey_y = self._generate() |
| 66 | |
| 67 | def _set_keys(self, pubkey_x, pubkey_y, privkey): |
| 68 | if self.raw_check_key(privkey, pubkey_x, pubkey_y) < 0: |
| 69 | self.pubkey_x = None |
| 70 | self.pubkey_y = None |
| 71 | self.privkey = None |