ed25519.py 2.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. # This file is dual licensed under the terms of the Apache License, Version
  2. # 2.0, and the BSD License. See the LICENSE file in the root of this repository
  3. # for complete details.
  4. import abc
  5. from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
  6. from cryptography.hazmat.primitives import _serialization
  7. _ED25519_KEY_SIZE = 32
  8. _ED25519_SIG_SIZE = 64
  9. class Ed25519PublicKey(metaclass=abc.ABCMeta):
  10. @classmethod
  11. def from_public_bytes(cls, data: bytes) -> "Ed25519PublicKey":
  12. from cryptography.hazmat.backends.openssl.backend import backend
  13. if not backend.ed25519_supported():
  14. raise UnsupportedAlgorithm(
  15. "ed25519 is not supported by this version of OpenSSL.",
  16. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  17. )
  18. return backend.ed25519_load_public_bytes(data)
  19. @abc.abstractmethod
  20. def public_bytes(
  21. self,
  22. encoding: _serialization.Encoding,
  23. format: _serialization.PublicFormat,
  24. ) -> bytes:
  25. """
  26. The serialized bytes of the public key.
  27. """
  28. @abc.abstractmethod
  29. def verify(self, signature: bytes, data: bytes) -> None:
  30. """
  31. Verify the signature.
  32. """
  33. class Ed25519PrivateKey(metaclass=abc.ABCMeta):
  34. @classmethod
  35. def generate(cls) -> "Ed25519PrivateKey":
  36. from cryptography.hazmat.backends.openssl.backend import backend
  37. if not backend.ed25519_supported():
  38. raise UnsupportedAlgorithm(
  39. "ed25519 is not supported by this version of OpenSSL.",
  40. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  41. )
  42. return backend.ed25519_generate_key()
  43. @classmethod
  44. def from_private_bytes(cls, data: bytes) -> "Ed25519PrivateKey":
  45. from cryptography.hazmat.backends.openssl.backend import backend
  46. if not backend.ed25519_supported():
  47. raise UnsupportedAlgorithm(
  48. "ed25519 is not supported by this version of OpenSSL.",
  49. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  50. )
  51. return backend.ed25519_load_private_bytes(data)
  52. @abc.abstractmethod
  53. def public_key(self) -> Ed25519PublicKey:
  54. """
  55. The Ed25519PublicKey derived from the private key.
  56. """
  57. @abc.abstractmethod
  58. def private_bytes(
  59. self,
  60. encoding: _serialization.Encoding,
  61. format: _serialization.PrivateFormat,
  62. encryption_algorithm: _serialization.KeySerializationEncryption,
  63. ) -> bytes:
  64. """
  65. The serialized bytes of the private key.
  66. """
  67. @abc.abstractmethod
  68. def sign(self, data: bytes) -> bytes:
  69. """
  70. Signs the data.
  71. """