2019-09-25 00:50:03 +08:00
|
|
|
from libp2p.crypto.ed25519 import Ed25519PrivateKey, Ed25519PublicKey
|
2019-09-25 00:38:59 +08:00
|
|
|
from libp2p.crypto.exceptions import MissingDeserializerError
|
2019-08-24 04:12:13 +08:00
|
|
|
from libp2p.crypto.keys import KeyType, PrivateKey, PublicKey
|
2019-09-05 00:13:19 +08:00
|
|
|
from libp2p.crypto.rsa import RSAPublicKey
|
2019-08-24 04:12:13 +08:00
|
|
|
from libp2p.crypto.secp256k1 import Secp256k1PrivateKey, Secp256k1PublicKey
|
|
|
|
|
|
|
|
key_type_to_public_key_deserializer = {
|
2019-09-05 00:13:19 +08:00
|
|
|
KeyType.Secp256k1.value: Secp256k1PublicKey.from_bytes,
|
|
|
|
KeyType.RSA.value: RSAPublicKey.from_bytes,
|
2019-09-10 08:04:35 +08:00
|
|
|
KeyType.Ed25519.value: Ed25519PublicKey.from_bytes,
|
2019-08-24 04:12:13 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
key_type_to_private_key_deserializer = {
|
2019-09-25 00:50:03 +08:00
|
|
|
KeyType.Secp256k1.value: Secp256k1PrivateKey.from_bytes,
|
|
|
|
KeyType.Ed25519.value: Ed25519PrivateKey.from_bytes,
|
2019-08-24 04:12:13 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
def deserialize_public_key(data: bytes) -> PublicKey:
|
|
|
|
f = PublicKey.deserialize_from_protobuf(data)
|
2019-09-25 00:38:59 +08:00
|
|
|
try:
|
|
|
|
deserializer = key_type_to_public_key_deserializer[f.key_type]
|
2019-12-20 00:31:18 +08:00
|
|
|
except KeyError as e:
|
|
|
|
raise MissingDeserializerError(
|
|
|
|
{"key_type": f.key_type, "key": "public_key"}
|
|
|
|
) from e
|
2019-08-24 04:12:13 +08:00
|
|
|
return deserializer(f.data)
|
|
|
|
|
|
|
|
|
|
|
|
def deserialize_private_key(data: bytes) -> PrivateKey:
|
|
|
|
f = PrivateKey.deserialize_from_protobuf(data)
|
2019-09-25 00:38:59 +08:00
|
|
|
try:
|
|
|
|
deserializer = key_type_to_private_key_deserializer[f.key_type]
|
2019-12-20 00:31:18 +08:00
|
|
|
except KeyError as e:
|
|
|
|
raise MissingDeserializerError(
|
|
|
|
{"key_type": f.key_type, "key": "private_key"}
|
|
|
|
) from e
|
2019-08-24 04:12:13 +08:00
|
|
|
return deserializer(f.data)
|