dsa.py 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297
  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. import typing
  6. from cryptography.hazmat.backends import _get_backend
  7. from cryptography.hazmat.backends.interfaces import Backend
  8. from cryptography.hazmat.primitives import _serialization, hashes
  9. from cryptography.hazmat.primitives.asymmetric import (
  10. AsymmetricSignatureContext,
  11. AsymmetricVerificationContext,
  12. utils as asym_utils,
  13. )
  14. class DSAParameters(metaclass=abc.ABCMeta):
  15. @abc.abstractmethod
  16. def generate_private_key(self) -> "DSAPrivateKey":
  17. """
  18. Generates and returns a DSAPrivateKey.
  19. """
  20. @abc.abstractmethod
  21. def parameter_numbers(self) -> "DSAParameterNumbers":
  22. """
  23. Returns a DSAParameterNumbers.
  24. """
  25. DSAParametersWithNumbers = DSAParameters
  26. class DSAPrivateKey(metaclass=abc.ABCMeta):
  27. @abc.abstractproperty
  28. def key_size(self) -> int:
  29. """
  30. The bit length of the prime modulus.
  31. """
  32. @abc.abstractmethod
  33. def public_key(self) -> "DSAPublicKey":
  34. """
  35. The DSAPublicKey associated with this private key.
  36. """
  37. @abc.abstractmethod
  38. def parameters(self) -> DSAParameters:
  39. """
  40. The DSAParameters object associated with this private key.
  41. """
  42. @abc.abstractmethod
  43. def signer(
  44. self,
  45. signature_algorithm: hashes.HashAlgorithm,
  46. ) -> AsymmetricSignatureContext:
  47. """
  48. Returns an AsymmetricSignatureContext used for signing data.
  49. """
  50. @abc.abstractmethod
  51. def sign(
  52. self,
  53. data: bytes,
  54. algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],
  55. ) -> bytes:
  56. """
  57. Signs the data
  58. """
  59. @abc.abstractmethod
  60. def private_numbers(self) -> "DSAPrivateNumbers":
  61. """
  62. Returns a DSAPrivateNumbers.
  63. """
  64. @abc.abstractmethod
  65. def private_bytes(
  66. self,
  67. encoding: _serialization.Encoding,
  68. format: _serialization.PrivateFormat,
  69. encryption_algorithm: _serialization.KeySerializationEncryption,
  70. ) -> bytes:
  71. """
  72. Returns the key serialized as bytes.
  73. """
  74. DSAPrivateKeyWithSerialization = DSAPrivateKey
  75. class DSAPublicKey(metaclass=abc.ABCMeta):
  76. @abc.abstractproperty
  77. def key_size(self) -> int:
  78. """
  79. The bit length of the prime modulus.
  80. """
  81. @abc.abstractmethod
  82. def parameters(self) -> DSAParameters:
  83. """
  84. The DSAParameters object associated with this public key.
  85. """
  86. @abc.abstractmethod
  87. def verifier(
  88. self,
  89. signature: bytes,
  90. signature_algorithm: hashes.HashAlgorithm,
  91. ) -> AsymmetricVerificationContext:
  92. """
  93. Returns an AsymmetricVerificationContext used for signing data.
  94. """
  95. @abc.abstractmethod
  96. def public_numbers(self) -> "DSAPublicNumbers":
  97. """
  98. Returns a DSAPublicNumbers.
  99. """
  100. @abc.abstractmethod
  101. def public_bytes(
  102. self,
  103. encoding: _serialization.Encoding,
  104. format: _serialization.PublicFormat,
  105. ) -> bytes:
  106. """
  107. Returns the key serialized as bytes.
  108. """
  109. @abc.abstractmethod
  110. def verify(
  111. self,
  112. signature: bytes,
  113. data: bytes,
  114. algorithm: typing.Union[asym_utils.Prehashed, hashes.HashAlgorithm],
  115. ) -> None:
  116. """
  117. Verifies the signature of the data.
  118. """
  119. DSAPublicKeyWithSerialization = DSAPublicKey
  120. class DSAParameterNumbers(object):
  121. def __init__(self, p: int, q: int, g: int):
  122. if (
  123. not isinstance(p, int)
  124. or not isinstance(q, int)
  125. or not isinstance(g, int)
  126. ):
  127. raise TypeError(
  128. "DSAParameterNumbers p, q, and g arguments must be integers."
  129. )
  130. self._p = p
  131. self._q = q
  132. self._g = g
  133. p = property(lambda self: self._p)
  134. q = property(lambda self: self._q)
  135. g = property(lambda self: self._g)
  136. def parameters(
  137. self, backend: typing.Optional[Backend] = None
  138. ) -> DSAParameters:
  139. backend = _get_backend(backend)
  140. return backend.load_dsa_parameter_numbers(self)
  141. def __eq__(self, other):
  142. if not isinstance(other, DSAParameterNumbers):
  143. return NotImplemented
  144. return self.p == other.p and self.q == other.q and self.g == other.g
  145. def __ne__(self, other):
  146. return not self == other
  147. def __repr__(self):
  148. return (
  149. "<DSAParameterNumbers(p={self.p}, q={self.q}, "
  150. "g={self.g})>".format(self=self)
  151. )
  152. class DSAPublicNumbers(object):
  153. def __init__(self, y: int, parameter_numbers: DSAParameterNumbers):
  154. if not isinstance(y, int):
  155. raise TypeError("DSAPublicNumbers y argument must be an integer.")
  156. if not isinstance(parameter_numbers, DSAParameterNumbers):
  157. raise TypeError(
  158. "parameter_numbers must be a DSAParameterNumbers instance."
  159. )
  160. self._y = y
  161. self._parameter_numbers = parameter_numbers
  162. y = property(lambda self: self._y)
  163. parameter_numbers = property(lambda self: self._parameter_numbers)
  164. def public_key(
  165. self, backend: typing.Optional[Backend] = None
  166. ) -> DSAPublicKey:
  167. backend = _get_backend(backend)
  168. return backend.load_dsa_public_numbers(self)
  169. def __eq__(self, other):
  170. if not isinstance(other, DSAPublicNumbers):
  171. return NotImplemented
  172. return (
  173. self.y == other.y
  174. and self.parameter_numbers == other.parameter_numbers
  175. )
  176. def __ne__(self, other):
  177. return not self == other
  178. def __repr__(self):
  179. return (
  180. "<DSAPublicNumbers(y={self.y}, "
  181. "parameter_numbers={self.parameter_numbers})>".format(self=self)
  182. )
  183. class DSAPrivateNumbers(object):
  184. def __init__(self, x: int, public_numbers: DSAPublicNumbers):
  185. if not isinstance(x, int):
  186. raise TypeError("DSAPrivateNumbers x argument must be an integer.")
  187. if not isinstance(public_numbers, DSAPublicNumbers):
  188. raise TypeError(
  189. "public_numbers must be a DSAPublicNumbers instance."
  190. )
  191. self._public_numbers = public_numbers
  192. self._x = x
  193. x = property(lambda self: self._x)
  194. public_numbers = property(lambda self: self._public_numbers)
  195. def private_key(
  196. self, backend: typing.Optional[Backend] = None
  197. ) -> DSAPrivateKey:
  198. backend = _get_backend(backend)
  199. return backend.load_dsa_private_numbers(self)
  200. def __eq__(self, other):
  201. if not isinstance(other, DSAPrivateNumbers):
  202. return NotImplemented
  203. return (
  204. self.x == other.x and self.public_numbers == other.public_numbers
  205. )
  206. def __ne__(self, other):
  207. return not self == other
  208. def generate_parameters(
  209. key_size: int, backend: typing.Optional[Backend] = None
  210. ) -> DSAParameters:
  211. backend = _get_backend(backend)
  212. return backend.generate_dsa_parameters(key_size)
  213. def generate_private_key(
  214. key_size: int, backend: typing.Optional[Backend] = None
  215. ) -> DSAPrivateKey:
  216. backend = _get_backend(backend)
  217. return backend.generate_dsa_private_key_and_parameters(key_size)
  218. def _check_dsa_parameters(parameters: DSAParameterNumbers) -> None:
  219. if parameters.p.bit_length() not in [1024, 2048, 3072, 4096]:
  220. raise ValueError(
  221. "p must be exactly 1024, 2048, 3072, or 4096 bits long"
  222. )
  223. if parameters.q.bit_length() not in [160, 224, 256]:
  224. raise ValueError("q must be exactly 160, 224, or 256 bits long")
  225. if not (1 < parameters.g < parameters.p):
  226. raise ValueError("g, p don't satisfy 1 < g < p.")
  227. def _check_dsa_private_numbers(numbers: DSAPrivateNumbers) -> None:
  228. parameters = numbers.public_numbers.parameter_numbers
  229. _check_dsa_parameters(parameters)
  230. if numbers.x <= 0 or numbers.x >= parameters.q:
  231. raise ValueError("x must be > 0 and < q.")
  232. if numbers.public_numbers.y != pow(parameters.g, numbers.x, parameters.p):
  233. raise ValueError("y must be equal to (g ** x % p).")