From 3c97a5a0ed63660381cb87bcbe7c32dbe4dd53d3 Mon Sep 17 00:00:00 2001 From: Alex Stokes Date: Fri, 23 Aug 2019 16:54:16 +0200 Subject: [PATCH] Add ECC key implementation --- libp2p/crypto/ecc.py | 55 +++++++++++++++++++++++++++++++++++++++++++ libp2p/crypto/keys.py | 1 + 2 files changed, 56 insertions(+) create mode 100644 libp2p/crypto/ecc.py diff --git a/libp2p/crypto/ecc.py b/libp2p/crypto/ecc.py new file mode 100644 index 0000000..7cfb433 --- /dev/null +++ b/libp2p/crypto/ecc.py @@ -0,0 +1,55 @@ +from Crypto.PublicKey import ECC +from Crypto.PublicKey.ECC import EccKey + +from libp2p.crypto.keys import KeyPair, KeyType, PrivateKey, PublicKey + + +class ECCPublicKey(PublicKey): + def __init__(self, impl: EccKey) -> None: + self.impl = impl + + def to_bytes(self) -> bytes: + return self.impl.export_key("DER") + + @classmethod + def from_bytes(cls, data: bytes) -> "ECCPublicKey": + public_key_impl = ECC.import_key(data) + return cls(public_key_impl) + + def get_type(self) -> KeyType: + return KeyType.ECC_P256 + + def verify(self, data: bytes, signature: bytes) -> bool: + raise NotImplementedError + + +class ECCPrivateKey(PrivateKey): + def __init__(self, impl: EccKey) -> None: + self.impl = impl + + @classmethod + def new(cls, curve: str) -> "ECCPrivateKey": + private_key_impl = ECC.generate(curve=curve) + return cls(private_key_impl) + + def to_bytes(self) -> bytes: + return self.impl.export_key("DER") + + def get_type(self) -> KeyType: + return KeyType.ECC_P256 + + def sign(self, data: bytes) -> bytes: + raise NotImplementedError + + def get_public_key(self) -> PublicKey: + return ECCPublicKey(self.impl.publickey()) + + +def create_new_key_pair(curve: str) -> KeyPair: + """ + Returns a new RSA keypair with the requested key size (``bits``) and the given public + exponent ``e``. Sane defaults are provided for both values. + """ + private_key = ECCPrivateKey.new(curve) + public_key = private_key.get_public_key() + return KeyPair(private_key, public_key) diff --git a/libp2p/crypto/keys.py b/libp2p/crypto/keys.py index 31caca0..33cca9d 100644 --- a/libp2p/crypto/keys.py +++ b/libp2p/crypto/keys.py @@ -11,6 +11,7 @@ class KeyType(Enum): Ed25519 = 1 Secp256k1 = 2 ECDSA = 3 + ECC_P256 = 4 class Key(ABC):