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.
 
 
 
 

534 line
18 KiB

  1. """
  2. This module includes some utility functions.
  3. The methods most typically used are the sigencode and sigdecode functions
  4. to be used with :func:`~ecdsa.keys.SigningKey.sign` and
  5. :func:`~ecdsa.keys.VerifyingKey.verify`
  6. respectively. See the :func:`sigencode_strings`, :func:`sigdecode_string`,
  7. :func:`sigencode_der`, :func:`sigencode_strings_canonize`,
  8. :func:`sigencode_string_canonize`, :func:`sigencode_der_canonize`,
  9. :func:`sigdecode_strings`, :func:`sigdecode_string`, and
  10. :func:`sigdecode_der` functions.
  11. """
  12. from __future__ import division
  13. import os
  14. import math
  15. import binascii
  16. import sys
  17. from hashlib import sha256
  18. from six import PY2, int2byte, next
  19. from . import der
  20. from ._compat import normalise_bytes
  21. # RFC5480:
  22. # The "unrestricted" algorithm identifier is:
  23. # id-ecPublicKey OBJECT IDENTIFIER ::= {
  24. # iso(1) member-body(2) us(840) ansi-X9-62(10045) keyType(2) 1 }
  25. oid_ecPublicKey = (1, 2, 840, 10045, 2, 1)
  26. encoded_oid_ecPublicKey = der.encode_oid(*oid_ecPublicKey)
  27. # RFC5480:
  28. # The ECDH algorithm uses the following object identifier:
  29. # id-ecDH OBJECT IDENTIFIER ::= {
  30. # iso(1) identified-organization(3) certicom(132) schemes(1)
  31. # ecdh(12) }
  32. oid_ecDH = (1, 3, 132, 1, 12)
  33. # RFC5480:
  34. # The ECMQV algorithm uses the following object identifier:
  35. # id-ecMQV OBJECT IDENTIFIER ::= {
  36. # iso(1) identified-organization(3) certicom(132) schemes(1)
  37. # ecmqv(13) }
  38. oid_ecMQV = (1, 3, 132, 1, 13)
  39. if sys.version_info >= (3,): # pragma: no branch
  40. def entropy_to_bits(ent_256):
  41. """Convert a bytestring to string of 0's and 1's"""
  42. return bin(int.from_bytes(ent_256, "big"))[2:].zfill(len(ent_256) * 8)
  43. else:
  44. def entropy_to_bits(ent_256):
  45. """Convert a bytestring to string of 0's and 1's"""
  46. return "".join(bin(ord(x))[2:].zfill(8) for x in ent_256)
  47. if sys.version_info < (2, 7): # pragma: no branch
  48. # Can't add a method to a built-in type so we are stuck with this
  49. def bit_length(x):
  50. return len(bin(x)) - 2
  51. else:
  52. def bit_length(x):
  53. return x.bit_length() or 1
  54. def orderlen(order):
  55. return (1 + len("%x" % order)) // 2 # bytes
  56. def randrange(order, entropy=None):
  57. """Return a random integer k such that 1 <= k < order, uniformly
  58. distributed across that range. Worst case should be a mean of 2 loops at
  59. (2**k)+2.
  60. Note that this function is not declared to be forwards-compatible: we may
  61. change the behavior in future releases. The entropy= argument (which
  62. should get a callable that behaves like os.urandom) can be used to
  63. achieve stability within a given release (for repeatable unit tests), but
  64. should not be used as a long-term-compatible key generation algorithm.
  65. """
  66. assert order > 1
  67. if entropy is None:
  68. entropy = os.urandom
  69. upper_2 = bit_length(order - 2)
  70. upper_256 = upper_2 // 8 + 1
  71. while True: # I don't think this needs a counter with bit-wise randrange
  72. ent_256 = entropy(upper_256)
  73. ent_2 = entropy_to_bits(ent_256)
  74. rand_num = int(ent_2[:upper_2], base=2) + 1
  75. if 0 < rand_num < order:
  76. return rand_num
  77. class PRNG:
  78. # this returns a callable which, when invoked with an integer N, will
  79. # return N pseudorandom bytes. Note: this is a short-term PRNG, meant
  80. # primarily for the needs of randrange_from_seed__trytryagain(), which
  81. # only needs to run it a few times per seed. It does not provide
  82. # protection against state compromise (forward security).
  83. def __init__(self, seed):
  84. self.generator = self.block_generator(seed)
  85. def __call__(self, numbytes):
  86. a = [next(self.generator) for i in range(numbytes)]
  87. if PY2: # pragma: no branch
  88. return "".join(a)
  89. else:
  90. return bytes(a)
  91. def block_generator(self, seed):
  92. counter = 0
  93. while True:
  94. for byte in sha256(
  95. ("prng-%d-%s" % (counter, seed)).encode()
  96. ).digest():
  97. yield byte
  98. counter += 1
  99. def randrange_from_seed__overshoot_modulo(seed, order):
  100. # hash the data, then turn the digest into a number in [1,order).
  101. #
  102. # We use David-Sarah Hopwood's suggestion: turn it into a number that's
  103. # sufficiently larger than the group order, then modulo it down to fit.
  104. # This should give adequate (but not perfect) uniformity, and simple
  105. # code. There are other choices: try-try-again is the main one.
  106. base = PRNG(seed)(2 * orderlen(order))
  107. number = (int(binascii.hexlify(base), 16) % (order - 1)) + 1
  108. assert 1 <= number < order, (1, number, order)
  109. return number
  110. def lsb_of_ones(numbits):
  111. return (1 << numbits) - 1
  112. def bits_and_bytes(order):
  113. bits = int(math.log(order - 1, 2) + 1)
  114. bytes = bits // 8
  115. extrabits = bits % 8
  116. return bits, bytes, extrabits
  117. # the following randrange_from_seed__METHOD() functions take an
  118. # arbitrarily-sized secret seed and turn it into a number that obeys the same
  119. # range limits as randrange() above. They are meant for deriving consistent
  120. # signing keys from a secret rather than generating them randomly, for
  121. # example a protocol in which three signing keys are derived from a master
  122. # secret. You should use a uniformly-distributed unguessable seed with about
  123. # curve.baselen bytes of entropy. To use one, do this:
  124. # seed = os.urandom(curve.baselen) # or other starting point
  125. # secexp = ecdsa.util.randrange_from_seed__trytryagain(sed, curve.order)
  126. # sk = SigningKey.from_secret_exponent(secexp, curve)
  127. def randrange_from_seed__truncate_bytes(seed, order, hashmod=sha256):
  128. # hash the seed, then turn the digest into a number in [1,order), but
  129. # don't worry about trying to uniformly fill the range. This will lose,
  130. # on average, four bits of entropy.
  131. bits, _bytes, extrabits = bits_and_bytes(order)
  132. if extrabits:
  133. _bytes += 1
  134. base = hashmod(seed).digest()[:_bytes]
  135. base = "\x00" * (_bytes - len(base)) + base
  136. number = 1 + int(binascii.hexlify(base), 16)
  137. assert 1 <= number < order
  138. return number
  139. def randrange_from_seed__truncate_bits(seed, order, hashmod=sha256):
  140. # like string_to_randrange_truncate_bytes, but only lose an average of
  141. # half a bit
  142. bits = int(math.log(order - 1, 2) + 1)
  143. maxbytes = (bits + 7) // 8
  144. base = hashmod(seed).digest()[:maxbytes]
  145. base = "\x00" * (maxbytes - len(base)) + base
  146. topbits = 8 * maxbytes - bits
  147. if topbits:
  148. base = int2byte(ord(base[0]) & lsb_of_ones(topbits)) + base[1:]
  149. number = 1 + int(binascii.hexlify(base), 16)
  150. assert 1 <= number < order
  151. return number
  152. def randrange_from_seed__trytryagain(seed, order):
  153. # figure out exactly how many bits we need (rounded up to the nearest
  154. # bit), so we can reduce the chance of looping to less than 0.5 . This is
  155. # specified to feed from a byte-oriented PRNG, and discards the
  156. # high-order bits of the first byte as necessary to get the right number
  157. # of bits. The average number of loops will range from 1.0 (when
  158. # order=2**k-1) to 2.0 (when order=2**k+1).
  159. assert order > 1
  160. bits, bytes, extrabits = bits_and_bytes(order)
  161. generate = PRNG(seed)
  162. while True:
  163. extrabyte = b""
  164. if extrabits:
  165. extrabyte = int2byte(ord(generate(1)) & lsb_of_ones(extrabits))
  166. guess = string_to_number(extrabyte + generate(bytes)) + 1
  167. if 1 <= guess < order:
  168. return guess
  169. def number_to_string(num, order):
  170. l = orderlen(order)
  171. fmt_str = "%0" + str(2 * l) + "x"
  172. string = binascii.unhexlify((fmt_str % num).encode())
  173. assert len(string) == l, (len(string), l)
  174. return string
  175. def number_to_string_crop(num, order):
  176. l = orderlen(order)
  177. fmt_str = "%0" + str(2 * l) + "x"
  178. string = binascii.unhexlify((fmt_str % num).encode())
  179. return string[:l]
  180. def string_to_number(string):
  181. return int(binascii.hexlify(string), 16)
  182. def string_to_number_fixedlen(string, order):
  183. l = orderlen(order)
  184. assert len(string) == l, (len(string), l)
  185. return int(binascii.hexlify(string), 16)
  186. def sigencode_strings(r, s, order):
  187. """
  188. Encode the signature to a pair of strings in a tuple
  189. Encodes signature into raw encoding (:term:`raw encoding`) with the
  190. ``r`` and ``s`` parts of the signature encoded separately.
  191. It's expected that this function will be used as a ``sigencode=`` parameter
  192. in :func:`ecdsa.keys.SigningKey.sign` method.
  193. :param int r: first parameter of the signature
  194. :param int s: second parameter of the signature
  195. :param int order: the order of the curve over which the signature was
  196. computed
  197. :return: raw encoding of ECDSA signature
  198. :rtype: tuple(bytes, bytes)
  199. """
  200. r_str = number_to_string(r, order)
  201. s_str = number_to_string(s, order)
  202. return (r_str, s_str)
  203. def sigencode_string(r, s, order):
  204. """
  205. Encode the signature to raw format (:term:`raw encoding`)
  206. It's expected that this function will be used as a ``sigencode=`` parameter
  207. in :func:`ecdsa.keys.SigningKey.sign` method.
  208. :param int r: first parameter of the signature
  209. :param int s: second parameter of the signature
  210. :param int order: the order of the curve over which the signature was
  211. computed
  212. :return: raw encoding of ECDSA signature
  213. :rtype: bytes
  214. """
  215. # for any given curve, the size of the signature numbers is
  216. # fixed, so just use simple concatenation
  217. r_str, s_str = sigencode_strings(r, s, order)
  218. return r_str + s_str
  219. def sigencode_der(r, s, order):
  220. """
  221. Encode the signature into the ECDSA-Sig-Value structure using :term:`DER`.
  222. Encodes the signature to the following :term:`ASN.1` structure::
  223. Ecdsa-Sig-Value ::= SEQUENCE {
  224. r INTEGER,
  225. s INTEGER
  226. }
  227. It's expected that this function will be used as a ``sigencode=`` parameter
  228. in :func:`ecdsa.keys.SigningKey.sign` method.
  229. :param int r: first parameter of the signature
  230. :param int s: second parameter of the signature
  231. :param int order: the order of the curve over which the signature was
  232. computed
  233. :return: DER encoding of ECDSA signature
  234. :rtype: bytes
  235. """
  236. return der.encode_sequence(der.encode_integer(r), der.encode_integer(s))
  237. def _canonize(s, order):
  238. """
  239. Internal function for ensuring that the ``s`` value of a signature is in
  240. the "canonical" format.
  241. :param int s: the second parameter of ECDSA signature
  242. :param int order: the order of the curve over which the signatures was
  243. computed
  244. :return: canonical value of s
  245. :rtype: int
  246. """
  247. if s > order // 2:
  248. s = order - s
  249. return s
  250. def sigencode_strings_canonize(r, s, order):
  251. """
  252. Encode the signature to a pair of strings in a tuple
  253. Encodes signature into raw encoding (:term:`raw encoding`) with the
  254. ``r`` and ``s`` parts of the signature encoded separately.
  255. Makes sure that the signature is encoded in the canonical format, where
  256. the ``s`` parameter is always smaller than ``order / 2``.
  257. Most commonly used in bitcoin.
  258. It's expected that this function will be used as a ``sigencode=`` parameter
  259. in :func:`ecdsa.keys.SigningKey.sign` method.
  260. :param int r: first parameter of the signature
  261. :param int s: second parameter of the signature
  262. :param int order: the order of the curve over which the signature was
  263. computed
  264. :return: raw encoding of ECDSA signature
  265. :rtype: tuple(bytes, bytes)
  266. """
  267. s = _canonize(s, order)
  268. return sigencode_strings(r, s, order)
  269. def sigencode_string_canonize(r, s, order):
  270. """
  271. Encode the signature to raw format (:term:`raw encoding`)
  272. Makes sure that the signature is encoded in the canonical format, where
  273. the ``s`` parameter is always smaller than ``order / 2``.
  274. Most commonly used in bitcoin.
  275. It's expected that this function will be used as a ``sigencode=`` parameter
  276. in :func:`ecdsa.keys.SigningKey.sign` method.
  277. :param int r: first parameter of the signature
  278. :param int s: second parameter of the signature
  279. :param int order: the order of the curve over which the signature was
  280. computed
  281. :return: raw encoding of ECDSA signature
  282. :rtype: bytes
  283. """
  284. s = _canonize(s, order)
  285. return sigencode_string(r, s, order)
  286. def sigencode_der_canonize(r, s, order):
  287. """
  288. Encode the signature into the ECDSA-Sig-Value structure using :term:`DER`.
  289. Makes sure that the signature is encoded in the canonical format, where
  290. the ``s`` parameter is always smaller than ``order / 2``.
  291. Most commonly used in bitcoin.
  292. Encodes the signature to the following :term:`ASN.1` structure::
  293. Ecdsa-Sig-Value ::= SEQUENCE {
  294. r INTEGER,
  295. s INTEGER
  296. }
  297. It's expected that this function will be used as a ``sigencode=`` parameter
  298. in :func:`ecdsa.keys.SigningKey.sign` method.
  299. :param int r: first parameter of the signature
  300. :param int s: second parameter of the signature
  301. :param int order: the order of the curve over which the signature was
  302. computed
  303. :return: DER encoding of ECDSA signature
  304. :rtype: bytes
  305. """
  306. s = _canonize(s, order)
  307. return sigencode_der(r, s, order)
  308. class MalformedSignature(Exception):
  309. """
  310. Raised by decoding functions when the signature is malformed.
  311. Malformed in this context means that the relevant strings or integers
  312. do not match what a signature over provided curve would create. Either
  313. because the byte strings have incorrect lengths or because the encoded
  314. values are too large.
  315. """
  316. pass
  317. def sigdecode_string(signature, order):
  318. """
  319. Decoder for :term:`raw encoding` of ECDSA signatures.
  320. raw encoding is a simple concatenation of the two integers that comprise
  321. the signature, with each encoded using the same amount of bytes depending
  322. on curve size/order.
  323. It's expected that this function will be used as the ``sigdecode=``
  324. parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method.
  325. :param signature: encoded signature
  326. :type signature: bytes like object
  327. :param order: order of the curve over which the signature was computed
  328. :type order: int
  329. :raises MalformedSignature: when the encoding of the signature is invalid
  330. :return: tuple with decoded ``r`` and ``s`` values of signature
  331. :rtype: tuple of ints
  332. """
  333. signature = normalise_bytes(signature)
  334. l = orderlen(order)
  335. if not len(signature) == 2 * l:
  336. raise MalformedSignature(
  337. "Invalid length of signature, expected {0} bytes long, "
  338. "provided string is {1} bytes long".format(2 * l, len(signature))
  339. )
  340. r = string_to_number_fixedlen(signature[:l], order)
  341. s = string_to_number_fixedlen(signature[l:], order)
  342. return r, s
  343. def sigdecode_strings(rs_strings, order):
  344. """
  345. Decode the signature from two strings.
  346. First string needs to be a big endian encoding of ``r``, second needs to
  347. be a big endian encoding of the ``s`` parameter of an ECDSA signature.
  348. It's expected that this function will be used as the ``sigdecode=``
  349. parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method.
  350. :param list rs_strings: list of two bytes-like objects, each encoding one
  351. parameter of signature
  352. :param int order: order of the curve over which the signature was computed
  353. :raises MalformedSignature: when the encoding of the signature is invalid
  354. :return: tuple with decoded ``r`` and ``s`` values of signature
  355. :rtype: tuple of ints
  356. """
  357. if not len(rs_strings) == 2:
  358. raise MalformedSignature(
  359. "Invalid number of strings provided: {0}, expected 2".format(
  360. len(rs_strings)
  361. )
  362. )
  363. (r_str, s_str) = rs_strings
  364. r_str = normalise_bytes(r_str)
  365. s_str = normalise_bytes(s_str)
  366. l = orderlen(order)
  367. if not len(r_str) == l:
  368. raise MalformedSignature(
  369. "Invalid length of first string ('r' parameter), "
  370. "expected {0} bytes long, provided string is {1} "
  371. "bytes long".format(l, len(r_str))
  372. )
  373. if not len(s_str) == l:
  374. raise MalformedSignature(
  375. "Invalid length of second string ('s' parameter), "
  376. "expected {0} bytes long, provided string is {1} "
  377. "bytes long".format(l, len(s_str))
  378. )
  379. r = string_to_number_fixedlen(r_str, order)
  380. s = string_to_number_fixedlen(s_str, order)
  381. return r, s
  382. def sigdecode_der(sig_der, order):
  383. """
  384. Decoder for DER format of ECDSA signatures.
  385. DER format of signature is one that uses the :term:`ASN.1` :term:`DER`
  386. rules to encode it as a sequence of two integers::
  387. Ecdsa-Sig-Value ::= SEQUENCE {
  388. r INTEGER,
  389. s INTEGER
  390. }
  391. It's expected that this function will be used as as the ``sigdecode=``
  392. parameter to the :func:`ecdsa.keys.VerifyingKey.verify` method.
  393. :param sig_der: encoded signature
  394. :type sig_der: bytes like object
  395. :param order: order of the curve over which the signature was computed
  396. :type order: int
  397. :raises UnexpectedDER: when the encoding of signature is invalid
  398. :return: tuple with decoded ``r`` and ``s`` values of signature
  399. :rtype: tuple of ints
  400. """
  401. sig_der = normalise_bytes(sig_der)
  402. # return der.encode_sequence(der.encode_integer(r), der.encode_integer(s))
  403. rs_strings, empty = der.remove_sequence(sig_der)
  404. if empty != b"":
  405. raise der.UnexpectedDER(
  406. "trailing junk after DER sig: %s" % binascii.hexlify(empty)
  407. )
  408. r, rest = der.remove_integer(rs_strings)
  409. s, empty = der.remove_integer(rest)
  410. if empty != b"":
  411. raise der.UnexpectedDER(
  412. "trailing junk after DER numbers: %s" % binascii.hexlify(empty)
  413. )
  414. return r, s