您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 

337 行
11 KiB

  1. """
  2. Class for performing Elliptic-curve Diffie-Hellman (ECDH) operations.
  3. """
  4. from .util import number_to_string
  5. from .ellipticcurve import INFINITY
  6. from .keys import SigningKey, VerifyingKey
  7. __all__ = [
  8. "ECDH",
  9. "NoKeyError",
  10. "NoCurveError",
  11. "InvalidCurveError",
  12. "InvalidSharedSecretError",
  13. ]
  14. class NoKeyError(Exception):
  15. """ECDH. Key not found but it is needed for operation."""
  16. pass
  17. class NoCurveError(Exception):
  18. """ECDH. Curve not set but it is needed for operation."""
  19. pass
  20. class InvalidCurveError(Exception):
  21. """
  22. ECDH. Raised in case the public and private keys use different curves.
  23. """
  24. pass
  25. class InvalidSharedSecretError(Exception):
  26. """ECDH. Raised in case the shared secret we obtained is an INFINITY."""
  27. pass
  28. class ECDH(object):
  29. """
  30. Elliptic-curve Diffie-Hellman (ECDH). A key agreement protocol.
  31. Allows two parties, each having an elliptic-curve public-private key
  32. pair, to establish a shared secret over an insecure channel
  33. """
  34. def __init__(self, curve=None, private_key=None, public_key=None):
  35. """
  36. ECDH init.
  37. Call can be initialised without parameters, then the first operation
  38. (loading either key) will set the used curve.
  39. All parameters must be ultimately set before shared secret
  40. calculation will be allowed.
  41. :param curve: curve for operations
  42. :type curve: Curve
  43. :param private_key: `my` private key for ECDH
  44. :type private_key: SigningKey
  45. :param public_key: `their` public key for ECDH
  46. :type public_key: VerifyingKey
  47. """
  48. self.curve = curve
  49. self.private_key = None
  50. self.public_key = None
  51. if private_key:
  52. self.load_private_key(private_key)
  53. if public_key:
  54. self.load_received_public_key(public_key)
  55. def _get_shared_secret(self, remote_public_key):
  56. if not self.private_key:
  57. raise NoKeyError(
  58. "Private key needs to be set to create shared secret"
  59. )
  60. if not self.public_key:
  61. raise NoKeyError(
  62. "Public key needs to be set to create shared secret"
  63. )
  64. if not (
  65. self.private_key.curve == self.curve == remote_public_key.curve
  66. ):
  67. raise InvalidCurveError(
  68. "Curves for public key and private key is not equal."
  69. )
  70. # shared secret = PUBKEYtheirs * PRIVATEKEYours
  71. result = (
  72. remote_public_key.pubkey.point
  73. * self.private_key.privkey.secret_multiplier
  74. )
  75. if result == INFINITY:
  76. raise InvalidSharedSecretError("Invalid shared secret (INFINITY).")
  77. return result.x()
  78. def set_curve(self, key_curve):
  79. """
  80. Set the working curve for ecdh operations.
  81. :param key_curve: curve from `curves` module
  82. :type key_curve: Curve
  83. """
  84. self.curve = key_curve
  85. def generate_private_key(self):
  86. """
  87. Generate local private key for ecdh operation with curve that was set.
  88. :raises NoCurveError: Curve must be set before key generation.
  89. :return: public (verifying) key from this private key.
  90. :rtype: VerifyingKey
  91. """
  92. if not self.curve:
  93. raise NoCurveError("Curve must be set prior to key generation.")
  94. return self.load_private_key(SigningKey.generate(curve=self.curve))
  95. def load_private_key(self, private_key):
  96. """
  97. Load private key from SigningKey (keys.py) object.
  98. Needs to have the same curve as was set with set_curve method.
  99. If curve is not set - it sets from this SigningKey
  100. :param private_key: Initialised SigningKey class
  101. :type private_key: SigningKey
  102. :raises InvalidCurveError: private_key curve not the same as self.curve
  103. :return: public (verifying) key from this private key.
  104. :rtype: VerifyingKey
  105. """
  106. if not self.curve:
  107. self.curve = private_key.curve
  108. if self.curve != private_key.curve:
  109. raise InvalidCurveError("Curve mismatch.")
  110. self.private_key = private_key
  111. return self.private_key.get_verifying_key()
  112. def load_private_key_bytes(self, private_key):
  113. """
  114. Load private key from byte string.
  115. Uses current curve and checks if the provided key matches
  116. the curve of ECDH key agreement.
  117. Key loads via from_string method of SigningKey class
  118. :param private_key: private key in bytes string format
  119. :type private_key: :term:`bytes-like object`
  120. :raises NoCurveError: Curve must be set before loading.
  121. :return: public (verifying) key from this private key.
  122. :rtype: VerifyingKey
  123. """
  124. if not self.curve:
  125. raise NoCurveError("Curve must be set prior to key load.")
  126. return self.load_private_key(
  127. SigningKey.from_string(private_key, curve=self.curve)
  128. )
  129. def load_private_key_der(self, private_key_der):
  130. """
  131. Load private key from DER byte string.
  132. Compares the curve of the DER-encoded key with the ECDH set curve,
  133. uses the former if unset.
  134. Note, the only DER format supported is the RFC5915
  135. Look at keys.py:SigningKey.from_der()
  136. :param private_key_der: string with the DER encoding of private ECDSA
  137. key
  138. :type private_key_der: string
  139. :raises InvalidCurveError: private_key curve not the same as self.curve
  140. :return: public (verifying) key from this private key.
  141. :rtype: VerifyingKey
  142. """
  143. return self.load_private_key(SigningKey.from_der(private_key_der))
  144. def load_private_key_pem(self, private_key_pem):
  145. """
  146. Load private key from PEM string.
  147. Compares the curve of the DER-encoded key with the ECDH set curve,
  148. uses the former if unset.
  149. Note, the only PEM format supported is the RFC5915
  150. Look at keys.py:SigningKey.from_pem()
  151. it needs to have `EC PRIVATE KEY` section
  152. :param private_key_pem: string with PEM-encoded private ECDSA key
  153. :type private_key_pem: string
  154. :raises InvalidCurveError: private_key curve not the same as self.curve
  155. :return: public (verifying) key from this private key.
  156. :rtype: VerifyingKey
  157. """
  158. return self.load_private_key(SigningKey.from_pem(private_key_pem))
  159. def get_public_key(self):
  160. """
  161. Provides a public key that matches the local private key.
  162. Needs to be sent to the remote party.
  163. :return: public (verifying) key from local private key.
  164. :rtype: VerifyingKey
  165. """
  166. return self.private_key.get_verifying_key()
  167. def load_received_public_key(self, public_key):
  168. """
  169. Load public key from VerifyingKey (keys.py) object.
  170. Needs to have the same curve as set as current for ecdh operation.
  171. If curve is not set - it sets it from VerifyingKey.
  172. :param public_key: Initialised VerifyingKey class
  173. :type public_key: VerifyingKey
  174. :raises InvalidCurveError: public_key curve not the same as self.curve
  175. """
  176. if not self.curve:
  177. self.curve = public_key.curve
  178. if self.curve != public_key.curve:
  179. raise InvalidCurveError("Curve mismatch.")
  180. self.public_key = public_key
  181. def load_received_public_key_bytes(
  182. self, public_key_str, valid_encodings=None
  183. ):
  184. """
  185. Load public key from byte string.
  186. Uses current curve and checks if key length corresponds to
  187. the current curve.
  188. Key loads via from_string method of VerifyingKey class
  189. :param public_key_str: public key in bytes string format
  190. :type public_key_str: :term:`bytes-like object`
  191. :param valid_encodings: list of acceptable point encoding formats,
  192. supported ones are: :term:`uncompressed`, :term:`compressed`,
  193. :term:`hybrid`, and :term:`raw encoding` (specified with ``raw``
  194. name). All formats by default (specified with ``None``).
  195. :type valid_encodings: :term:`set-like object`
  196. """
  197. return self.load_received_public_key(
  198. VerifyingKey.from_string(
  199. public_key_str, self.curve, valid_encodings
  200. )
  201. )
  202. def load_received_public_key_der(self, public_key_der):
  203. """
  204. Load public key from DER byte string.
  205. Compares the curve of the DER-encoded key with the ECDH set curve,
  206. uses the former if unset.
  207. Note, the only DER format supported is the RFC5912
  208. Look at keys.py:VerifyingKey.from_der()
  209. :param public_key_der: string with the DER encoding of public ECDSA key
  210. :type public_key_der: string
  211. :raises InvalidCurveError: public_key curve not the same as self.curve
  212. """
  213. return self.load_received_public_key(
  214. VerifyingKey.from_der(public_key_der)
  215. )
  216. def load_received_public_key_pem(self, public_key_pem):
  217. """
  218. Load public key from PEM string.
  219. Compares the curve of the PEM-encoded key with the ECDH set curve,
  220. uses the former if unset.
  221. Note, the only PEM format supported is the RFC5912
  222. Look at keys.py:VerifyingKey.from_pem()
  223. :param public_key_pem: string with PEM-encoded public ECDSA key
  224. :type public_key_pem: string
  225. :raises InvalidCurveError: public_key curve not the same as self.curve
  226. """
  227. return self.load_received_public_key(
  228. VerifyingKey.from_pem(public_key_pem)
  229. )
  230. def generate_sharedsecret_bytes(self):
  231. """
  232. Generate shared secret from local private key and remote public key.
  233. The objects needs to have both private key and received public key
  234. before generation is allowed.
  235. :raises InvalidCurveError: public_key curve not the same as self.curve
  236. :raises NoKeyError: public_key or private_key is not set
  237. :return: shared secret
  238. :rtype: bytes
  239. """
  240. return number_to_string(
  241. self.generate_sharedsecret(), self.private_key.curve.curve.p()
  242. )
  243. def generate_sharedsecret(self):
  244. """
  245. Generate shared secret from local private key and remote public key.
  246. The objects needs to have both private key and received public key
  247. before generation is allowed.
  248. It's the same for local and remote party,
  249. shared secret(local private key, remote public key) ==
  250. shared secret(local public key, remote private key)
  251. :raises InvalidCurveError: public_key curve not the same as self.curve
  252. :raises NoKeyError: public_key or private_key is not set
  253. :return: shared secret
  254. :rtype: int
  255. """
  256. return self._get_shared_secret(self.public_key)