|
| 1 | +import sys |
| 2 | + |
| 3 | +from cryptography.exceptions import InvalidSignature |
| 4 | +from cryptography.hazmat.primitives.asymmetric import ed448 |
| 5 | +from cryptography.hazmat.primitives.asymmetric import ed25519 |
| 6 | + |
| 7 | +from ..exception import BadSignature |
| 8 | +from ..exception import Unsupported |
| 9 | +from . import Signer |
| 10 | + |
| 11 | + |
| 12 | +class EDDSASigner(Signer): |
| 13 | + def sign(self, msg, key): |
| 14 | + """ |
| 15 | + Create a signature over a message as defined in RFC7515 using an |
| 16 | + Octet Key Pair key |
| 17 | +
|
| 18 | + :param msg: The message |
| 19 | + :param key: An Ed25519PrivateKey or Ed448PrivateKey instance |
| 20 | + :return: |
| 21 | + """ |
| 22 | + |
| 23 | + if not isinstance(key, (ed25519.Ed25519PrivateKey, ed448.Ed448PrivateKey)): |
| 24 | + raise TypeError( |
| 25 | + "The private key must be an instance of Ed25519PrivateKey or Ed448PrivateKey" |
| 26 | + ) |
| 27 | + |
| 28 | + return key.sign(msg) |
| 29 | + |
| 30 | + def verify(self, msg, sig, key): |
| 31 | + """ |
| 32 | + Verify a message signature |
| 33 | +
|
| 34 | + :param msg: The message |
| 35 | + :param sig: A signature |
| 36 | + :param key: A Ed25519PublicKey or Ed448PublicKey to use for the verification. |
| 37 | + :raises: BadSignature if the signature can't be verified. |
| 38 | + :return: True |
| 39 | + """ |
| 40 | + if not isinstance(key, (ed25519.Ed25519PublicKey, ed448.Ed448PublicKey)): |
| 41 | + raise TypeError( |
| 42 | + "The public key must be an instance of Ed25519PublicKey or Ed448PublicKey" |
| 43 | + ) |
| 44 | + |
| 45 | + try: |
| 46 | + key.verify(sig, msg) |
| 47 | + except InvalidSignature as err: |
| 48 | + raise BadSignature(err) |
| 49 | + else: |
| 50 | + return True |
0 commit comments