From 5fdca2ffb2460045b9920739ca481b397ced5946 Mon Sep 17 00:00:00 2001 From: Alex Stokes Date: Mon, 9 Sep 2019 20:23:44 -0400 Subject: [PATCH] Add public key implementation --- libp2p/crypto/ed25519.py | 45 +++++++++++++++++++++++++++++++++++----- 1 file changed, 40 insertions(+), 5 deletions(-) diff --git a/libp2p/crypto/ed25519.py b/libp2p/crypto/ed25519.py index 1b34a705..61c46311 100644 --- a/libp2p/crypto/ed25519.py +++ b/libp2p/crypto/ed25519.py @@ -1,13 +1,15 @@ from Crypto.Hash import SHA256 -from libp2p.crypto.keys import KeyType, PublicKey +from libp2p.crypto.keys import KeyPair, KeyType, PrivateKey, PublicKey from nacl.exceptions import BadSignatureError -from nacl.public import PublicKey as Ed255129PublicKeyImpl -from nacl.signing import VerifyKey +from nacl.public import PrivateKey as PrivateKeyImpl +from nacl.public import PublicKey as PublicKeyImpl +from nacl.signing import SigningKey, VerifyKey +import nacl.utils as utils class Ed25519PublicKey(PublicKey): - def __init__(self, impl: Ed255129PublicKeyImpl) -> None: + def __init__(self, impl: PublicKeyImpl) -> None: self.impl = impl def to_bytes(self) -> bytes: @@ -15,7 +17,7 @@ class Ed25519PublicKey(PublicKey): @classmethod def from_bytes(cls, key_bytes: bytes) -> "Ed25519PublicKey": - return cls(Ed255129PublicKeyImpl(key_bytes)) + return cls(PublicKeyImpl(key_bytes)) def get_type(self) -> KeyType: return KeyType.Ed25519 @@ -28,3 +30,36 @@ class Ed25519PublicKey(PublicKey): except BadSignatureError: return False return True + + +class Ed25519PrivateKey(PrivateKey): + def __init__(self, impl: PrivateKeyImpl) -> None: + self.impl = impl + + @classmethod + def new(cls, seed: bytes = None) -> "Ed25519PrivateKey": + if not seed: + seed = utils.random() + + private_key_impl = PrivateKeyImpl.from_seed(seed) + return cls(private_key_impl) + + def to_bytes(self) -> bytes: + return bytes(self.impl) + + def get_type(self) -> KeyType: + return KeyType.Ed25519 + + def sign(self, data: bytes) -> bytes: + h = SHA256.new(data) + signing_key = SigningKey(self.to_bytes()) + return signing_key.sign(h) + + def get_public_key(self) -> PublicKey: + return Ed25519PublicKey(self.impl.public_key) + + +def create_new_key_pair(seed: bytes = None) -> KeyPair: + private_key = Ed25519PrivateKey.new(seed) + public_key = private_key.get_public_key() + return KeyPair(private_key, public_key)