dsa.py 7.7 KB

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