You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

1632 lines
64 KiB

  1. """
  2. Primary classes for performing signing and verification operations.
  3. """
  4. import binascii
  5. from hashlib import sha1
  6. import os
  7. from six import PY2
  8. from . import ecdsa, eddsa
  9. from . import der, ssh
  10. from . import rfc6979
  11. from . import ellipticcurve
  12. from .curves import NIST192p, Curve, Ed25519, Ed448
  13. from .ecdsa import RSZeroError
  14. from .util import string_to_number, number_to_string, randrange
  15. from .util import sigencode_string, sigdecode_string, bit_length
  16. from .util import (
  17. oid_ecPublicKey,
  18. encoded_oid_ecPublicKey,
  19. oid_ecDH,
  20. oid_ecMQV,
  21. MalformedSignature,
  22. )
  23. from ._compat import normalise_bytes
  24. from .errors import MalformedPointError
  25. from .ellipticcurve import PointJacobi, CurveEdTw
  26. __all__ = [
  27. "BadSignatureError",
  28. "BadDigestError",
  29. "VerifyingKey",
  30. "SigningKey",
  31. "MalformedPointError",
  32. ]
  33. class BadSignatureError(Exception):
  34. """
  35. Raised when verification of signature failed.
  36. Will be raised irrespective of reason of the failure:
  37. * the calculated or provided hash does not match the signature
  38. * the signature does not match the curve/public key
  39. * the encoding of the signature is malformed
  40. * the size of the signature does not match the curve of the VerifyingKey
  41. """
  42. pass
  43. class BadDigestError(Exception):
  44. """Raised in case the selected hash is too large for the curve."""
  45. pass
  46. def _truncate_and_convert_digest(digest, curve, allow_truncate):
  47. """Truncates and converts digest to an integer."""
  48. if not allow_truncate:
  49. if len(digest) > curve.baselen:
  50. raise BadDigestError(
  51. "this curve ({0}) is too short "
  52. "for the length of your digest ({1})".format(
  53. curve.name, 8 * len(digest)
  54. )
  55. )
  56. else:
  57. digest = digest[: curve.baselen]
  58. number = string_to_number(digest)
  59. if allow_truncate:
  60. max_length = bit_length(curve.order)
  61. # we don't use bit_length(number) as that truncates leading zeros
  62. length = len(digest) * 8
  63. # See NIST FIPS 186-4:
  64. #
  65. # When the length of the output of the hash function is greater
  66. # than N (i.e., the bit length of q), then the leftmost N bits of
  67. # the hash function output block shall be used in any calculation
  68. # using the hash function output during the generation or
  69. # verification of a digital signature.
  70. #
  71. # as such, we need to shift-out the low-order bits:
  72. number >>= max(0, length - max_length)
  73. return number
  74. class VerifyingKey(object):
  75. """
  76. Class for handling keys that can verify signatures (public keys).
  77. :ivar `~ecdsa.curves.Curve` ~.curve: The Curve over which all the
  78. cryptographic operations will take place
  79. :ivar default_hashfunc: the function that will be used for hashing the
  80. data. Should implement the same API as hashlib.sha1
  81. :vartype default_hashfunc: callable
  82. :ivar pubkey: the actual public key
  83. :vartype pubkey: ~ecdsa.ecdsa.Public_key
  84. """
  85. def __init__(self, _error__please_use_generate=None):
  86. """Unsupported, please use one of the classmethods to initialise."""
  87. if not _error__please_use_generate:
  88. raise TypeError(
  89. "Please use VerifyingKey.generate() to construct me"
  90. )
  91. self.curve = None
  92. self.default_hashfunc = None
  93. self.pubkey = None
  94. def __repr__(self):
  95. pub_key = self.to_string("compressed")
  96. if self.default_hashfunc:
  97. hash_name = self.default_hashfunc().name
  98. else:
  99. hash_name = "None"
  100. return "VerifyingKey.from_string({0!r}, {1!r}, {2})".format(
  101. pub_key, self.curve, hash_name
  102. )
  103. def __eq__(self, other):
  104. """Return True if the points are identical, False otherwise."""
  105. if isinstance(other, VerifyingKey):
  106. return self.curve == other.curve and self.pubkey == other.pubkey
  107. return NotImplemented
  108. def __ne__(self, other):
  109. """Return False if the points are identical, True otherwise."""
  110. return not self == other
  111. @classmethod
  112. def from_public_point(
  113. cls, point, curve=NIST192p, hashfunc=sha1, validate_point=True
  114. ):
  115. """
  116. Initialise the object from a Point object.
  117. This is a low-level method, generally you will not want to use it.
  118. :param point: The point to wrap around, the actual public key
  119. :type point: ~ecdsa.ellipticcurve.AbstractPoint
  120. :param curve: The curve on which the point needs to reside, defaults
  121. to NIST192p
  122. :type curve: ~ecdsa.curves.Curve
  123. :param hashfunc: The default hash function that will be used for
  124. verification, needs to implement the same interface
  125. as :py:class:`hashlib.sha1`
  126. :type hashfunc: callable
  127. :type bool validate_point: whether to check if the point lays on curve
  128. should always be used if the public point is not a result
  129. of our own calculation
  130. :raises MalformedPointError: if the public point does not lay on the
  131. curve
  132. :return: Initialised VerifyingKey object
  133. :rtype: VerifyingKey
  134. """
  135. self = cls(_error__please_use_generate=True)
  136. if isinstance(curve.curve, CurveEdTw):
  137. raise ValueError("Method incompatible with Edwards curves")
  138. if not isinstance(point, ellipticcurve.PointJacobi):
  139. point = ellipticcurve.PointJacobi.from_affine(point)
  140. self.curve = curve
  141. self.default_hashfunc = hashfunc
  142. try:
  143. self.pubkey = ecdsa.Public_key(
  144. curve.generator, point, validate_point
  145. )
  146. except ecdsa.InvalidPointError:
  147. raise MalformedPointError("Point does not lay on the curve")
  148. self.pubkey.order = curve.order
  149. return self
  150. def precompute(self, lazy=False):
  151. """
  152. Precompute multiplication tables for faster signature verification.
  153. Calling this method will cause the library to precompute the
  154. scalar multiplication tables, used in signature verification.
  155. While it's an expensive operation (comparable to performing
  156. as many signatures as the bit size of the curve, i.e. 256 for NIST256p)
  157. it speeds up verification 2 times. You should call this method
  158. if you expect to verify hundreds of signatures (or more) using the same
  159. VerifyingKey object.
  160. Note: You should call this method only once, this method generates a
  161. new precomputation table every time it's called.
  162. :param bool lazy: whether to calculate the precomputation table now
  163. (if set to False) or if it should be delayed to the time of first
  164. use (when set to True)
  165. """
  166. if isinstance(self.curve.curve, CurveEdTw):
  167. pt = self.pubkey.point
  168. self.pubkey.point = ellipticcurve.PointEdwards(
  169. pt.curve(),
  170. pt.x(),
  171. pt.y(),
  172. 1,
  173. pt.x() * pt.y(),
  174. self.curve.order,
  175. generator=True,
  176. )
  177. else:
  178. self.pubkey.point = ellipticcurve.PointJacobi.from_affine(
  179. self.pubkey.point, True
  180. )
  181. # as precomputation in now delayed to the time of first use of the
  182. # point and we were asked specifically to precompute now, make
  183. # sure the precomputation is performed now to preserve the behaviour
  184. if not lazy:
  185. self.pubkey.point * 2
  186. @classmethod
  187. def from_string(
  188. cls,
  189. string,
  190. curve=NIST192p,
  191. hashfunc=sha1,
  192. validate_point=True,
  193. valid_encodings=None,
  194. ):
  195. """
  196. Initialise the object from byte encoding of public key.
  197. The method does accept and automatically detect the type of point
  198. encoding used. It supports the :term:`raw encoding`,
  199. :term:`uncompressed`, :term:`compressed`, and :term:`hybrid` encodings.
  200. It also works with the native encoding of Ed25519 and Ed448 public
  201. keys (technically those are compressed, but encoded differently than
  202. in other signature systems).
  203. Note, while the method is named "from_string" it's a misnomer from
  204. Python 2 days when there were no binary strings. In Python 3 the
  205. input needs to be a bytes-like object.
  206. :param string: single point encoding of the public key
  207. :type string: :term:`bytes-like object`
  208. :param curve: the curve on which the public key is expected to lay
  209. :type curve: ~ecdsa.curves.Curve
  210. :param hashfunc: The default hash function that will be used for
  211. verification, needs to implement the same interface as
  212. hashlib.sha1. Ignored for EdDSA.
  213. :type hashfunc: callable
  214. :param validate_point: whether to verify that the point lays on the
  215. provided curve or not, defaults to True. Ignored for EdDSA.
  216. :type validate_point: bool
  217. :param valid_encodings: list of acceptable point encoding formats,
  218. supported ones are: :term:`uncompressed`, :term:`compressed`,
  219. :term:`hybrid`, and :term:`raw encoding` (specified with ``raw``
  220. name). All formats by default (specified with ``None``).
  221. Ignored for EdDSA.
  222. :type valid_encodings: :term:`set-like object`
  223. :raises MalformedPointError: if the public point does not lay on the
  224. curve or the encoding is invalid
  225. :return: Initialised VerifyingKey object
  226. :rtype: VerifyingKey
  227. """
  228. if isinstance(curve.curve, CurveEdTw):
  229. self = cls(_error__please_use_generate=True)
  230. self.curve = curve
  231. self.default_hashfunc = None # ignored for EdDSA
  232. try:
  233. self.pubkey = eddsa.PublicKey(curve.generator, string)
  234. except ValueError:
  235. raise MalformedPointError("Malformed point for the curve")
  236. return self
  237. point = PointJacobi.from_bytes(
  238. curve.curve,
  239. string,
  240. validate_encoding=validate_point,
  241. valid_encodings=valid_encodings,
  242. )
  243. return cls.from_public_point(point, curve, hashfunc, validate_point)
  244. @classmethod
  245. def from_pem(
  246. cls,
  247. string,
  248. hashfunc=sha1,
  249. valid_encodings=None,
  250. valid_curve_encodings=None,
  251. ):
  252. """
  253. Initialise from public key stored in :term:`PEM` format.
  254. The PEM header of the key should be ``BEGIN PUBLIC KEY``.
  255. See the :func:`~VerifyingKey.from_der()` method for details of the
  256. format supported.
  257. Note: only a single PEM object decoding is supported in provided
  258. string.
  259. :param string: text with PEM-encoded public ECDSA key
  260. :type string: str
  261. :param valid_encodings: list of allowed point encodings.
  262. By default :term:`uncompressed`, :term:`compressed`, and
  263. :term:`hybrid`. To read malformed files, include
  264. :term:`raw encoding` with ``raw`` in the list.
  265. :type valid_encodings: :term:`set-like object`
  266. :param valid_curve_encodings: list of allowed encoding formats
  267. for curve parameters. By default (``None``) all are supported:
  268. ``named_curve`` and ``explicit``.
  269. :type valid_curve_encodings: :term:`set-like object`
  270. :return: Initialised VerifyingKey object
  271. :rtype: VerifyingKey
  272. """
  273. return cls.from_der(
  274. der.unpem(string),
  275. hashfunc=hashfunc,
  276. valid_encodings=valid_encodings,
  277. valid_curve_encodings=valid_curve_encodings,
  278. )
  279. @classmethod
  280. def from_der(
  281. cls,
  282. string,
  283. hashfunc=sha1,
  284. valid_encodings=None,
  285. valid_curve_encodings=None,
  286. ):
  287. """
  288. Initialise the key stored in :term:`DER` format.
  289. The expected format of the key is the SubjectPublicKeyInfo structure
  290. from RFC5912 (for RSA keys, it's known as the PKCS#1 format)::
  291. SubjectPublicKeyInfo {PUBLIC-KEY: IOSet} ::= SEQUENCE {
  292. algorithm AlgorithmIdentifier {PUBLIC-KEY, {IOSet}},
  293. subjectPublicKey BIT STRING
  294. }
  295. Note: only public EC keys are supported by this method. The
  296. SubjectPublicKeyInfo.algorithm.algorithm field must specify
  297. id-ecPublicKey (see RFC3279).
  298. Only the named curve encoding is supported, thus the
  299. SubjectPublicKeyInfo.algorithm.parameters field needs to be an
  300. object identifier. A sequence in that field indicates an explicit
  301. parameter curve encoding, this format is not supported. A NULL object
  302. in that field indicates an "implicitlyCA" encoding, where the curve
  303. parameters come from CA certificate, those, again, are not supported.
  304. :param string: binary string with the DER encoding of public ECDSA key
  305. :type string: bytes-like object
  306. :param valid_encodings: list of allowed point encodings.
  307. By default :term:`uncompressed`, :term:`compressed`, and
  308. :term:`hybrid`. To read malformed files, include
  309. :term:`raw encoding` with ``raw`` in the list.
  310. :type valid_encodings: :term:`set-like object`
  311. :param valid_curve_encodings: list of allowed encoding formats
  312. for curve parameters. By default (``None``) all are supported:
  313. ``named_curve`` and ``explicit``.
  314. :type valid_curve_encodings: :term:`set-like object`
  315. :return: Initialised VerifyingKey object
  316. :rtype: VerifyingKey
  317. """
  318. if valid_encodings is None:
  319. valid_encodings = set(["uncompressed", "compressed", "hybrid"])
  320. string = normalise_bytes(string)
  321. # [[oid_ecPublicKey,oid_curve], point_str_bitstring]
  322. s1, empty = der.remove_sequence(string)
  323. if empty != b"":
  324. raise der.UnexpectedDER(
  325. "trailing junk after DER pubkey: %s" % binascii.hexlify(empty)
  326. )
  327. s2, point_str_bitstring = der.remove_sequence(s1)
  328. # s2 = oid_ecPublicKey,oid_curve
  329. oid_pk, rest = der.remove_object(s2)
  330. if oid_pk in (Ed25519.oid, Ed448.oid):
  331. if oid_pk == Ed25519.oid:
  332. curve = Ed25519
  333. else:
  334. assert oid_pk == Ed448.oid
  335. curve = Ed448
  336. point_str, empty = der.remove_bitstring(point_str_bitstring, 0)
  337. if empty:
  338. raise der.UnexpectedDER("trailing junk after public key")
  339. return cls.from_string(point_str, curve, None)
  340. if not oid_pk == oid_ecPublicKey:
  341. raise der.UnexpectedDER(
  342. "Unexpected object identifier in DER "
  343. "encoding: {0!r}".format(oid_pk)
  344. )
  345. curve = Curve.from_der(rest, valid_curve_encodings)
  346. point_str, empty = der.remove_bitstring(point_str_bitstring, 0)
  347. if empty != b"":
  348. raise der.UnexpectedDER(
  349. "trailing junk after pubkey pointstring: %s"
  350. % binascii.hexlify(empty)
  351. )
  352. # raw encoding of point is invalid in DER files
  353. if len(point_str) == curve.verifying_key_length:
  354. raise der.UnexpectedDER("Malformed encoding of public point")
  355. return cls.from_string(
  356. point_str,
  357. curve,
  358. hashfunc=hashfunc,
  359. valid_encodings=valid_encodings,
  360. )
  361. @classmethod
  362. def from_public_key_recovery(
  363. cls,
  364. signature,
  365. data,
  366. curve,
  367. hashfunc=sha1,
  368. sigdecode=sigdecode_string,
  369. allow_truncate=True,
  370. ):
  371. """
  372. Return keys that can be used as verifiers of the provided signature.
  373. Tries to recover the public key that can be used to verify the
  374. signature, usually returns two keys like that.
  375. :param signature: the byte string with the encoded signature
  376. :type signature: bytes-like object
  377. :param data: the data to be hashed for signature verification
  378. :type data: bytes-like object
  379. :param curve: the curve over which the signature was performed
  380. :type curve: ~ecdsa.curves.Curve
  381. :param hashfunc: The default hash function that will be used for
  382. verification, needs to implement the same interface as hashlib.sha1
  383. :type hashfunc: callable
  384. :param sigdecode: Callable to define the way the signature needs to
  385. be decoded to an object, needs to handle `signature` as the
  386. first parameter, the curve order (an int) as the second and return
  387. a tuple with two integers, "r" as the first one and "s" as the
  388. second one. See :func:`ecdsa.util.sigdecode_string` and
  389. :func:`ecdsa.util.sigdecode_der` for examples.
  390. :param bool allow_truncate: if True, the provided hashfunc can generate
  391. values larger than the bit size of the order of the curve, the
  392. extra bits (at the end of the digest) will be truncated.
  393. :type sigdecode: callable
  394. :return: Initialised VerifyingKey objects
  395. :rtype: list of VerifyingKey
  396. """
  397. if isinstance(curve.curve, CurveEdTw):
  398. raise ValueError("Method unsupported for Edwards curves")
  399. data = normalise_bytes(data)
  400. digest = hashfunc(data).digest()
  401. return cls.from_public_key_recovery_with_digest(
  402. signature,
  403. digest,
  404. curve,
  405. hashfunc=hashfunc,
  406. sigdecode=sigdecode,
  407. allow_truncate=allow_truncate,
  408. )
  409. @classmethod
  410. def from_public_key_recovery_with_digest(
  411. cls,
  412. signature,
  413. digest,
  414. curve,
  415. hashfunc=sha1,
  416. sigdecode=sigdecode_string,
  417. allow_truncate=False,
  418. ):
  419. """
  420. Return keys that can be used as verifiers of the provided signature.
  421. Tries to recover the public key that can be used to verify the
  422. signature, usually returns two keys like that.
  423. :param signature: the byte string with the encoded signature
  424. :type signature: bytes-like object
  425. :param digest: the hash value of the message signed by the signature
  426. :type digest: bytes-like object
  427. :param curve: the curve over which the signature was performed
  428. :type curve: ~ecdsa.curves.Curve
  429. :param hashfunc: The default hash function that will be used for
  430. verification, needs to implement the same interface as hashlib.sha1
  431. :type hashfunc: callable
  432. :param sigdecode: Callable to define the way the signature needs to
  433. be decoded to an object, needs to handle `signature` as the
  434. first parameter, the curve order (an int) as the second and return
  435. a tuple with two integers, "r" as the first one and "s" as the
  436. second one. See :func:`ecdsa.util.sigdecode_string` and
  437. :func:`ecdsa.util.sigdecode_der` for examples.
  438. :type sigdecode: callable
  439. :param bool allow_truncate: if True, the provided hashfunc can generate
  440. values larger than the bit size of the order of the curve (and
  441. the length of provided `digest`), the extra bits (at the end of the
  442. digest) will be truncated.
  443. :return: Initialised VerifyingKey object
  444. :rtype: VerifyingKey
  445. """
  446. if isinstance(curve.curve, CurveEdTw):
  447. raise ValueError("Method unsupported for Edwards curves")
  448. generator = curve.generator
  449. r, s = sigdecode(signature, generator.order())
  450. sig = ecdsa.Signature(r, s)
  451. digest = normalise_bytes(digest)
  452. digest_as_number = _truncate_and_convert_digest(
  453. digest, curve, allow_truncate
  454. )
  455. pks = sig.recover_public_keys(digest_as_number, generator)
  456. # Transforms the ecdsa.Public_key object into a VerifyingKey
  457. verifying_keys = [
  458. cls.from_public_point(pk.point, curve, hashfunc) for pk in pks
  459. ]
  460. return verifying_keys
  461. def to_string(self, encoding="raw"):
  462. """
  463. Convert the public key to a byte string.
  464. The method by default uses the :term:`raw encoding` (specified
  465. by `encoding="raw"`. It can also output keys in :term:`uncompressed`,
  466. :term:`compressed` and :term:`hybrid` formats.
  467. Remember that the curve identification is not part of the encoding
  468. so to decode the point using :func:`~VerifyingKey.from_string`, curve
  469. needs to be specified.
  470. Note: while the method is called "to_string", it's a misnomer from
  471. Python 2 days when character strings and byte strings shared type.
  472. On Python 3 the returned type will be `bytes`.
  473. :return: :term:`raw encoding` of the public key (public point) on the
  474. curve
  475. :rtype: bytes
  476. """
  477. assert encoding in ("raw", "uncompressed", "compressed", "hybrid")
  478. return self.pubkey.point.to_bytes(encoding)
  479. def to_pem(
  480. self, point_encoding="uncompressed", curve_parameters_encoding=None
  481. ):
  482. """
  483. Convert the public key to the :term:`PEM` format.
  484. The PEM header of the key will be ``BEGIN PUBLIC KEY``.
  485. The format of the key is described in the
  486. :func:`~VerifyingKey.from_der()` method.
  487. This method supports only "named curve" encoding of keys.
  488. :param str point_encoding: specification of the encoding format
  489. of public keys. "uncompressed" is most portable, "compressed" is
  490. smallest. "hybrid" is uncommon and unsupported by most
  491. implementations, it is as big as "uncompressed".
  492. :param str curve_parameters_encoding: the encoding for curve parameters
  493. to use, by default tries to use ``named_curve`` encoding,
  494. if that is not possible, falls back to ``explicit`` encoding.
  495. :return: portable encoding of the public key
  496. :rtype: bytes
  497. .. warning:: The PEM is encoded to US-ASCII, it needs to be
  498. re-encoded if the system is incompatible (e.g. uses UTF-16)
  499. """
  500. return der.topem(
  501. self.to_der(point_encoding, curve_parameters_encoding),
  502. "PUBLIC KEY",
  503. )
  504. def to_der(
  505. self, point_encoding="uncompressed", curve_parameters_encoding=None
  506. ):
  507. """
  508. Convert the public key to the :term:`DER` format.
  509. The format of the key is described in the
  510. :func:`~VerifyingKey.from_der()` method.
  511. This method supports only "named curve" encoding of keys.
  512. :param str point_encoding: specification of the encoding format
  513. of public keys. "uncompressed" is most portable, "compressed" is
  514. smallest. "hybrid" is uncommon and unsupported by most
  515. implementations, it is as big as "uncompressed".
  516. :param str curve_parameters_encoding: the encoding for curve parameters
  517. to use, by default tries to use ``named_curve`` encoding,
  518. if that is not possible, falls back to ``explicit`` encoding.
  519. :return: DER encoding of the public key
  520. :rtype: bytes
  521. """
  522. if point_encoding == "raw":
  523. raise ValueError("raw point_encoding not allowed in DER")
  524. point_str = self.to_string(point_encoding)
  525. if isinstance(self.curve.curve, CurveEdTw):
  526. return der.encode_sequence(
  527. der.encode_sequence(der.encode_oid(*self.curve.oid)),
  528. der.encode_bitstring(bytes(point_str), 0),
  529. )
  530. return der.encode_sequence(
  531. der.encode_sequence(
  532. encoded_oid_ecPublicKey,
  533. self.curve.to_der(curve_parameters_encoding, point_encoding),
  534. ),
  535. # 0 is the number of unused bits in the
  536. # bit string
  537. der.encode_bitstring(point_str, 0),
  538. )
  539. def to_ssh(self):
  540. """
  541. Convert the public key to the SSH format.
  542. :return: SSH encoding of the public key
  543. :rtype: bytes
  544. """
  545. return ssh.serialize_public(
  546. self.curve.name,
  547. self.to_string(),
  548. )
  549. def verify(
  550. self,
  551. signature,
  552. data,
  553. hashfunc=None,
  554. sigdecode=sigdecode_string,
  555. allow_truncate=True,
  556. ):
  557. """
  558. Verify a signature made over provided data.
  559. Will hash `data` to verify the signature.
  560. By default expects signature in :term:`raw encoding`. Can also be used
  561. to verify signatures in ASN.1 DER encoding by using
  562. :func:`ecdsa.util.sigdecode_der`
  563. as the `sigdecode` parameter.
  564. :param signature: encoding of the signature
  565. :type signature: sigdecode method dependent
  566. :param data: data signed by the `signature`, will be hashed using
  567. `hashfunc`, if specified, or default hash function
  568. :type data: :term:`bytes-like object`
  569. :param hashfunc: The default hash function that will be used for
  570. verification, needs to implement the same interface as hashlib.sha1
  571. :type hashfunc: callable
  572. :param sigdecode: Callable to define the way the signature needs to
  573. be decoded to an object, needs to handle `signature` as the
  574. first parameter, the curve order (an int) as the second and return
  575. a tuple with two integers, "r" as the first one and "s" as the
  576. second one. See :func:`ecdsa.util.sigdecode_string` and
  577. :func:`ecdsa.util.sigdecode_der` for examples.
  578. :type sigdecode: callable
  579. :param bool allow_truncate: if True, the provided digest can have
  580. bigger bit-size than the order of the curve, the extra bits (at
  581. the end of the digest) will be truncated. Use it when verifying
  582. SHA-384 output using NIST256p or in similar situations. Defaults to
  583. True.
  584. :raises BadSignatureError: if the signature is invalid or malformed
  585. :return: True if the verification was successful
  586. :rtype: bool
  587. """
  588. # signature doesn't have to be a bytes-like-object so don't normalise
  589. # it, the decoders will do that
  590. data = normalise_bytes(data)
  591. if isinstance(self.curve.curve, CurveEdTw):
  592. signature = normalise_bytes(signature)
  593. try:
  594. return self.pubkey.verify(data, signature)
  595. except (ValueError, MalformedPointError) as e:
  596. raise BadSignatureError("Signature verification failed", e)
  597. hashfunc = hashfunc or self.default_hashfunc
  598. digest = hashfunc(data).digest()
  599. return self.verify_digest(signature, digest, sigdecode, allow_truncate)
  600. def verify_digest(
  601. self,
  602. signature,
  603. digest,
  604. sigdecode=sigdecode_string,
  605. allow_truncate=False,
  606. ):
  607. """
  608. Verify a signature made over provided hash value.
  609. By default expects signature in :term:`raw encoding`. Can also be used
  610. to verify signatures in ASN.1 DER encoding by using
  611. :func:`ecdsa.util.sigdecode_der`
  612. as the `sigdecode` parameter.
  613. :param signature: encoding of the signature
  614. :type signature: sigdecode method dependent
  615. :param digest: raw hash value that the signature authenticates.
  616. :type digest: :term:`bytes-like object`
  617. :param sigdecode: Callable to define the way the signature needs to
  618. be decoded to an object, needs to handle `signature` as the
  619. first parameter, the curve order (an int) as the second and return
  620. a tuple with two integers, "r" as the first one and "s" as the
  621. second one. See :func:`ecdsa.util.sigdecode_string` and
  622. :func:`ecdsa.util.sigdecode_der` for examples.
  623. :type sigdecode: callable
  624. :param bool allow_truncate: if True, the provided digest can have
  625. bigger bit-size than the order of the curve, the extra bits (at
  626. the end of the digest) will be truncated. Use it when verifying
  627. SHA-384 output using NIST256p or in similar situations.
  628. :raises BadSignatureError: if the signature is invalid or malformed
  629. :raises BadDigestError: if the provided digest is too big for the curve
  630. associated with this VerifyingKey and allow_truncate was not set
  631. :return: True if the verification was successful
  632. :rtype: bool
  633. """
  634. # signature doesn't have to be a bytes-like-object so don't normalise
  635. # it, the decoders will do that
  636. digest = normalise_bytes(digest)
  637. number = _truncate_and_convert_digest(
  638. digest,
  639. self.curve,
  640. allow_truncate,
  641. )
  642. try:
  643. r, s = sigdecode(signature, self.pubkey.order)
  644. except (der.UnexpectedDER, MalformedSignature) as e:
  645. raise BadSignatureError("Malformed formatting of signature", e)
  646. sig = ecdsa.Signature(r, s)
  647. if self.pubkey.verifies(number, sig):
  648. return True
  649. raise BadSignatureError("Signature verification failed")
  650. class SigningKey(object):
  651. """
  652. Class for handling keys that can create signatures (private keys).
  653. :ivar `~ecdsa.curves.Curve` curve: The Curve over which all the
  654. cryptographic operations will take place
  655. :ivar default_hashfunc: the function that will be used for hashing the
  656. data. Should implement the same API as :py:class:`hashlib.sha1`
  657. :ivar int baselen: the length of a :term:`raw encoding` of private key
  658. :ivar `~ecdsa.keys.VerifyingKey` verifying_key: the public key
  659. associated with this private key
  660. :ivar `~ecdsa.ecdsa.Private_key` privkey: the actual private key
  661. """
  662. def __init__(self, _error__please_use_generate=None):
  663. """Unsupported, please use one of the classmethods to initialise."""
  664. if not _error__please_use_generate:
  665. raise TypeError("Please use SigningKey.generate() to construct me")
  666. self.curve = None
  667. self.default_hashfunc = None
  668. self.baselen = None
  669. self.verifying_key = None
  670. self.privkey = None
  671. def __eq__(self, other):
  672. """Return True if the points are identical, False otherwise."""
  673. if isinstance(other, SigningKey):
  674. return (
  675. self.curve == other.curve
  676. and self.verifying_key == other.verifying_key
  677. and self.privkey == other.privkey
  678. )
  679. return NotImplemented
  680. def __ne__(self, other):
  681. """Return False if the points are identical, True otherwise."""
  682. return not self == other
  683. @classmethod
  684. def _twisted_edwards_keygen(cls, curve, entropy):
  685. """Generate a private key on a Twisted Edwards curve."""
  686. if not entropy:
  687. entropy = os.urandom
  688. random = entropy(curve.baselen)
  689. private_key = eddsa.PrivateKey(curve.generator, random)
  690. public_key = private_key.public_key()
  691. verifying_key = VerifyingKey.from_string(
  692. public_key.public_key(), curve
  693. )
  694. self = cls(_error__please_use_generate=True)
  695. self.curve = curve
  696. self.default_hashfunc = None
  697. self.baselen = curve.baselen
  698. self.privkey = private_key
  699. self.verifying_key = verifying_key
  700. return self
  701. @classmethod
  702. def _weierstrass_keygen(cls, curve, entropy, hashfunc):
  703. """Generate a private key on a Weierstrass curve."""
  704. secexp = randrange(curve.order, entropy)
  705. return cls.from_secret_exponent(secexp, curve, hashfunc)
  706. @classmethod
  707. def generate(cls, curve=NIST192p, entropy=None, hashfunc=sha1):
  708. """
  709. Generate a random private key.
  710. :param curve: The curve on which the point needs to reside, defaults
  711. to NIST192p
  712. :type curve: ~ecdsa.curves.Curve
  713. :param entropy: Source of randomness for generating the private keys,
  714. should provide cryptographically secure random numbers if the keys
  715. need to be secure. Uses os.urandom() by default.
  716. :type entropy: callable
  717. :param hashfunc: The default hash function that will be used for
  718. signing, needs to implement the same interface
  719. as hashlib.sha1
  720. :type hashfunc: callable
  721. :return: Initialised SigningKey object
  722. :rtype: SigningKey
  723. """
  724. if isinstance(curve.curve, CurveEdTw):
  725. return cls._twisted_edwards_keygen(curve, entropy)
  726. return cls._weierstrass_keygen(curve, entropy, hashfunc)
  727. @classmethod
  728. def from_secret_exponent(cls, secexp, curve=NIST192p, hashfunc=sha1):
  729. """
  730. Create a private key from a random integer.
  731. Note: it's a low level method, it's recommended to use the
  732. :func:`~SigningKey.generate` method to create private keys.
  733. :param int secexp: secret multiplier (the actual private key in ECDSA).
  734. Needs to be an integer between 1 and the curve order.
  735. :param curve: The curve on which the point needs to reside
  736. :type curve: ~ecdsa.curves.Curve
  737. :param hashfunc: The default hash function that will be used for
  738. signing, needs to implement the same interface
  739. as hashlib.sha1
  740. :type hashfunc: callable
  741. :raises MalformedPointError: when the provided secexp is too large
  742. or too small for the curve selected
  743. :raises RuntimeError: if the generation of public key from private
  744. key failed
  745. :return: Initialised SigningKey object
  746. :rtype: SigningKey
  747. """
  748. if isinstance(curve.curve, CurveEdTw):
  749. raise ValueError(
  750. "Edwards keys don't support setting the secret scalar "
  751. "(exponent) directly"
  752. )
  753. self = cls(_error__please_use_generate=True)
  754. self.curve = curve
  755. self.default_hashfunc = hashfunc
  756. self.baselen = curve.baselen
  757. n = curve.order
  758. if not 1 <= secexp < n:
  759. raise MalformedPointError(
  760. "Invalid value for secexp, expected integer "
  761. "between 1 and {0}".format(n)
  762. )
  763. pubkey_point = curve.generator * secexp
  764. if hasattr(pubkey_point, "scale"):
  765. pubkey_point = pubkey_point.scale()
  766. self.verifying_key = VerifyingKey.from_public_point(
  767. pubkey_point, curve, hashfunc, False
  768. )
  769. pubkey = self.verifying_key.pubkey
  770. self.privkey = ecdsa.Private_key(pubkey, secexp)
  771. self.privkey.order = n
  772. return self
  773. @classmethod
  774. def from_string(cls, string, curve=NIST192p, hashfunc=sha1):
  775. """
  776. Decode the private key from :term:`raw encoding`.
  777. Note: the name of this method is a misnomer coming from days of
  778. Python 2, when binary strings and character strings shared a type.
  779. In Python 3, the expected type is `bytes`.
  780. :param string: the raw encoding of the private key
  781. :type string: :term:`bytes-like object`
  782. :param curve: The curve on which the point needs to reside
  783. :type curve: ~ecdsa.curves.Curve
  784. :param hashfunc: The default hash function that will be used for
  785. signing, needs to implement the same interface
  786. as hashlib.sha1
  787. :type hashfunc: callable
  788. :raises MalformedPointError: if the length of encoding doesn't match
  789. the provided curve or the encoded values is too large
  790. :raises RuntimeError: if the generation of public key from private
  791. key failed
  792. :return: Initialised SigningKey object
  793. :rtype: SigningKey
  794. """
  795. string = normalise_bytes(string)
  796. if len(string) != curve.baselen:
  797. raise MalformedPointError(
  798. "Invalid length of private key, received {0}, "
  799. "expected {1}".format(len(string), curve.baselen)
  800. )
  801. if isinstance(curve.curve, CurveEdTw):
  802. self = cls(_error__please_use_generate=True)
  803. self.curve = curve
  804. self.default_hashfunc = None # Ignored for EdDSA
  805. self.baselen = curve.baselen
  806. self.privkey = eddsa.PrivateKey(curve.generator, string)
  807. self.verifying_key = VerifyingKey.from_string(
  808. self.privkey.public_key().public_key(), curve
  809. )
  810. return self
  811. secexp = string_to_number(string)
  812. return cls.from_secret_exponent(secexp, curve, hashfunc)
  813. @classmethod
  814. def from_pem(cls, string, hashfunc=sha1, valid_curve_encodings=None):
  815. """
  816. Initialise from key stored in :term:`PEM` format.
  817. The PEM formats supported are the un-encrypted RFC5915
  818. (the ssleay format) supported by OpenSSL, and the more common
  819. un-encrypted RFC5958 (the PKCS #8 format).
  820. The legacy format files have the header with the string
  821. ``BEGIN EC PRIVATE KEY``.
  822. PKCS#8 files have the header ``BEGIN PRIVATE KEY``.
  823. Encrypted files (ones that include the string
  824. ``Proc-Type: 4,ENCRYPTED``
  825. right after the PEM header) are not supported.
  826. See :func:`~SigningKey.from_der` for ASN.1 syntax of the objects in
  827. this files.
  828. :param string: text with PEM-encoded private ECDSA key
  829. :type string: str
  830. :param valid_curve_encodings: list of allowed encoding formats
  831. for curve parameters. By default (``None``) all are supported:
  832. ``named_curve`` and ``explicit``.
  833. :type valid_curve_encodings: :term:`set-like object`
  834. :raises MalformedPointError: if the length of encoding doesn't match
  835. the provided curve or the encoded values is too large
  836. :raises RuntimeError: if the generation of public key from private
  837. key failed
  838. :raises UnexpectedDER: if the encoding of the PEM file is incorrect
  839. :return: Initialised SigningKey object
  840. :rtype: SigningKey
  841. """
  842. if not PY2 and isinstance(string, str): # pragma: no branch
  843. string = string.encode()
  844. # The privkey pem may have multiple sections, commonly it also has
  845. # "EC PARAMETERS", we need just "EC PRIVATE KEY". PKCS#8 should not
  846. # have the "EC PARAMETERS" section; it's just "PRIVATE KEY".
  847. private_key_index = string.find(b"-----BEGIN EC PRIVATE KEY-----")
  848. if private_key_index == -1:
  849. private_key_index = string.index(b"-----BEGIN PRIVATE KEY-----")
  850. return cls.from_der(
  851. der.unpem(string[private_key_index:]),
  852. hashfunc,
  853. valid_curve_encodings,
  854. )
  855. @classmethod
  856. def from_der(cls, string, hashfunc=sha1, valid_curve_encodings=None):
  857. """
  858. Initialise from key stored in :term:`DER` format.
  859. The DER formats supported are the un-encrypted RFC5915
  860. (the ssleay format) supported by OpenSSL, and the more common
  861. un-encrypted RFC5958 (the PKCS #8 format).
  862. Both formats contain an ASN.1 object following the syntax specified
  863. in RFC5915::
  864. ECPrivateKey ::= SEQUENCE {
  865. version INTEGER { ecPrivkeyVer1(1) }} (ecPrivkeyVer1),
  866. privateKey OCTET STRING,
  867. parameters [0] ECParameters {{ NamedCurve }} OPTIONAL,
  868. publicKey [1] BIT STRING OPTIONAL
  869. }
  870. `publicKey` field is ignored completely (errors, if any, in it will
  871. be undetected).
  872. Two formats are supported for the `parameters` field: the named
  873. curve and the explicit encoding of curve parameters.
  874. In the legacy ssleay format, this implementation requires the optional
  875. `parameters` field to get the curve name. In PKCS #8 format, the curve
  876. is part of the PrivateKeyAlgorithmIdentifier.
  877. The PKCS #8 format includes an ECPrivateKey object as the `privateKey`
  878. field within a larger structure::
  879. OneAsymmetricKey ::= SEQUENCE {
  880. version Version,
  881. privateKeyAlgorithm PrivateKeyAlgorithmIdentifier,
  882. privateKey PrivateKey,
  883. attributes [0] Attributes OPTIONAL,
  884. ...,
  885. [[2: publicKey [1] PublicKey OPTIONAL ]],
  886. ...
  887. }
  888. The `attributes` and `publicKey` fields are completely ignored; errors
  889. in them will not be detected.
  890. :param string: binary string with DER-encoded private ECDSA key
  891. :type string: :term:`bytes-like object`
  892. :param valid_curve_encodings: list of allowed encoding formats
  893. for curve parameters. By default (``None``) all are supported:
  894. ``named_curve`` and ``explicit``.
  895. Ignored for EdDSA.
  896. :type valid_curve_encodings: :term:`set-like object`
  897. :raises MalformedPointError: if the length of encoding doesn't match
  898. the provided curve or the encoded values is too large
  899. :raises RuntimeError: if the generation of public key from private
  900. key failed
  901. :raises UnexpectedDER: if the encoding of the DER file is incorrect
  902. :return: Initialised SigningKey object
  903. :rtype: SigningKey
  904. """
  905. s = normalise_bytes(string)
  906. curve = None
  907. s, empty = der.remove_sequence(s)
  908. if empty != b"":
  909. raise der.UnexpectedDER(
  910. "trailing junk after DER privkey: %s" % binascii.hexlify(empty)
  911. )
  912. version, s = der.remove_integer(s)
  913. # At this point, PKCS #8 has a sequence containing the algorithm
  914. # identifier and the curve identifier. The ssleay format instead has
  915. # an octet string containing the key data, so this is how we can
  916. # distinguish the two formats.
  917. if der.is_sequence(s):
  918. if version not in (0, 1):
  919. raise der.UnexpectedDER(
  920. "expected version '0' or '1' at start of privkey, got %d"
  921. % version
  922. )
  923. sequence, s = der.remove_sequence(s)
  924. algorithm_oid, algorithm_identifier = der.remove_object(sequence)
  925. if algorithm_oid in (Ed25519.oid, Ed448.oid):
  926. if algorithm_identifier:
  927. raise der.UnexpectedDER(
  928. "Non NULL parameters for a EdDSA key"
  929. )
  930. key_str_der, s = der.remove_octet_string(s)
  931. # As RFC5958 describe, there are may be optional Attributes
  932. # and Publickey. Don't raise error if something after
  933. # Privatekey
  934. # TODO parse attributes or validate publickey
  935. # if s:
  936. # raise der.UnexpectedDER(
  937. # "trailing junk inside the privateKey"
  938. # )
  939. key_str, s = der.remove_octet_string(key_str_der)
  940. if s:
  941. raise der.UnexpectedDER(
  942. "trailing junk after the encoded private key"
  943. )
  944. if algorithm_oid == Ed25519.oid:
  945. curve = Ed25519
  946. else:
  947. assert algorithm_oid == Ed448.oid
  948. curve = Ed448
  949. return cls.from_string(key_str, curve, None)
  950. if algorithm_oid not in (oid_ecPublicKey, oid_ecDH, oid_ecMQV):
  951. raise der.UnexpectedDER(
  952. "unexpected algorithm identifier '%s'" % (algorithm_oid,)
  953. )
  954. curve = Curve.from_der(algorithm_identifier, valid_curve_encodings)
  955. # Up next is an octet string containing an ECPrivateKey. Ignore
  956. # the optional "attributes" and "publicKey" fields that come after.
  957. s, _ = der.remove_octet_string(s)
  958. # Unpack the ECPrivateKey to get to the key data octet string,
  959. # and rejoin the ssleay parsing path.
  960. s, empty = der.remove_sequence(s)
  961. if empty != b"":
  962. raise der.UnexpectedDER(
  963. "trailing junk after DER privkey: %s"
  964. % binascii.hexlify(empty)
  965. )
  966. version, s = der.remove_integer(s)
  967. # The version of the ECPrivateKey must be 1.
  968. if version != 1:
  969. raise der.UnexpectedDER(
  970. "expected version '1' at start of DER privkey, got %d"
  971. % version
  972. )
  973. privkey_str, s = der.remove_octet_string(s)
  974. if not curve:
  975. tag, curve_oid_str, s = der.remove_constructed(s)
  976. if tag != 0:
  977. raise der.UnexpectedDER(
  978. "expected tag 0 in DER privkey, got %d" % tag
  979. )
  980. curve = Curve.from_der(curve_oid_str, valid_curve_encodings)
  981. # we don't actually care about the following fields
  982. #
  983. # tag, pubkey_bitstring, s = der.remove_constructed(s)
  984. # if tag != 1:
  985. # raise der.UnexpectedDER("expected tag 1 in DER privkey, got %d"
  986. # % tag)
  987. # pubkey_str = der.remove_bitstring(pubkey_bitstring, 0)
  988. # if empty != "":
  989. # raise der.UnexpectedDER("trailing junk after DER privkey "
  990. # "pubkeystr: %s"
  991. # % binascii.hexlify(empty))
  992. # our from_string method likes fixed-length privkey strings
  993. if len(privkey_str) < curve.baselen:
  994. privkey_str = (
  995. b"\x00" * (curve.baselen - len(privkey_str)) + privkey_str
  996. )
  997. return cls.from_string(privkey_str, curve, hashfunc)
  998. def to_string(self):
  999. """
  1000. Convert the private key to :term:`raw encoding`.
  1001. Note: while the method is named "to_string", its name comes from
  1002. Python 2 days, when binary and character strings used the same type.
  1003. The type used in Python 3 is `bytes`.
  1004. :return: raw encoding of private key
  1005. :rtype: bytes
  1006. """
  1007. if isinstance(self.curve.curve, CurveEdTw):
  1008. return bytes(self.privkey.private_key)
  1009. secexp = self.privkey.secret_multiplier
  1010. s = number_to_string(secexp, self.privkey.order)
  1011. return s
  1012. def to_pem(
  1013. self,
  1014. point_encoding="uncompressed",
  1015. format="ssleay",
  1016. curve_parameters_encoding=None,
  1017. ):
  1018. """
  1019. Convert the private key to the :term:`PEM` format.
  1020. See :func:`~SigningKey.from_pem` method for format description.
  1021. Only the named curve format is supported.
  1022. The public key will be included in generated string.
  1023. The PEM header will specify ``BEGIN EC PRIVATE KEY`` or
  1024. ``BEGIN PRIVATE KEY``, depending on the desired format.
  1025. :param str point_encoding: format to use for encoding public point
  1026. :param str format: either ``ssleay`` (default) or ``pkcs8``
  1027. :param str curve_parameters_encoding: format of encoded curve
  1028. parameters, default depends on the curve, if the curve has
  1029. an associated OID, ``named_curve`` format will be used,
  1030. if no OID is associated with the curve, the fallback of
  1031. ``explicit`` parameters will be used.
  1032. :return: PEM encoded private key
  1033. :rtype: bytes
  1034. .. warning:: The PEM is encoded to US-ASCII, it needs to be
  1035. re-encoded if the system is incompatible (e.g. uses UTF-16)
  1036. """
  1037. # TODO: "BEGIN ECPARAMETERS"
  1038. assert format in ("ssleay", "pkcs8")
  1039. header = "EC PRIVATE KEY" if format == "ssleay" else "PRIVATE KEY"
  1040. return der.topem(
  1041. self.to_der(point_encoding, format, curve_parameters_encoding),
  1042. header,
  1043. )
  1044. def _encode_eddsa(self):
  1045. """Create a PKCS#8 encoding of EdDSA keys."""
  1046. ec_private_key = der.encode_octet_string(self.to_string())
  1047. return der.encode_sequence(
  1048. der.encode_integer(0),
  1049. der.encode_sequence(der.encode_oid(*self.curve.oid)),
  1050. der.encode_octet_string(ec_private_key),
  1051. )
  1052. def to_der(
  1053. self,
  1054. point_encoding="uncompressed",
  1055. format="ssleay",
  1056. curve_parameters_encoding=None,
  1057. ):
  1058. """
  1059. Convert the private key to the :term:`DER` format.
  1060. See :func:`~SigningKey.from_der` method for format specification.
  1061. Only the named curve format is supported.
  1062. The public key will be included in the generated string.
  1063. :param str point_encoding: format to use for encoding public point
  1064. Ignored for EdDSA
  1065. :param str format: either ``ssleay`` (default) or ``pkcs8``.
  1066. EdDSA keys require ``pkcs8``.
  1067. :param str curve_parameters_encoding: format of encoded curve
  1068. parameters, default depends on the curve, if the curve has
  1069. an associated OID, ``named_curve`` format will be used,
  1070. if no OID is associated with the curve, the fallback of
  1071. ``explicit`` parameters will be used.
  1072. Ignored for EdDSA.
  1073. :return: DER encoded private key
  1074. :rtype: bytes
  1075. """
  1076. # SEQ([int(1), octetstring(privkey),cont[0], oid(secp224r1),
  1077. # cont[1],bitstring])
  1078. if point_encoding == "raw":
  1079. raise ValueError("raw encoding not allowed in DER")
  1080. assert format in ("ssleay", "pkcs8")
  1081. if isinstance(self.curve.curve, CurveEdTw):
  1082. if format != "pkcs8":
  1083. raise ValueError("Only PKCS#8 format supported for EdDSA keys")
  1084. return self._encode_eddsa()
  1085. encoded_vk = self.get_verifying_key().to_string(point_encoding)
  1086. priv_key_elems = [
  1087. der.encode_integer(1),
  1088. der.encode_octet_string(self.to_string()),
  1089. ]
  1090. if format == "ssleay":
  1091. priv_key_elems.append(
  1092. der.encode_constructed(
  1093. 0, self.curve.to_der(curve_parameters_encoding)
  1094. )
  1095. )
  1096. # the 0 in encode_bitstring specifies the number of unused bits
  1097. # in the `encoded_vk` string
  1098. priv_key_elems.append(
  1099. der.encode_constructed(1, der.encode_bitstring(encoded_vk, 0))
  1100. )
  1101. ec_private_key = der.encode_sequence(*priv_key_elems)
  1102. if format == "ssleay":
  1103. return ec_private_key
  1104. else:
  1105. return der.encode_sequence(
  1106. # version = 1 means the public key is not present in the
  1107. # top-level structure.
  1108. der.encode_integer(1),
  1109. der.encode_sequence(
  1110. der.encode_oid(*oid_ecPublicKey),
  1111. self.curve.to_der(curve_parameters_encoding),
  1112. ),
  1113. der.encode_octet_string(ec_private_key),
  1114. )
  1115. def to_ssh(self):
  1116. """
  1117. Convert the private key to the SSH format.
  1118. :return: SSH encoded private key
  1119. :rtype: bytes
  1120. """
  1121. return ssh.serialize_private(
  1122. self.curve.name,
  1123. self.verifying_key.to_string(),
  1124. self.to_string(),
  1125. )
  1126. def get_verifying_key(self):
  1127. """
  1128. Return the VerifyingKey associated with this private key.
  1129. Equivalent to reading the `verifying_key` field of an instance.
  1130. :return: a public key that can be used to verify the signatures made
  1131. with this SigningKey
  1132. :rtype: VerifyingKey
  1133. """
  1134. return self.verifying_key
  1135. def sign_deterministic(
  1136. self,
  1137. data,
  1138. hashfunc=None,
  1139. sigencode=sigencode_string,
  1140. extra_entropy=b"",
  1141. ):
  1142. """
  1143. Create signature over data.
  1144. For Weierstrass curves it uses the deterministic RFC6979 algorithm.
  1145. For Edwards curves it uses the standard EdDSA algorithm.
  1146. For ECDSA the data will be hashed using the `hashfunc` function before
  1147. signing.
  1148. For EdDSA the data will be hashed with the hash associated with the
  1149. curve (SHA-512 for Ed25519 and SHAKE-256 for Ed448).
  1150. This is the recommended method for performing signatures when hashing
  1151. of data is necessary.
  1152. :param data: data to be hashed and computed signature over
  1153. :type data: :term:`bytes-like object`
  1154. :param hashfunc: hash function to use for computing the signature,
  1155. if unspecified, the default hash function selected during
  1156. object initialisation will be used (see
  1157. `VerifyingKey.default_hashfunc`). The object needs to implement
  1158. the same interface as hashlib.sha1.
  1159. Ignored with EdDSA.
  1160. :type hashfunc: callable
  1161. :param sigencode: function used to encode the signature.
  1162. The function needs to accept three parameters: the two integers
  1163. that are the signature and the order of the curve over which the
  1164. signature was computed. It needs to return an encoded signature.
  1165. See `ecdsa.util.sigencode_string` and `ecdsa.util.sigencode_der`
  1166. as examples of such functions.
  1167. Ignored with EdDSA.
  1168. :type sigencode: callable
  1169. :param extra_entropy: additional data that will be fed into the random
  1170. number generator used in the RFC6979 process. Entirely optional.
  1171. Ignored with EdDSA.
  1172. :type extra_entropy: :term:`bytes-like object`
  1173. :return: encoded signature over `data`
  1174. :rtype: bytes or sigencode function dependent type
  1175. """
  1176. hashfunc = hashfunc or self.default_hashfunc
  1177. data = normalise_bytes(data)
  1178. if isinstance(self.curve.curve, CurveEdTw):
  1179. return self.privkey.sign(data)
  1180. extra_entropy = normalise_bytes(extra_entropy)
  1181. digest = hashfunc(data).digest()
  1182. return self.sign_digest_deterministic(
  1183. digest,
  1184. hashfunc=hashfunc,
  1185. sigencode=sigencode,
  1186. extra_entropy=extra_entropy,
  1187. allow_truncate=True,
  1188. )
  1189. def sign_digest_deterministic(
  1190. self,
  1191. digest,
  1192. hashfunc=None,
  1193. sigencode=sigencode_string,
  1194. extra_entropy=b"",
  1195. allow_truncate=False,
  1196. ):
  1197. """
  1198. Create signature for digest using the deterministic RFC6979 algorithm.
  1199. `digest` should be the output of cryptographically secure hash function
  1200. like SHA256 or SHA-3-256.
  1201. This is the recommended method for performing signatures when no
  1202. hashing of data is necessary.
  1203. :param digest: hash of data that will be signed
  1204. :type digest: :term:`bytes-like object`
  1205. :param hashfunc: hash function to use for computing the random "k"
  1206. value from RFC6979 process,
  1207. if unspecified, the default hash function selected during
  1208. object initialisation will be used (see
  1209. :attr:`.VerifyingKey.default_hashfunc`). The object needs to
  1210. implement
  1211. the same interface as :func:`~hashlib.sha1` from :py:mod:`hashlib`.
  1212. :type hashfunc: callable
  1213. :param sigencode: function used to encode the signature.
  1214. The function needs to accept three parameters: the two integers
  1215. that are the signature and the order of the curve over which the
  1216. signature was computed. It needs to return an encoded signature.
  1217. See :func:`~ecdsa.util.sigencode_string` and
  1218. :func:`~ecdsa.util.sigencode_der`
  1219. as examples of such functions.
  1220. :type sigencode: callable
  1221. :param extra_entropy: additional data that will be fed into the random
  1222. number generator used in the RFC6979 process. Entirely optional.
  1223. :type extra_entropy: :term:`bytes-like object`
  1224. :param bool allow_truncate: if True, the provided digest can have
  1225. bigger bit-size than the order of the curve, the extra bits (at
  1226. the end of the digest) will be truncated. Use it when signing
  1227. SHA-384 output using NIST256p or in similar situations.
  1228. :return: encoded signature for the `digest` hash
  1229. :rtype: bytes or sigencode function dependent type
  1230. """
  1231. if isinstance(self.curve.curve, CurveEdTw):
  1232. raise ValueError("Method unsupported for Edwards curves")
  1233. secexp = self.privkey.secret_multiplier
  1234. hashfunc = hashfunc or self.default_hashfunc
  1235. digest = normalise_bytes(digest)
  1236. extra_entropy = normalise_bytes(extra_entropy)
  1237. def simple_r_s(r, s, order):
  1238. return r, s, order
  1239. retry_gen = 0
  1240. while True:
  1241. k = rfc6979.generate_k(
  1242. self.curve.generator.order(),
  1243. secexp,
  1244. hashfunc,
  1245. digest,
  1246. retry_gen=retry_gen,
  1247. extra_entropy=extra_entropy,
  1248. )
  1249. try:
  1250. r, s, order = self.sign_digest(
  1251. digest,
  1252. sigencode=simple_r_s,
  1253. k=k,
  1254. allow_truncate=allow_truncate,
  1255. )
  1256. break
  1257. except RSZeroError:
  1258. retry_gen += 1
  1259. return sigencode(r, s, order)
  1260. def sign(
  1261. self,
  1262. data,
  1263. entropy=None,
  1264. hashfunc=None,
  1265. sigencode=sigencode_string,
  1266. k=None,
  1267. allow_truncate=True,
  1268. ):
  1269. """
  1270. Create signature over data.
  1271. Uses the probabilistic ECDSA algorithm for Weierstrass curves
  1272. (NIST256p, etc.) and the deterministic EdDSA algorithm for the
  1273. Edwards curves (Ed25519, Ed448).
  1274. This method uses the standard ECDSA algorithm that requires a
  1275. cryptographically secure random number generator.
  1276. It's recommended to use the :func:`~SigningKey.sign_deterministic`
  1277. method instead of this one.
  1278. :param data: data that will be hashed for signing
  1279. :type data: :term:`bytes-like object`
  1280. :param callable entropy: randomness source, :func:`os.urandom` by
  1281. default. Ignored with EdDSA.
  1282. :param hashfunc: hash function to use for hashing the provided
  1283. ``data``.
  1284. If unspecified the default hash function selected during
  1285. object initialisation will be used (see
  1286. :attr:`.VerifyingKey.default_hashfunc`).
  1287. Should behave like :func:`~hashlib.sha1` from :py:mod:`hashlib`.
  1288. The output length of the
  1289. hash (in bytes) must not be longer than the length of the curve
  1290. order (rounded up to the nearest byte), so using SHA256 with
  1291. NIST256p is ok, but SHA256 with NIST192p is not. (In the 2**-96ish
  1292. unlikely event of a hash output larger than the curve order, the
  1293. hash will effectively be wrapped mod n).
  1294. If you want to explicitly allow use of large hashes with small
  1295. curves set the ``allow_truncate`` to ``True``.
  1296. Use ``hashfunc=hashlib.sha1`` to match openssl's
  1297. ``-ecdsa-with-SHA1`` mode,
  1298. or ``hashfunc=hashlib.sha256`` for openssl-1.0.0's
  1299. ``-ecdsa-with-SHA256``.
  1300. Ignored for EdDSA
  1301. :type hashfunc: callable
  1302. :param sigencode: function used to encode the signature.
  1303. The function needs to accept three parameters: the two integers
  1304. that are the signature and the order of the curve over which the
  1305. signature was computed. It needs to return an encoded signature.
  1306. See :func:`~ecdsa.util.sigencode_string` and
  1307. :func:`~ecdsa.util.sigencode_der`
  1308. as examples of such functions.
  1309. Ignored for EdDSA
  1310. :type sigencode: callable
  1311. :param int k: a pre-selected nonce for calculating the signature.
  1312. In typical use cases, it should be set to None (the default) to
  1313. allow its generation from an entropy source.
  1314. Ignored for EdDSA.
  1315. :param bool allow_truncate: if ``True``, the provided digest can have
  1316. bigger bit-size than the order of the curve, the extra bits (at
  1317. the end of the digest) will be truncated. Use it when signing
  1318. SHA-384 output using NIST256p or in similar situations. True by
  1319. default.
  1320. Ignored for EdDSA.
  1321. :raises RSZeroError: in the unlikely event when *r* parameter or
  1322. *s* parameter of the created signature is equal 0, as that would
  1323. leak the key. Caller should try a better entropy source, retry with
  1324. different ``k``, or use the
  1325. :func:`~SigningKey.sign_deterministic` in such case.
  1326. :return: encoded signature of the hash of `data`
  1327. :rtype: bytes or sigencode function dependent type
  1328. """
  1329. hashfunc = hashfunc or self.default_hashfunc
  1330. data = normalise_bytes(data)
  1331. if isinstance(self.curve.curve, CurveEdTw):
  1332. return self.sign_deterministic(data)
  1333. h = hashfunc(data).digest()
  1334. return self.sign_digest(h, entropy, sigencode, k, allow_truncate)
  1335. def sign_digest(
  1336. self,
  1337. digest,
  1338. entropy=None,
  1339. sigencode=sigencode_string,
  1340. k=None,
  1341. allow_truncate=False,
  1342. ):
  1343. """
  1344. Create signature over digest using the probabilistic ECDSA algorithm.
  1345. This method uses the standard ECDSA algorithm that requires a
  1346. cryptographically secure random number generator.
  1347. This method does not hash the input.
  1348. It's recommended to use the
  1349. :func:`~SigningKey.sign_digest_deterministic` method
  1350. instead of this one.
  1351. :param digest: hash value that will be signed
  1352. :type digest: :term:`bytes-like object`
  1353. :param callable entropy: randomness source, os.urandom by default
  1354. :param sigencode: function used to encode the signature.
  1355. The function needs to accept three parameters: the two integers
  1356. that are the signature and the order of the curve over which the
  1357. signature was computed. It needs to return an encoded signature.
  1358. See `ecdsa.util.sigencode_string` and `ecdsa.util.sigencode_der`
  1359. as examples of such functions.
  1360. :type sigencode: callable
  1361. :param int k: a pre-selected nonce for calculating the signature.
  1362. In typical use cases, it should be set to None (the default) to
  1363. allow its generation from an entropy source.
  1364. :param bool allow_truncate: if True, the provided digest can have
  1365. bigger bit-size than the order of the curve, the extra bits (at
  1366. the end of the digest) will be truncated. Use it when signing
  1367. SHA-384 output using NIST256p or in similar situations.
  1368. :raises RSZeroError: in the unlikely event when "r" parameter or
  1369. "s" parameter of the created signature is equal 0, as that would
  1370. leak the key. Caller should try a better entropy source, retry with
  1371. different 'k', or use the
  1372. :func:`~SigningKey.sign_digest_deterministic` in such case.
  1373. :return: encoded signature for the `digest` hash
  1374. :rtype: bytes or sigencode function dependent type
  1375. """
  1376. if isinstance(self.curve.curve, CurveEdTw):
  1377. raise ValueError("Method unsupported for Edwards curves")
  1378. digest = normalise_bytes(digest)
  1379. number = _truncate_and_convert_digest(
  1380. digest,
  1381. self.curve,
  1382. allow_truncate,
  1383. )
  1384. r, s = self.sign_number(number, entropy, k)
  1385. return sigencode(r, s, self.privkey.order)
  1386. def sign_number(self, number, entropy=None, k=None):
  1387. """
  1388. Sign an integer directly.
  1389. Note, this is a low level method, usually you will want to use
  1390. :func:`~SigningKey.sign_deterministic` or
  1391. :func:`~SigningKey.sign_digest_deterministic`.
  1392. :param int number: number to sign using the probabilistic ECDSA
  1393. algorithm.
  1394. :param callable entropy: entropy source, os.urandom by default
  1395. :param int k: pre-selected nonce for signature operation. If unset
  1396. it will be selected at random using the entropy source.
  1397. :raises RSZeroError: in the unlikely event when "r" parameter or
  1398. "s" parameter of the created signature is equal 0, as that would
  1399. leak the key. Caller should try a better entropy source, retry with
  1400. different 'k', or use the
  1401. :func:`~SigningKey.sign_digest_deterministic` in such case.
  1402. :return: the "r" and "s" parameters of the signature
  1403. :rtype: tuple of ints
  1404. """
  1405. if isinstance(self.curve.curve, CurveEdTw):
  1406. raise ValueError("Method unsupported for Edwards curves")
  1407. order = self.privkey.order
  1408. if k is not None:
  1409. _k = k
  1410. else:
  1411. _k = randrange(order, entropy)
  1412. assert 1 <= _k < order
  1413. sig = self.privkey.sign(number, _k)
  1414. return sig.r, sig.s