2019-09-05 00:27:57 +08:00
|
|
|
from Crypto.Hash import SHA256
|
2019-08-14 09:17:08 +08:00
|
|
|
import Crypto.PublicKey.RSA as RSA
|
|
|
|
from Crypto.PublicKey.RSA import RsaKey
|
2019-09-05 00:27:57 +08:00
|
|
|
from Crypto.Signature import pkcs1_15
|
2019-08-14 09:17:08 +08:00
|
|
|
|
2019-08-14 11:23:07 +08:00
|
|
|
from libp2p.crypto.keys import KeyPair, KeyType, PrivateKey, PublicKey
|
2019-08-14 09:17:08 +08:00
|
|
|
|
|
|
|
|
|
|
|
class RSAPublicKey(PublicKey):
|
|
|
|
def __init__(self, impl: RsaKey) -> None:
|
|
|
|
self.impl = impl
|
|
|
|
|
|
|
|
def to_bytes(self) -> bytes:
|
|
|
|
return self.impl.export_key("DER")
|
|
|
|
|
2019-08-20 23:54:33 +08:00
|
|
|
@classmethod
|
|
|
|
def from_bytes(cls, key_bytes: bytes) -> "RSAPublicKey":
|
|
|
|
rsakey = RSA.import_key(key_bytes)
|
|
|
|
return cls(rsakey)
|
|
|
|
|
2019-08-14 09:17:08 +08:00
|
|
|
def get_type(self) -> KeyType:
|
|
|
|
return KeyType.RSA
|
|
|
|
|
|
|
|
def verify(self, data: bytes, signature: bytes) -> bool:
|
2019-09-05 00:27:57 +08:00
|
|
|
h = SHA256.new(data)
|
|
|
|
try:
|
2019-09-05 01:19:27 +08:00
|
|
|
# NOTE: the typing in ``pycryptodome`` is wrong on the arguments to ``verify``.
|
|
|
|
pkcs1_15.new(self.impl).verify(h, signature) # type: ignore
|
2019-09-05 00:27:57 +08:00
|
|
|
except (ValueError, TypeError):
|
|
|
|
return False
|
|
|
|
return True
|
2019-08-14 09:17:08 +08:00
|
|
|
|
|
|
|
|
|
|
|
class RSAPrivateKey(PrivateKey):
|
|
|
|
def __init__(self, impl: RsaKey) -> None:
|
|
|
|
self.impl = impl
|
|
|
|
|
|
|
|
@classmethod
|
|
|
|
def new(cls, bits: int = 2048, e: int = 65537) -> "RSAPrivateKey":
|
|
|
|
private_key_impl = RSA.generate(bits, e=e)
|
|
|
|
return cls(private_key_impl)
|
|
|
|
|
|
|
|
def to_bytes(self) -> bytes:
|
|
|
|
return self.impl.export_key("DER")
|
|
|
|
|
|
|
|
def get_type(self) -> KeyType:
|
|
|
|
return KeyType.RSA
|
|
|
|
|
|
|
|
def sign(self, data: bytes) -> bytes:
|
2019-09-05 00:27:57 +08:00
|
|
|
h = SHA256.new(data)
|
2019-09-05 01:19:27 +08:00
|
|
|
# NOTE: the typing in ``pycryptodome`` is wrong on the arguments to ``sign``.
|
|
|
|
return pkcs1_15.new(self.impl).sign(h) # type: ignore
|
2019-08-14 09:17:08 +08:00
|
|
|
|
|
|
|
def get_public_key(self) -> PublicKey:
|
|
|
|
return RSAPublicKey(self.impl.publickey())
|
|
|
|
|
|
|
|
|
2019-08-14 11:23:07 +08:00
|
|
|
def create_new_key_pair(bits: int = 2048, e: int = 65537) -> KeyPair:
|
2019-08-14 09:17:08 +08:00
|
|
|
"""
|
|
|
|
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 = RSAPrivateKey.new(bits, e)
|
|
|
|
public_key = private_key.get_public_key()
|
2019-08-14 11:23:07 +08:00
|
|
|
return KeyPair(private_key, public_key)
|