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

486 行
16 KiB

  1. # Copyright 2011 Sybren A. Stüvel <sybren@stuvel.eu>
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # https://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Functions for PKCS#1 version 1.5 encryption and signing
  15. This module implements certain functionality from PKCS#1 version 1.5. For a
  16. very clear example, read http://www.di-mgt.com.au/rsa_alg.html#pkcs1schemes
  17. At least 8 bytes of random padding is used when encrypting a message. This makes
  18. these methods much more secure than the ones in the ``rsa`` module.
  19. WARNING: this module leaks information when decryption fails. The exceptions
  20. that are raised contain the Python traceback information, which can be used to
  21. deduce where in the process the failure occurred. DO NOT PASS SUCH INFORMATION
  22. to your users.
  23. """
  24. import hashlib
  25. import os
  26. import sys
  27. import typing
  28. from hmac import compare_digest
  29. from . import common, transform, core, key
  30. if typing.TYPE_CHECKING:
  31. HashType = hashlib._Hash
  32. else:
  33. HashType = typing.Any
  34. # ASN.1 codes that describe the hash algorithm used.
  35. HASH_ASN1 = {
  36. "MD5": b"\x30\x20\x30\x0c\x06\x08\x2a\x86\x48\x86\xf7\x0d\x02\x05\x05\x00\x04\x10",
  37. "SHA-1": b"\x30\x21\x30\x09\x06\x05\x2b\x0e\x03\x02\x1a\x05\x00\x04\x14",
  38. "SHA-224": b"\x30\x2d\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x04\x05\x00\x04\x1c",
  39. "SHA-256": b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x01\x05\x00\x04\x20",
  40. "SHA-384": b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x02\x05\x00\x04\x30",
  41. "SHA-512": b"\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x03\x05\x00\x04\x40",
  42. }
  43. HASH_METHODS: typing.Dict[str, typing.Callable[[], HashType]] = {
  44. "MD5": hashlib.md5,
  45. "SHA-1": hashlib.sha1,
  46. "SHA-224": hashlib.sha224,
  47. "SHA-256": hashlib.sha256,
  48. "SHA-384": hashlib.sha384,
  49. "SHA-512": hashlib.sha512,
  50. }
  51. """Hash methods supported by this library."""
  52. if sys.version_info >= (3, 6):
  53. # Python 3.6 introduced SHA3 support.
  54. HASH_ASN1.update(
  55. {
  56. "SHA3-256": b"\x30\x31\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x08\x05\x00\x04\x20",
  57. "SHA3-384": b"\x30\x41\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x09\x05\x00\x04\x30",
  58. "SHA3-512": b"\x30\x51\x30\x0d\x06\x09\x60\x86\x48\x01\x65\x03\x04\x02\x0a\x05\x00\x04\x40",
  59. }
  60. )
  61. HASH_METHODS.update(
  62. {
  63. "SHA3-256": hashlib.sha3_256,
  64. "SHA3-384": hashlib.sha3_384,
  65. "SHA3-512": hashlib.sha3_512,
  66. }
  67. )
  68. class CryptoError(Exception):
  69. """Base class for all exceptions in this module."""
  70. class DecryptionError(CryptoError):
  71. """Raised when decryption fails."""
  72. class VerificationError(CryptoError):
  73. """Raised when verification fails."""
  74. def _pad_for_encryption(message: bytes, target_length: int) -> bytes:
  75. r"""Pads the message for encryption, returning the padded message.
  76. :return: 00 02 RANDOM_DATA 00 MESSAGE
  77. >>> block = _pad_for_encryption(b'hello', 16)
  78. >>> len(block)
  79. 16
  80. >>> block[0:2]
  81. b'\x00\x02'
  82. >>> block[-6:]
  83. b'\x00hello'
  84. """
  85. max_msglength = target_length - 11
  86. msglength = len(message)
  87. if msglength > max_msglength:
  88. raise OverflowError(
  89. "%i bytes needed for message, but there is only"
  90. " space for %i" % (msglength, max_msglength)
  91. )
  92. # Get random padding
  93. padding = b""
  94. padding_length = target_length - msglength - 3
  95. # We remove 0-bytes, so we'll end up with less padding than we've asked for,
  96. # so keep adding data until we're at the correct length.
  97. while len(padding) < padding_length:
  98. needed_bytes = padding_length - len(padding)
  99. # Always read at least 8 bytes more than we need, and trim off the rest
  100. # after removing the 0-bytes. This increases the chance of getting
  101. # enough bytes, especially when needed_bytes is small
  102. new_padding = os.urandom(needed_bytes + 5)
  103. new_padding = new_padding.replace(b"\x00", b"")
  104. padding = padding + new_padding[:needed_bytes]
  105. assert len(padding) == padding_length
  106. return b"".join([b"\x00\x02", padding, b"\x00", message])
  107. def _pad_for_signing(message: bytes, target_length: int) -> bytes:
  108. r"""Pads the message for signing, returning the padded message.
  109. The padding is always a repetition of FF bytes.
  110. :return: 00 01 PADDING 00 MESSAGE
  111. >>> block = _pad_for_signing(b'hello', 16)
  112. >>> len(block)
  113. 16
  114. >>> block[0:2]
  115. b'\x00\x01'
  116. >>> block[-6:]
  117. b'\x00hello'
  118. >>> block[2:-6]
  119. b'\xff\xff\xff\xff\xff\xff\xff\xff'
  120. """
  121. max_msglength = target_length - 11
  122. msglength = len(message)
  123. if msglength > max_msglength:
  124. raise OverflowError(
  125. "%i bytes needed for message, but there is only"
  126. " space for %i" % (msglength, max_msglength)
  127. )
  128. padding_length = target_length - msglength - 3
  129. return b"".join([b"\x00\x01", padding_length * b"\xff", b"\x00", message])
  130. def encrypt(message: bytes, pub_key: key.PublicKey) -> bytes:
  131. """Encrypts the given message using PKCS#1 v1.5
  132. :param message: the message to encrypt. Must be a byte string no longer than
  133. ``k-11`` bytes, where ``k`` is the number of bytes needed to encode
  134. the ``n`` component of the public key.
  135. :param pub_key: the :py:class:`rsa.PublicKey` to encrypt with.
  136. :raise OverflowError: when the message is too large to fit in the padded
  137. block.
  138. >>> from rsa import key, common
  139. >>> (pub_key, priv_key) = key.newkeys(256)
  140. >>> message = b'hello'
  141. >>> crypto = encrypt(message, pub_key)
  142. The crypto text should be just as long as the public key 'n' component:
  143. >>> len(crypto) == common.byte_size(pub_key.n)
  144. True
  145. """
  146. keylength = common.byte_size(pub_key.n)
  147. padded = _pad_for_encryption(message, keylength)
  148. payload = transform.bytes2int(padded)
  149. encrypted = core.encrypt_int(payload, pub_key.e, pub_key.n)
  150. block = transform.int2bytes(encrypted, keylength)
  151. return block
  152. def decrypt(crypto: bytes, priv_key: key.PrivateKey) -> bytes:
  153. r"""Decrypts the given message using PKCS#1 v1.5
  154. The decryption is considered 'failed' when the resulting cleartext doesn't
  155. start with the bytes 00 02, or when the 00 byte between the padding and
  156. the message cannot be found.
  157. :param crypto: the crypto text as returned by :py:func:`rsa.encrypt`
  158. :param priv_key: the :py:class:`rsa.PrivateKey` to decrypt with.
  159. :raise DecryptionError: when the decryption fails. No details are given as
  160. to why the code thinks the decryption fails, as this would leak
  161. information about the private key.
  162. >>> import rsa
  163. >>> (pub_key, priv_key) = rsa.newkeys(256)
  164. It works with strings:
  165. >>> crypto = encrypt(b'hello', pub_key)
  166. >>> decrypt(crypto, priv_key)
  167. b'hello'
  168. And with binary data:
  169. >>> crypto = encrypt(b'\x00\x00\x00\x00\x01', pub_key)
  170. >>> decrypt(crypto, priv_key)
  171. b'\x00\x00\x00\x00\x01'
  172. Altering the encrypted information will *likely* cause a
  173. :py:class:`rsa.pkcs1.DecryptionError`. If you want to be *sure*, use
  174. :py:func:`rsa.sign`.
  175. .. warning::
  176. Never display the stack trace of a
  177. :py:class:`rsa.pkcs1.DecryptionError` exception. It shows where in the
  178. code the exception occurred, and thus leaks information about the key.
  179. It's only a tiny bit of information, but every bit makes cracking the
  180. keys easier.
  181. >>> crypto = encrypt(b'hello', pub_key)
  182. >>> crypto = crypto[0:5] + b'X' + crypto[6:] # change a byte
  183. >>> decrypt(crypto, priv_key)
  184. Traceback (most recent call last):
  185. ...
  186. rsa.pkcs1.DecryptionError: Decryption failed
  187. """
  188. blocksize = common.byte_size(priv_key.n)
  189. encrypted = transform.bytes2int(crypto)
  190. decrypted = priv_key.blinded_decrypt(encrypted)
  191. cleartext = transform.int2bytes(decrypted, blocksize)
  192. # Detect leading zeroes in the crypto. These are not reflected in the
  193. # encrypted value (as leading zeroes do not influence the value of an
  194. # integer). This fixes CVE-2020-13757.
  195. if len(crypto) > blocksize:
  196. # This is operating on public information, so doesn't need to be constant-time.
  197. raise DecryptionError("Decryption failed")
  198. # If we can't find the cleartext marker, decryption failed.
  199. cleartext_marker_bad = not compare_digest(cleartext[:2], b"\x00\x02")
  200. # Find the 00 separator between the padding and the message
  201. sep_idx = cleartext.find(b"\x00", 2)
  202. # sep_idx indicates the position of the `\x00` separator that separates the
  203. # padding from the actual message. The padding should be at least 8 bytes
  204. # long (see https://tools.ietf.org/html/rfc8017#section-7.2.2 step 3), which
  205. # means the separator should be at least at index 10 (because of the
  206. # `\x00\x02` marker that precedes it).
  207. sep_idx_bad = sep_idx < 10
  208. anything_bad = cleartext_marker_bad | sep_idx_bad
  209. if anything_bad:
  210. raise DecryptionError("Decryption failed")
  211. return cleartext[sep_idx + 1 :]
  212. def sign_hash(hash_value: bytes, priv_key: key.PrivateKey, hash_method: str) -> bytes:
  213. """Signs a precomputed hash with the private key.
  214. Hashes the message, then signs the hash with the given key. This is known
  215. as a "detached signature", because the message itself isn't altered.
  216. :param hash_value: A precomputed hash to sign (ignores message).
  217. :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
  218. :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1',
  219. 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'.
  220. :return: a message signature block.
  221. :raise OverflowError: if the private key is too small to contain the
  222. requested hash.
  223. """
  224. # Get the ASN1 code for this hash method
  225. if hash_method not in HASH_ASN1:
  226. raise ValueError("Invalid hash method: %s" % hash_method)
  227. asn1code = HASH_ASN1[hash_method]
  228. # Encrypt the hash with the private key
  229. cleartext = asn1code + hash_value
  230. keylength = common.byte_size(priv_key.n)
  231. padded = _pad_for_signing(cleartext, keylength)
  232. payload = transform.bytes2int(padded)
  233. encrypted = priv_key.blinded_encrypt(payload)
  234. block = transform.int2bytes(encrypted, keylength)
  235. return block
  236. def sign(message: bytes, priv_key: key.PrivateKey, hash_method: str) -> bytes:
  237. """Signs the message with the private key.
  238. Hashes the message, then signs the hash with the given key. This is known
  239. as a "detached signature", because the message itself isn't altered.
  240. :param message: the message to sign. Can be an 8-bit string or a file-like
  241. object. If ``message`` has a ``read()`` method, it is assumed to be a
  242. file-like object.
  243. :param priv_key: the :py:class:`rsa.PrivateKey` to sign with
  244. :param hash_method: the hash method used on the message. Use 'MD5', 'SHA-1',
  245. 'SHA-224', SHA-256', 'SHA-384' or 'SHA-512'.
  246. :return: a message signature block.
  247. :raise OverflowError: if the private key is too small to contain the
  248. requested hash.
  249. """
  250. msg_hash = compute_hash(message, hash_method)
  251. return sign_hash(msg_hash, priv_key, hash_method)
  252. def verify(message: bytes, signature: bytes, pub_key: key.PublicKey) -> str:
  253. """Verifies that the signature matches the message.
  254. The hash method is detected automatically from the signature.
  255. :param message: the signed message. Can be an 8-bit string or a file-like
  256. object. If ``message`` has a ``read()`` method, it is assumed to be a
  257. file-like object.
  258. :param signature: the signature block, as created with :py:func:`rsa.sign`.
  259. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
  260. :raise VerificationError: when the signature doesn't match the message.
  261. :returns: the name of the used hash.
  262. """
  263. keylength = common.byte_size(pub_key.n)
  264. encrypted = transform.bytes2int(signature)
  265. decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
  266. clearsig = transform.int2bytes(decrypted, keylength)
  267. # Get the hash method
  268. method_name = _find_method_hash(clearsig)
  269. message_hash = compute_hash(message, method_name)
  270. # Reconstruct the expected padded hash
  271. cleartext = HASH_ASN1[method_name] + message_hash
  272. expected = _pad_for_signing(cleartext, keylength)
  273. if len(signature) != keylength:
  274. raise VerificationError("Verification failed")
  275. # Compare with the signed one
  276. if expected != clearsig:
  277. raise VerificationError("Verification failed")
  278. return method_name
  279. def find_signature_hash(signature: bytes, pub_key: key.PublicKey) -> str:
  280. """Returns the hash name detected from the signature.
  281. If you also want to verify the message, use :py:func:`rsa.verify()` instead.
  282. It also returns the name of the used hash.
  283. :param signature: the signature block, as created with :py:func:`rsa.sign`.
  284. :param pub_key: the :py:class:`rsa.PublicKey` of the person signing the message.
  285. :returns: the name of the used hash.
  286. """
  287. keylength = common.byte_size(pub_key.n)
  288. encrypted = transform.bytes2int(signature)
  289. decrypted = core.decrypt_int(encrypted, pub_key.e, pub_key.n)
  290. clearsig = transform.int2bytes(decrypted, keylength)
  291. return _find_method_hash(clearsig)
  292. def yield_fixedblocks(infile: typing.BinaryIO, blocksize: int) -> typing.Iterator[bytes]:
  293. """Generator, yields each block of ``blocksize`` bytes in the input file.
  294. :param infile: file to read and separate in blocks.
  295. :param blocksize: block size in bytes.
  296. :returns: a generator that yields the contents of each block
  297. """
  298. while True:
  299. block = infile.read(blocksize)
  300. read_bytes = len(block)
  301. if read_bytes == 0:
  302. break
  303. yield block
  304. if read_bytes < blocksize:
  305. break
  306. def compute_hash(message: typing.Union[bytes, typing.BinaryIO], method_name: str) -> bytes:
  307. """Returns the message digest.
  308. :param message: the signed message. Can be an 8-bit string or a file-like
  309. object. If ``message`` has a ``read()`` method, it is assumed to be a
  310. file-like object.
  311. :param method_name: the hash method, must be a key of
  312. :py:const:`rsa.pkcs1.HASH_METHODS`.
  313. """
  314. if method_name not in HASH_METHODS:
  315. raise ValueError("Invalid hash method: %s" % method_name)
  316. method = HASH_METHODS[method_name]
  317. hasher = method()
  318. if isinstance(message, bytes):
  319. hasher.update(message)
  320. else:
  321. assert hasattr(message, "read") and hasattr(message.read, "__call__")
  322. # read as 1K blocks
  323. for block in yield_fixedblocks(message, 1024):
  324. hasher.update(block)
  325. return hasher.digest()
  326. def _find_method_hash(clearsig: bytes) -> str:
  327. """Finds the hash method.
  328. :param clearsig: full padded ASN1 and hash.
  329. :return: the used hash method.
  330. :raise VerificationFailed: when the hash method cannot be found
  331. """
  332. for (hashname, asn1code) in HASH_ASN1.items():
  333. if asn1code in clearsig:
  334. return hashname
  335. raise VerificationError("Verification failed")
  336. __all__ = [
  337. "encrypt",
  338. "decrypt",
  339. "sign",
  340. "verify",
  341. "DecryptionError",
  342. "VerificationError",
  343. "CryptoError",
  344. ]
  345. if __name__ == "__main__":
  346. print("Running doctests 1000x or until failure")
  347. import doctest
  348. for count in range(1000):
  349. (failures, tests) = doctest.testmod()
  350. if failures:
  351. break
  352. if count % 100 == 0 and count:
  353. print("%i times" % count)
  354. print("Doctests done")