plugin - fixes key generation

Key generation was performed using pyca/crpytography but keys were expected to be objects from coincurve. This comes from teos_cli where keys are generated beforehand and stored, and later on loaded from disk. The plugin generates keys and uses them straightaway (at least the first time), so it would fail in that case.
This commit is contained in:
Sergi Delgado Segura
2020-05-05 18:46:37 +02:00
parent df43d30ca5
commit bef8df8d36

View File

@@ -1,9 +1,6 @@
import os.path
from pathlib import Path
from binascii import hexlify
from cryptography.hazmat.backends import default_backend
from cryptography.hazmat.primitives import serialization
from cryptography.hazmat.primitives.asymmetric import ec
from coincurve import PrivateKey
from common.exceptions import InvalidKey
from common.cryptographer import Cryptographer
@@ -11,21 +8,15 @@ from common.cryptographer import Cryptographer
def save_key(sk, filename):
"""
Saves secret key on disk.
Saves the secret key on disk.
Args:
sk (:obj:`PrivateKey`): a private key file to be saved on disk.
sk (:obj:`EllipticCurvePrivateKey`): a private key file to be saved on disk.
filename (:obj:`str`): the name that will be given to the key file.
"""
der = sk.private_bytes(
encoding=serialization.Encoding.DER,
format=serialization.PrivateFormat.PKCS8,
encryption_algorithm=serialization.NoEncryption(),
)
with open(filename, "wb") as der_out:
der_out.write(der)
der_out.write(sk.to_der())
def generate_keys(data_dir):
@@ -36,8 +27,8 @@ def generate_keys(data_dir):
data_dir (:obj:`str`): path to data directory where the keys will be stored.
Returns:
:obj:`tuple`: a tuple containing a ``PrivateKey`` and a ``str`` representing the client sk and compressed
pk respectively.
:obj:`tuple`: a tuple containing a ``PrivateKey`` and a ``str`` representing the client sk and
compressed pk respectively.
Raises:
:obj:`FileExistsError`: if the key pair already exists in the given directory.
@@ -50,14 +41,11 @@ def generate_keys(data_dir):
if os.path.exists(sk_file_name):
raise FileExistsError("The client key pair already exists")
sk = ec.generate_private_key(ec.SECP256K1, default_backend())
sk = PrivateKey()
pk = sk.public_key
save_key(sk, sk_file_name)
compressed_pk = sk.public_key().public_bytes(
encoding=serialization.Encoding.X962, format=serialization.PublicFormat.CompressedPoint
)
return sk, hexlify(compressed_pk).decode("utf-8")
return sk, Cryptographer.get_compressed_pk(pk)
def load_keys(data_dir):
@@ -68,8 +56,8 @@ def load_keys(data_dir):
data_dir (:obj:`str`): path to data directory where the keys are stored.
Returns:
:obj:`tuple`: a tuple containing a ``PrivateKey`` and a ``str`` representing the client sk and compressed
pk respectively.
:obj:`tuple`: a tuple containing a ``EllipticCurvePrivateKey`` and a ``str`` representing the client sk and
compressed pk respectively.
Raises:
:obj:`InvalidKey <cli.exceptions.InvalidKey>`: if any of the keys is invalid or cannot be loaded.