2019-09-10 08:04:35 +08:00
|
|
|
from Crypto.Hash import SHA256
|
2019-09-10 08:18:39 +08:00
|
|
|
from nacl.exceptions import BadSignatureError
|
2019-09-10 08:23:44 +08:00
|
|
|
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
|
2019-09-10 08:04:35 +08:00
|
|
|
|
2019-09-25 01:07:33 +08:00
|
|
|
from libp2p.crypto.keys import KeyPair, KeyType, PrivateKey, PublicKey
|
|
|
|
|
2019-09-10 08:04:35 +08:00
|
|
|
|
|
|
|
class Ed25519PublicKey(PublicKey):
|
2019-09-10 08:23:44 +08:00
|
|
|
def __init__(self, impl: PublicKeyImpl) -> None:
|
2019-09-10 08:04:35 +08:00
|
|
|
self.impl = impl
|
|
|
|
|
|
|
|
def to_bytes(self) -> bytes:
|
|
|
|
return bytes(self.impl)
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def from_bytes(cls, key_bytes: bytes) -> "Ed25519PublicKey":
|
2019-09-10 08:23:44 +08:00
|
|
|
return cls(PublicKeyImpl(key_bytes))
|
2019-09-10 08:04:35 +08:00
|
|
|
|
|
|
|
def get_type(self) -> KeyType:
|
|
|
|
return KeyType.Ed25519
|
|
|
|
|
|
|
|
def verify(self, data: bytes, signature: bytes) -> bool:
|
|
|
|
verify_key = VerifyKey(self.to_bytes())
|
|
|
|
try:
|
2021-03-16 15:55:44 +08:00
|
|
|
verify_key.verify(data, signature)
|
2019-09-10 08:04:35 +08:00
|
|
|
except BadSignatureError:
|
|
|
|
return False
|
|
|
|
return True
|
2019-09-10 08:23:44 +08:00
|
|
|
|
|
|
|
|
|
|
|
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)
|
|
|
|
|
2019-09-25 00:50:03 +08:00
|
|
|
@classmethod
|
|
|
|
def from_bytes(cls, data: bytes) -> "Ed25519PrivateKey":
|
|
|
|
impl = PrivateKeyImpl(data)
|
|
|
|
return cls(impl)
|
|
|
|
|
2019-09-10 08:23:44 +08:00
|
|
|
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)
|