ed25519.py 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  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. from __future__ import absolute_import, division, print_function
  5. import abc
  6. import six
  7. from cryptography.exceptions import UnsupportedAlgorithm, _Reasons
  8. _ED25519_KEY_SIZE = 32
  9. _ED25519_SIG_SIZE = 64
  10. @six.add_metaclass(abc.ABCMeta)
  11. class Ed25519PublicKey(object):
  12. @classmethod
  13. def from_public_bytes(cls, data):
  14. from cryptography.hazmat.backends.openssl.backend import backend
  15. if not backend.ed25519_supported():
  16. raise UnsupportedAlgorithm(
  17. "ed25519 is not supported by this version of OpenSSL.",
  18. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  19. )
  20. return backend.ed25519_load_public_bytes(data)
  21. @abc.abstractmethod
  22. def public_bytes(self, encoding, format):
  23. """
  24. The serialized bytes of the public key.
  25. """
  26. @abc.abstractmethod
  27. def verify(self, signature, data):
  28. """
  29. Verify the signature.
  30. """
  31. @six.add_metaclass(abc.ABCMeta)
  32. class Ed25519PrivateKey(object):
  33. @classmethod
  34. def generate(cls):
  35. from cryptography.hazmat.backends.openssl.backend import backend
  36. if not backend.ed25519_supported():
  37. raise UnsupportedAlgorithm(
  38. "ed25519 is not supported by this version of OpenSSL.",
  39. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  40. )
  41. return backend.ed25519_generate_key()
  42. @classmethod
  43. def from_private_bytes(cls, data):
  44. from cryptography.hazmat.backends.openssl.backend import backend
  45. if not backend.ed25519_supported():
  46. raise UnsupportedAlgorithm(
  47. "ed25519 is not supported by this version of OpenSSL.",
  48. _Reasons.UNSUPPORTED_PUBLIC_KEY_ALGORITHM,
  49. )
  50. return backend.ed25519_load_private_bytes(data)
  51. @abc.abstractmethod
  52. def public_key(self):
  53. """
  54. The Ed25519PublicKey derived from the private key.
  55. """
  56. @abc.abstractmethod
  57. def private_bytes(self, encoding, format, encryption_algorithm):
  58. """
  59. The serialized bytes of the private key.
  60. """
  61. @abc.abstractmethod
  62. def sign(self, data):
  63. """
  64. Signs the data.
  65. """