setup.py 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610
  1. #! /usr/bin/env python
  2. #
  3. # setup.py : Distutils setup script
  4. #
  5. # ===================================================================
  6. # The contents of this file are dedicated to the public domain. To
  7. # the extent that dedication to the public domain is not available,
  8. # everyone is granted a worldwide, perpetual, royalty-free,
  9. # non-exclusive license to exercise all rights associated with the
  10. # contents of this file for any purpose whatsoever.
  11. # No rights are reserved.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  14. # EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  15. # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  16. # NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
  17. # BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
  18. # ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
  19. # CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  20. # SOFTWARE.
  21. # ===================================================================
  22. try:
  23. from setuptools import Extension, Command, setup
  24. except ImportError:
  25. from distutils.core import Extension, Command, setup
  26. from distutils.command.build_ext import build_ext
  27. from distutils.command.build import build
  28. from distutils.command.install_lib import install_lib
  29. from distutils.errors import CCompilerError
  30. import distutils
  31. import re, os, sys, shutil
  32. use_separate_namespace = os.path.isfile(".separate_namespace")
  33. project_name = "pycryptodome"
  34. package_root = "Crypto"
  35. other_project = "pycryptodomex"
  36. other_root = "Cryptodome"
  37. if use_separate_namespace:
  38. project_name, other_project = other_project, project_name
  39. package_root, other_root = other_root, package_root
  40. longdesc = """
  41. PyCryptodome
  42. ============
  43. PyCryptodome is a self-contained Python package of low-level
  44. cryptographic primitives.
  45. It supports Python 2.4 or newer, all Python 3 versions and PyPy.
  46. You can install it with::
  47. pip install THIS_PROJECT
  48. All modules are installed under the ``THIS_ROOT`` package.
  49. Check the OTHER_PROJECT_ project for the equivalent library that
  50. works under the ``OTHER_ROOT`` package.
  51. PyCryptodome is a fork of PyCrypto. It brings several enhancements
  52. with respect to the last official version of PyCrypto (2.6.1),
  53. for instance:
  54. * Authenticated encryption modes (GCM, CCM, EAX, SIV, OCB)
  55. * Accelerated AES on Intel platforms via AES-NI
  56. * First class support for PyPy
  57. * Elliptic curves cryptography (NIST P-256 curve only)
  58. * Better and more compact API (`nonce` and `iv` attributes for ciphers,
  59. automatic generation of random nonces and IVs, simplified CTR cipher mode,
  60. and more)
  61. * SHA-3 (including SHAKE XOFs) and BLAKE2 hash algorithms
  62. * Salsa20 and ChaCha20 stream ciphers
  63. * scrypt and HKDF
  64. * Deterministic (EC)DSA
  65. * Password-protected PKCS#8 key containers
  66. * Shamir's Secret Sharing scheme
  67. * Random numbers get sourced directly from the OS (and not from a CSPRNG in userspace)
  68. * Simplified install process, including better support for Windows
  69. * Cleaner RSA and DSA key generation (largely based on FIPS 186-4)
  70. * Major clean ups and simplification of the code base
  71. PyCryptodome is not a wrapper to a separate C library like *OpenSSL*.
  72. To the largest possible extent, algorithms are implemented in pure Python.
  73. Only the pieces that are extremely critical to performance (e.g. block ciphers)
  74. are implemented as C extensions.
  75. For more information, see the `homepage`_.
  76. All the code can be downloaded from `GitHub`_.
  77. .. _OTHER_PROJECT: https://pypi.python.org/pypi/OTHER_PROJECT
  78. .. _`homepage`: http://www.pycryptodome.org
  79. .. _GitHub: https://github.com/Legrandin/pycryptodome
  80. """.replace("THIS_PROJECT", project_name).\
  81. replace("THIS_ROOT", package_root).\
  82. replace("OTHER_PROJECT", other_project).\
  83. replace("OTHER_ROOT", other_root)
  84. # By doing this we neeed to change version information in a single file
  85. for line in open(os.path.join("lib", "Crypto", "__init__.py")):
  86. if line.startswith("version_info"):
  87. version_tuple = eval(line.split("=")[1])
  88. version_string = "%d.%d" % version_tuple[:-1]
  89. if version_tuple[2] is not None:
  90. if str(version_tuple[2]).isdigit():
  91. version_string += "."
  92. version_string += str(version_tuple[2])
  93. if sys.version[0:1] == '1':
  94. raise RuntimeError ("The Python Cryptography Toolkit requires "
  95. "Python 2.x or 3.x to build.")
  96. try:
  97. # Python 3
  98. from distutils.command.build_py import build_py_2to3 as build_py
  99. except ImportError:
  100. # Python 2
  101. from distutils.command.build_py import build_py
  102. # Work around the print / print() issue with Python 2.x and 3.x. We only need
  103. # to print at one point of the code, which makes this easy
  104. def PrintErr(*args, **kwd):
  105. fout = kwd.get("file", sys.stderr)
  106. w = fout.write
  107. if args:
  108. w(str(args[0]))
  109. sep = kwd.get("sep", " ")
  110. for a in args[1:]:
  111. w(sep)
  112. w(str(a))
  113. w(kwd.get("end", "\n"))
  114. def test_compilation(program, extra_cc_options=None, extra_libraries=None):
  115. """Test if a certain C program can be compiled."""
  116. # Create a temporary file with the C program
  117. if not os.path.exists("build"):
  118. os.makedirs("build")
  119. fname = os.path.join("build", "test1.c")
  120. f = open(fname, 'w')
  121. f.write(program)
  122. f.close()
  123. # Name for the temporary executable
  124. oname = os.path.join("build", "test1.out")
  125. debug = False
  126. # Mute the compiler and the linker
  127. if not debug:
  128. old_stdout = os.dup(sys.stdout.fileno())
  129. old_stderr = os.dup(sys.stderr.fileno())
  130. dev_null = open(os.devnull, "w")
  131. os.dup2(dev_null.fileno(), sys.stdout.fileno())
  132. os.dup2(dev_null.fileno(), sys.stderr.fileno())
  133. objects = []
  134. try:
  135. compiler = distutils.ccompiler.new_compiler()
  136. if compiler.compiler_type in [ 'msvc' ]:
  137. # Force creation of the manifest file (http://bugs.python.org/issue16296)
  138. # as needed by VS2010
  139. extra_linker_options = [ "/MANIFEST" ]
  140. else:
  141. extra_linker_options = []
  142. distutils.sysconfig.customize_compiler(compiler)
  143. objects = compiler.compile([fname], extra_postargs=extra_cc_options)
  144. compiler.link_executable(objects, oname, libraries=extra_libraries, extra_preargs=extra_linker_options)
  145. result = True
  146. except CCompilerError:
  147. result = False
  148. for f in objects + [fname, oname]:
  149. try:
  150. os.remove(f)
  151. except OSError:
  152. pass
  153. # Restore stdout and stderr
  154. if not debug:
  155. if old_stdout is not None:
  156. os.dup2(old_stdout, sys.stdout.fileno())
  157. if old_stderr is not None:
  158. os.dup2(old_stderr, sys.stderr.fileno())
  159. if dev_null is not None:
  160. dev_null.close()
  161. return result
  162. def change_module_name(file_name):
  163. """Change any occurrance of 'Crypto' to 'Cryptodome'."""
  164. fd = open(file_name, "rt")
  165. content = (fd.read().
  166. replace("Crypto.", "Cryptodome.").
  167. replace("Crypto ", "Cryptodome ").
  168. replace("'Crypto'", "'Cryptodome'").
  169. replace('"Crypto"', '"Cryptodome"'))
  170. fd.close()
  171. os.remove(file_name)
  172. fd = open(file_name, "wt")
  173. fd.write(content)
  174. fd.close()
  175. def rename_crypto_dir(build_lib):
  176. """Move all files from the 'Crypto' package to the
  177. 'Cryptodome' package in the given build directory"""
  178. source = os.path.join(build_lib, "Crypto")
  179. target = os.path.join(build_lib, "Cryptodome")
  180. if not os.path.exists(target):
  181. PrintErr("Creating directory %s" % target)
  182. os.makedirs(target)
  183. else:
  184. PrintErr("Directory %s already exists" % target)
  185. # Crypto package becomes Cryptodome
  186. for root_src, dirs, files in os.walk(source):
  187. root_dst, nr_repl = re.subn('Crypto', 'Cryptodome', root_src)
  188. assert nr_repl == 1
  189. for dir_name in dirs:
  190. full_dir_name_dst = os.path.join(root_dst, dir_name)
  191. if not os.path.exists(full_dir_name_dst):
  192. os.makedirs(full_dir_name_dst)
  193. for file_name in files:
  194. full_file_name_src = os.path.join(root_src, file_name)
  195. full_file_name_dst = os.path.join(root_dst, file_name)
  196. PrintErr("Copying file %s to %s" % (full_file_name_src, full_file_name_dst))
  197. shutil.copy2(full_file_name_src, full_file_name_dst)
  198. if file_name.endswith(".py"):
  199. change_module_name(full_file_name_dst)
  200. class PCTBuildExt (build_ext):
  201. aesni_mod_names = "Crypto.Cipher._raw_aesni",
  202. def run(self):
  203. build_ext.run(self)
  204. if use_separate_namespace:
  205. rename_crypto_dir(self.build_lib)
  206. # Clean-up (extensions are built last)
  207. crypto_dir = os.path.join(self.build_lib, "Crypto")
  208. PrintErr("Deleting directory %s" % crypto_dir)
  209. shutil.rmtree(crypto_dir)
  210. def build_extensions(self):
  211. # Disable any assembly in libtomcrypt files
  212. self.compiler.define_macro("LTC_NO_ASM")
  213. # Detect which modules should be compiled
  214. self.detect_modules()
  215. # Call the superclass's build_extensions method
  216. build_ext.build_extensions(self)
  217. def check_cpuid_h(self):
  218. # UNIX
  219. source = """
  220. #include <cpuid.h>
  221. int main(void)
  222. {
  223. unsigned int eax, ebx, ecx, edx;
  224. __get_cpuid(1, &eax, &ebx, &ecx, &edx);
  225. return 0;
  226. }
  227. """
  228. if test_compilation(source):
  229. self.compiler.define_macro("HAVE_CPUID_H")
  230. return True
  231. else:
  232. return False
  233. def check_intrin_h(self):
  234. # Windows
  235. source = """
  236. #include <intrin.h>
  237. int main(void)
  238. {
  239. int a, b[4];
  240. __cpuid(b, a);
  241. return 0;
  242. }
  243. """
  244. if test_compilation(source):
  245. self.compiler.define_macro("HAVE_INTRIN_H")
  246. return True
  247. else:
  248. return False
  249. def check_aesni(self):
  250. source = """
  251. #include <wmmintrin.h>
  252. __m128i f(__m128i x, __m128i y) {
  253. return _mm_aesenc_si128(x, y);
  254. }
  255. int main(void) {
  256. return 0;
  257. }
  258. """
  259. aes_mods = [ x for x in self.extensions if x.name in self.aesni_mod_names ]
  260. result = test_compilation(source)
  261. if not result:
  262. result = test_compilation(source, extra_cc_options=['-maes'])
  263. if result:
  264. for x in aes_mods:
  265. x.extra_compile_args += ['-maes']
  266. return result
  267. def detect_modules (self):
  268. # Detect compiler support for CPUID instruction and AESNI
  269. if (self.check_cpuid_h() or self.check_intrin_h()) and self.check_aesni():
  270. PrintErr("Compiling support for Intel AES instructions")
  271. else:
  272. PrintErr ("warning: no support for Intel AESNI instructions")
  273. self.remove_extensions(self.aesni_mod_names)
  274. def remove_extensions(self, names):
  275. """Remove the specified extension from the list of extensions
  276. to build"""
  277. self.extensions = [ x for x in self.extensions if x.name not in names ]
  278. class PCTBuildPy(build_py):
  279. def find_package_modules(self, package, package_dir, *args, **kwargs):
  280. modules = build_py.find_package_modules(self, package, package_dir,
  281. *args, **kwargs)
  282. # Exclude certain modules
  283. retval = []
  284. for item in modules:
  285. pkg, module = item[:2]
  286. retval.append(item)
  287. return retval
  288. def run(self):
  289. build_py.run(self)
  290. if use_separate_namespace:
  291. rename_crypto_dir(self.build_lib)
  292. """
  293. class TestCommand(Command):
  294. description = "Run self-test"
  295. # Long option name, short option name, description
  296. user_options = [
  297. ('skip-slow-tests', None,
  298. 'Skip slow tests'),
  299. ('module=', 'm', 'Test a single module (e.g. Cipher, PublicKey)')
  300. ]
  301. def initialize_options(self):
  302. self.build_dir = None
  303. self.skip_slow_tests = None
  304. self.module = None
  305. def finalize_options(self):
  306. self.set_undefined_options('install', ('build_lib', 'build_dir'))
  307. self.config = {'slow_tests': not self.skip_slow_tests}
  308. def run(self):
  309. # Run sub commands
  310. for cmd_name in self.get_sub_commands():
  311. self.run_command(cmd_name)
  312. # Run SelfTest
  313. old_path = sys.path[:]
  314. self.announce("running self-tests on " + package_root)
  315. try:
  316. sys.path.insert(0, self.build_dir)
  317. if use_separate_namespace:
  318. from Cryptodome import SelfTest
  319. from Cryptodome.Math import Numbers
  320. else:
  321. from Crypto import SelfTest
  322. from Crypto.Math import Numbers
  323. moduleObj = None
  324. if self.module:
  325. if self.module.count('.')==0:
  326. # Test a whole a sub-package
  327. full_module = package_root + ".SelfTest." + self.module
  328. module_name = self.module
  329. else:
  330. # Test only a module
  331. # Assume only one dot is present
  332. comps = self.module.split('.')
  333. module_name = "test_" + comps[1]
  334. full_module = package_root + ".SelfTest." + comps[0] + "." + module_name
  335. # Import sub-package or module
  336. moduleObj = __import__( full_module, globals(), locals(), module_name )
  337. PrintErr(package_root + ".Math implementation:",
  338. str(Numbers._implementation))
  339. SelfTest.run(module=moduleObj, verbosity=self.verbose, stream=sys.stdout, config=self.config)
  340. finally:
  341. # Restore sys.path
  342. sys.path[:] = old_path
  343. # Run slower self-tests
  344. self.announce("running extended self-tests")
  345. sub_commands = [ ('build', None) ]
  346. """
  347. setup(
  348. name = project_name,
  349. version = version_string,
  350. description = "Cryptographic library for Python",
  351. long_description = longdesc,
  352. author = "Helder Eijs",
  353. author_email = "helderijs@gmail.com",
  354. url = "http://www.pycryptodome.org",
  355. platforms = 'Posix; MacOS X; Windows',
  356. classifiers = [
  357. 'Development Status :: 4 - Beta',
  358. 'License :: OSI Approved :: BSD License',
  359. 'License :: Public Domain',
  360. 'Intended Audience :: Developers',
  361. 'Operating System :: Unix',
  362. 'Operating System :: Microsoft :: Windows',
  363. 'Operating System :: MacOS :: MacOS X',
  364. 'Topic :: Security :: Cryptography',
  365. 'Programming Language :: Python :: 2',
  366. 'Programming Language :: Python :: 2.4',
  367. 'Programming Language :: Python :: 2.5',
  368. 'Programming Language :: Python :: 2.6',
  369. 'Programming Language :: Python :: 2.7',
  370. 'Programming Language :: Python :: 3',
  371. ],
  372. packages = [
  373. "Crypto",
  374. "Crypto.Cipher",
  375. "Crypto.Hash",
  376. "Crypto.IO",
  377. "Crypto.PublicKey",
  378. "Crypto.Protocol",
  379. "Crypto.Random",
  380. "Crypto.Signature",
  381. "Crypto.Util",
  382. "Crypto.Math",
  383. #"Crypto.SelfTest",
  384. #"Crypto.SelfTest.Cipher",
  385. #"Crypto.SelfTest.Hash",
  386. #"Crypto.SelfTest.IO",
  387. #"Crypto.SelfTest.Protocol",
  388. #"Crypto.SelfTest.PublicKey",
  389. #"Crypto.SelfTest.Random",
  390. #"Crypto.SelfTest.Signature",
  391. #"Crypto.SelfTest.Util",
  392. #"Crypto.SelfTest.Math",
  393. ],
  394. package_dir = { "Crypto": "lib/Crypto" },
  395. package_data = {
  396. #"Crypto.SelfTest.Cipher" : [
  397. # "test_vectors/AES/*.rsp",
  398. # "test_vectors/TDES/*.rsp",
  399. # ],
  400. #"Crypto.SelfTest.Hash" : [
  401. # "test_vectors/SHA3/*.txt",
  402. # "test_vectors/keccak/*.txt",
  403. # "test_vectors/BLAKE2s/*.txt",
  404. # "test_vectors/BLAKE2b/*.txt"
  405. # ],
  406. #"Crypto.SelfTest.Signature" : [
  407. # "test_vectors/DSA/*.*",
  408. # "test_vectors/ECDSA/*.*",
  409. # "test_vectors/PKCS1-v1.5/*.*",
  410. # "test_vectors/PKCS1-PSS/*.*"
  411. # ],
  412. #"Crypto.SelfTest.PublicKey" : [
  413. # "test_vectors/ECC/*.*",
  414. # ],
  415. "Crypto.Math" : [ "mpir.dll" ],
  416. },
  417. cmdclass = {
  418. 'build_ext':PCTBuildExt,
  419. 'build_py': PCTBuildPy
  420. #'test': TestCommand
  421. },
  422. ext_modules = [
  423. # Hash functions
  424. Extension("Crypto.Hash._MD2",
  425. include_dirs=['src/'],
  426. sources=["src/MD2.c"]),
  427. Extension("Crypto.Hash._MD4",
  428. include_dirs=['src/'],
  429. sources=["src/MD4.c"]),
  430. Extension("Crypto.Hash._SHA256",
  431. include_dirs=['src/'],
  432. sources=["src/SHA256.c"]),
  433. Extension("Crypto.Hash._SHA224",
  434. include_dirs=['src/'],
  435. sources=["src/SHA224.c"]),
  436. Extension("Crypto.Hash._SHA384",
  437. include_dirs=['src/'],
  438. sources=["src/SHA384.c"]),
  439. Extension("Crypto.Hash._SHA512",
  440. include_dirs=['src/'],
  441. sources=["src/SHA512.c"]),
  442. Extension("Crypto.Hash._RIPEMD160",
  443. include_dirs=['src/'],
  444. sources=["src/RIPEMD160.c"]),
  445. Extension("Crypto.Hash._keccak",
  446. include_dirs=['src/'],
  447. sources=["src/keccak.c"]),
  448. Extension("Crypto.Hash._BLAKE2b",
  449. include_dirs=['src/'],
  450. sources=["src/blake2b.c"]),
  451. Extension("Crypto.Hash._BLAKE2s",
  452. include_dirs=['src/'],
  453. sources=["src/blake2s.c"]),
  454. # Block encryption algorithms
  455. Extension("Crypto.Cipher._raw_aes",
  456. include_dirs=['src/'],
  457. sources=["src/AES.c"]),
  458. Extension("Crypto.Cipher._raw_aesni",
  459. include_dirs=['src/'],
  460. sources=["src/AESNI.c"]),
  461. Extension("Crypto.Cipher._raw_arc2",
  462. include_dirs=['src/'],
  463. sources=["src/ARC2.c"]),
  464. Extension("Crypto.Cipher._raw_blowfish",
  465. include_dirs=['src/'],
  466. sources=["src/Blowfish.c"]),
  467. Extension("Crypto.Cipher._raw_cast",
  468. include_dirs=['src/'],
  469. sources=["src/CAST.c"]),
  470. Extension("Crypto.Cipher._raw_des",
  471. include_dirs=['src/', 'src/libtom/'],
  472. sources=["src/DES.c"]),
  473. Extension("Crypto.Cipher._raw_des3",
  474. include_dirs=['src/', 'src/libtom/'],
  475. sources=["src/DES3.c"]),
  476. Extension("Crypto.Util._galois",
  477. include_dirs=['src/'],
  478. sources=['src/galois.c']),
  479. Extension("Crypto.Util._cpuid",
  480. include_dirs=['src/'],
  481. sources=['src/cpuid.c']),
  482. # Chaining modes
  483. Extension("Crypto.Cipher._raw_ecb",
  484. include_dirs=['src/'],
  485. sources=["src/raw_ecb.c"]),
  486. Extension("Crypto.Cipher._raw_cbc",
  487. include_dirs=['src/'],
  488. sources=["src/raw_cbc.c"]),
  489. Extension("Crypto.Cipher._raw_cfb",
  490. include_dirs=['src/'],
  491. sources=["src/raw_cfb.c"]),
  492. Extension("Crypto.Cipher._raw_ofb",
  493. include_dirs=['src/'],
  494. sources=["src/raw_ofb.c"]),
  495. Extension("Crypto.Cipher._raw_ctr",
  496. include_dirs=['src/'],
  497. sources=["src/raw_ctr.c"]),
  498. Extension("Crypto.Cipher._raw_ocb",
  499. include_dirs=['src/'],
  500. sources=["src/raw_ocb.c"]),
  501. # Stream ciphers
  502. Extension("Crypto.Cipher._ARC4",
  503. include_dirs=['src/'],
  504. sources=["src/ARC4.c"]),
  505. Extension("Crypto.Cipher._Salsa20",
  506. include_dirs=['src/', 'src/libtom/'],
  507. sources=["src/Salsa20.c"]),
  508. Extension("Crypto.Cipher._chacha20",
  509. include_dirs=['src/'],
  510. sources=["src/chacha20.c"]),
  511. # Others
  512. Extension("Crypto.Protocol._scrypt",
  513. include_dirs=['src/'],
  514. sources=["src/scrypt.c"]),
  515. # Utility modules
  516. Extension("Crypto.Util._strxor",
  517. include_dirs=['src/'],
  518. sources=['src/strxor.c']),
  519. ]
  520. )