pycrypt.rst 52 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188
  1. ====================================
  2. Python Cryptography Toolkit
  3. ====================================
  4. **Version 2.6.1**
  5. The Python Cryptography Toolkit describes a package containing various
  6. cryptographic modules for the Python programming language. This
  7. documentation assumes you have some basic knowledge about the Python
  8. language, but not necessarily about cryptography.
  9. .. contents::
  10. Introduction
  11. -------------------
  12. Design Goals
  13. ===================
  14. The Python cryptography toolkit is intended to provide a reliable and
  15. stable base for writing Python programs that require cryptographic
  16. functions.
  17. A central goal has been to provide a simple, consistent interface for
  18. similar classes of algorithms. For example, all block cipher objects
  19. have the same methods and return values, and support the same feedback
  20. modes. Hash functions have a different interface, but it too is
  21. consistent over all the hash functions available. Some of these
  22. interfaces have been codified as Python Enhancement Proposal
  23. documents, as PEP 247, "API for Cryptographic Hash Functions", and
  24. PEP 272, "API for Block Encryption Algorithms".
  25. This is intended to make it easy to replace old algorithms with newer,
  26. more secure ones. If you're given a bit of portably-written Python
  27. code that uses the DES encryption algorithm, you should be able to use
  28. AES instead by simply changing ``from Crypto.Cipher import DES`` to
  29. ``from Crypto.Cipher import AES``, and changing all references to
  30. ``DES.new()`` to ``AES.new()``. It's also fairly simple to
  31. write your own modules that mimic this interface, thus letting you use
  32. combinations or permutations of algorithms.
  33. Some modules are implemented in C for performance; others are written
  34. in Python for ease of modification. Generally, low-level functions
  35. like ciphers and hash functions are written in C, while less
  36. speed-critical functions have been written in Python. This division
  37. may change in future releases. When speeds are quoted in this
  38. document, they were measured on a 500 MHz Pentium II running Linux.
  39. The exact speeds will obviously vary with different machines,
  40. different compilers, and the phase of the moon, but they provide a
  41. crude basis for comparison. Currently the cryptographic
  42. implementations are acceptably fast, but not spectacularly good. I
  43. welcome any suggestions or patches for faster code.
  44. I have placed the code under no restrictions; you can redistribute the
  45. code freely or commercially, in its original form or with any
  46. modifications you make, subject to whatever local laws may apply in your
  47. jurisdiction. Note that you still have to come to some agreement with
  48. the holders of any patented algorithms you're using. If you're
  49. intensively using these modules, please tell me about it; there's little
  50. incentive for me to work on this package if I don't know of anyone using
  51. it.
  52. I also make no guarantees as to the usefulness, correctness, or legality
  53. of these modules, nor does their inclusion constitute an endorsement of
  54. their effectiveness. Many cryptographic algorithms are patented;
  55. inclusion in this package does not necessarily mean you are allowed to
  56. incorporate them in a product and sell it. Some of these algorithms may
  57. have been cryptanalyzed, and may no longer be secure. While I will
  58. include commentary on the relative security of the algorithms in the
  59. sections entitled "Security Notes", there may be more recent analyses
  60. I'm not aware of. (Or maybe I'm just clueless.) If you're implementing
  61. an important system, don't just grab things out of a toolbox and put
  62. them together; do some research first. On the other hand, if you're
  63. just interested in keeping your co-workers or your relatives out of your
  64. files, any of the components here could be used.
  65. This document is very much a work in progress. If you have any
  66. questions, comments, complaints, or suggestions, please send them to me.
  67. Acknowledgements
  68. ==================================================
  69. Much of the code that actually implements the various cryptographic
  70. algorithms was not written by me. I'd like to thank all the people who
  71. implemented them, and released their work under terms which allowed me
  72. to use their code. These individuals are credited in the relevant
  73. chapters of this documentation. Bruce Schneier's book
  74. :title-reference:`Applied Cryptography` was also very useful in writing this toolkit; I highly
  75. recommend it if you're interested in learning more about cryptography.
  76. Good luck with your cryptography hacking!
  77. Crypto.Hash: Hash Functions
  78. --------------------------------------------------
  79. Hash functions take arbitrary strings as input, and produce an output
  80. of fixed size that is dependent on the input; it should never be
  81. possible to derive the input data given only the hash function's
  82. output. One simple hash function consists of simply adding together
  83. all the bytes of the input, and taking the result modulo 256. For a
  84. hash function to be cryptographically secure, it must be very
  85. difficult to find two messages with the same hash value, or to find a
  86. message with a given hash value. The simple additive hash function
  87. fails this criterion miserably and the hash functions described below
  88. meet this criterion (as far as we know). Examples of
  89. cryptographically secure hash functions include MD2, MD5, and SHA1.
  90. Hash functions can be used simply as a checksum, or, in association with a
  91. public-key algorithm, can be used to implement digital signatures.
  92. The hashing algorithms currently implemented are:
  93. ============= ============= ========
  94. Hash function Digest length Security
  95. ============= ============= ========
  96. MD2 128 bits Insecure, do not use
  97. MD4 128 bits Insecure, do not use
  98. MD5 128 bits Insecure, do not use
  99. RIPEMD 160 bits Secure. This is RIPEMD-160.
  100. SHA 160 bits SHA1 is shaky. Walk, do not run, away from SHA1.
  101. SHA256 256 bits Secure.
  102. ============= ============= ========
  103. Resources:
  104. On SHA1 (in)security: http://www.schneier.com/blog/archives/2005/02/cryptanalysis_o.html
  105. SHA1 phase-out by 2010: http://csrc.nist.gov/groups/ST/toolkit/documents/shs/hash_standards_comments.pdf
  106. On MD5 insecurity: http://www.schneier.com/blog/archives/2008/12/forging_ssl_cer.html
  107. Crypto.Hash.HMAC implements the RFC-2104 HMAC algorithm. The HMAC module is
  108. a copy of Python 2.2's module, and works on Python 2.1 as well.
  109. HMAC's security depends on the cryptographic strength of the key handed to it,
  110. and on the underlying hashing method used. HMAC-MD5 and HMAC-SHA1 are used in
  111. IPSEC and TLS.
  112. All hashing modules with the exception of HMAC share the same interface.
  113. After importing a given hashing module, call the ``new()`` function to create
  114. a new hashing object. You can now feed arbitrary strings into the object
  115. with the ``update()`` method, and can ask for the hash value at
  116. any time by calling the ``digest()`` or ``hexdigest()``
  117. methods. The ``new()`` function can also be passed an optional
  118. string parameter that will be immediately hashed into the object's
  119. state.
  120. To create a HMAC object, call HMAC's ```new()`` function with the key (as
  121. a string or bytes object) to be used, an optional message, and the hash
  122. function to use. HMAC defaults to using MD5. This is not a secure default,
  123. please use SHA256 or better instead in new implementations.
  124. Hash function modules define one variable:
  125. **digest_size**:
  126. An integer value; the size of the digest
  127. produced by the hashing objects. You could also obtain this value by
  128. creating a sample object, and taking the length of the digest string
  129. it returns, but using ``digest_size`` is faster.
  130. The methods for hashing objects are always the following:
  131. **copy()**:
  132. Return a separate copy of this hashing object. An ``update`` to
  133. this copy won't affect the original object.
  134. **digest()**:
  135. Return the hash value of this hashing object, as a string containing
  136. 8-bit data. The object is not altered in any way by this function;
  137. you can continue updating the object after calling this function.
  138. Python 3.x: digest() returns a bytes object
  139. **hexdigest()**:
  140. Return the hash value of this hashing object, as a string containing
  141. the digest data as hexadecimal digits. The resulting string will be
  142. twice as long as that returned by ``digest()``. The object is not
  143. altered in any way by this function; you can continue updating the
  144. object after calling this function.
  145. **update(arg)**:
  146. Update this hashing object with the string ``arg``.
  147. Python 3.x: The passed argument must be an object interpretable as
  148. a buffer of bytes
  149. Here's an example, using the SHA-256 algorithm::
  150. >>> from Crypto.Hash import SHA256
  151. >>> m = SHA256.new()
  152. >>> m.update('abc')
  153. >>> m.digest()
  154. '\xbax\x16\xbf\x8f\x01\xcf\xeaAA@\xde]\xae"#\xb0\x03a\xa3\x96\x17z\x9c\xb4\x10\xffa\xf2\x00\x15\xad'
  155. >>> m.hexdigest()
  156. 'ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad'
  157. Here's an example of using HMAC::
  158. >>> from Crypto.Hash import HMAC, SHA256
  159. >>> m = HMAC.new('Please do not use this key in your code, with sugar on top',
  160. '', SHA256)
  161. >>> m.update('abc')
  162. >>> m.digest()
  163. 'F\xaa\x83\t\x97<\x8c\x12\xff\xe8l\xca:\x1d\xb4\xfc7\xfa\x84tK-\xb0\x00v*\xc2\x90\x19\xaa\xfaz'
  164. >>> m.hexdigest()
  165. '46aa8309973c8c12ffe86cca3a1db4fc37fa84744b2db000762ac29019aafa7a'
  166. Security Notes
  167. ==========================
  168. Hashing algorithms are broken by developing an algorithm to compute a
  169. string that produces a given hash value, or to find two messages that
  170. produce the same hash value. Consider an example where Alice and Bob
  171. are using digital signatures to sign a contract. Alice computes the
  172. hash value of the text of the contract and signs the hash value with
  173. her private key. Bob could then compute a different contract that has
  174. the same hash value, and it would appear that Alice signed that bogus
  175. contract; she'd have no way to prove otherwise. Finding such a
  176. message by brute force takes ``pow(2, b-1)`` operations, where the
  177. hash function produces *b*-bit hashes.
  178. If Bob can only find two messages with the same hash value but can't
  179. choose the resulting hash value, he can look for two messages with
  180. different meanings, such as "I will mow Bob's lawn for $10" and "I owe
  181. Bob $1,000,000", and ask Alice to sign the first, innocuous contract.
  182. This attack is easier for Bob, since finding two such messages by brute
  183. force will take ``pow(2, b/2)`` operations on average. However,
  184. Alice can protect herself by changing the protocol; she can simply
  185. append a random string to the contract before hashing and signing it;
  186. the random string can then be kept with the signature.
  187. Some of the algorithms implemented here have been completely broken.
  188. The MD2, MD4 and MD5 hash functions are widely considered insecure
  189. hash functions, as it has been proven that meaningful hash collisions
  190. can be generated for them, in the case of MD4 and MD5 in mere seconds.
  191. MD2 is rather slow at 1250 K/sec. MD4 is faster at 44,500 K/sec.
  192. MD5 is a strengthened version of MD4 with four rounds; beginning in 2004,
  193. a series of attacks were discovered and it's now possible to create pairs
  194. of files that result in the same MD5 hash. The MD5
  195. implementation is moderately well-optimized and thus faster on x86
  196. processors, running at 35,500 K/sec. MD5 may even be faster than MD4,
  197. depending on the processor and compiler you use.
  198. MD5 is still supported for compatibility with existing protocols, but
  199. implementors should use SHA256 in new software because there are no known
  200. attacks against SHA256.
  201. All the MD* algorithms produce 128-bit hashes.
  202. SHA1 produces a 160-bit hash. Because of recent theoretical attacks against SHA1,
  203. NIST recommended phasing out use of SHA1 by 2010.
  204. SHA256 produces a larger 256-bit hash, and there are no known attacks against it.
  205. It operates at 10,500 K/sec.
  206. RIPEMD has a 160-bit output, the same output size as SHA1, and operates at 17,600
  207. K/sec.
  208. Credits
  209. ===============
  210. The MD2 and MD4 implementations were written by A.M. Kuchling, and the MD5
  211. code was implemented by Colin Plumb. The SHA1 code was originally written by
  212. Peter Gutmann. The RIPEMD160 code as of version 2.1.0 was written by Dwayne
  213. Litzenberger. The SHA256 code was written by Tom St. Denis and is part of the
  214. LibTomCrypt library (http://www.libtomcrypt.org/); it was adapted for the
  215. toolkit by Jeethu Rao and Taylor Boon.
  216. Crypto.Cipher: Encryption Algorithms
  217. --------------------------------------------------
  218. Encryption algorithms transform their input data, or **plaintext**,
  219. in some way that is dependent on a variable **key**, producing
  220. **ciphertext**. This transformation can easily be reversed, if (and,
  221. hopefully, only if) one knows the key. The key can be varied by the
  222. user or application and chosen from some very large space of possible
  223. keys.
  224. For a secure encryption algorithm, it should be very difficult to
  225. determine the original plaintext without knowing the key; usually, no
  226. clever attacks on the algorithm are known, so the only way of breaking
  227. the algorithm is to try all possible keys. Since the number of possible
  228. keys is usually of the order of 2 to the power of 56 or 128, this is not
  229. a serious threat, although 2 to the power of 56 is now considered
  230. insecure in the face of custom-built parallel computers and distributed
  231. key guessing efforts.
  232. **Block ciphers** take multibyte inputs of a fixed size
  233. (frequently 8 or 16 bytes long) and encrypt them. Block ciphers can
  234. be operated in various modes. The simplest is Electronic Code Book
  235. (or ECB) mode. In this mode, each block of plaintext is simply
  236. encrypted to produce the ciphertext. This mode can be dangerous,
  237. because many files will contain patterns greater than the block size;
  238. for example, the comments in a C program may contain long strings of
  239. asterisks intended to form a box. All these identical blocks will
  240. encrypt to identical ciphertext; an adversary may be able to use this
  241. structure to obtain some information about the text.
  242. To eliminate this weakness, there are various feedback modes in which
  243. the plaintext is combined with the previous ciphertext before
  244. encrypting; this eliminates any repetitive structure in the
  245. ciphertext.
  246. One mode is Cipher Block Chaining (CBC mode); another is Cipher
  247. FeedBack (CFB mode). CBC mode still encrypts in blocks, and thus is
  248. only slightly slower than ECB mode. CFB mode encrypts on a
  249. byte-by-byte basis, and is much slower than either of the other two
  250. modes. The chaining feedback modes require an initialization value to
  251. start off the encryption; this is a string of the same length as the
  252. ciphering algorithm's block size, and is passed to the ``new()``
  253. function.
  254. The currently available block ciphers are listed in the following table,
  255. and are in the ``Crypto.Cipher`` package:
  256. ================= ============================
  257. Cipher Key Size/Block Size
  258. ================= ============================
  259. AES 16, 24, or 32 bytes/16 bytes
  260. ARC2 Variable/8 bytes
  261. Blowfish Variable/8 bytes
  262. CAST Variable/8 bytes
  263. DES 8 bytes/8 bytes
  264. DES3 (Triple DES) 16 bytes/8 bytes
  265. ================= ============================
  266. In a strict formal sense, **stream ciphers** encrypt data bit-by-bit;
  267. practically, stream ciphers work on a character-by-character basis.
  268. Stream ciphers use exactly the same interface as block ciphers, with a block
  269. length that will always be 1; this is how block and stream ciphers can be
  270. distinguished.
  271. The only feedback mode available for stream ciphers is ECB mode.
  272. The currently available stream ciphers are listed in the following table:
  273. ======= =========
  274. Cipher Key Size
  275. ======= =========
  276. ARC4 Variable
  277. XOR Variable
  278. ======= =========
  279. ARC4 is short for "Alleged RC4". In September of 1994, someone posted
  280. C code to both the Cypherpunks mailing list and to the Usenet
  281. newsgroup ``sci.crypt``, claiming that it implemented the RC4
  282. algorithm. This claim turned out to be correct. Note that there's a
  283. damaging class of weak RC4 keys; this module won't warn you about such keys.
  284. .. % XXX are there other analyses of RC4?
  285. A similar anonymous posting was made for Alleged RC2 in January, 1996.
  286. An example usage of the DES module::
  287. >>> from Crypto.Cipher import DES
  288. >>> obj=DES.new('abcdefgh', DES.MODE_ECB)
  289. >>> plain="Guido van Rossum is a space alien."
  290. >>> len(plain)
  291. 34
  292. >>> obj.encrypt(plain)
  293. Traceback (innermost last):
  294. File "<stdin>", line 1, in ?
  295. ValueError: Strings for DES must be a multiple of 8 in length
  296. >>> ciph=obj.encrypt(plain+'XXXXXX')
  297. >>> ciph
  298. '\021,\343Nq\214DY\337T\342pA\372\255\311s\210\363,\300j\330\250\312\347\342I\3215w\03561\303dgb/\006'
  299. >>> obj.decrypt(ciph)
  300. 'Guido van Rossum is a space alien.XXXXXX'
  301. All cipher algorithms share a common interface. After importing a
  302. given module, there is exactly one function and two variables
  303. available.
  304. **new(key, mode[, IV])**:
  305. Returns a ciphering object, using ``key`` and feedback mode
  306. ``mode``.
  307. If ``mode`` is ``MODE_CBC`` or ``MODE_CFB``, ``IV`` must be provided,
  308. and must be a string of the same length as the block size.
  309. Some algorithms support additional keyword arguments to this function; see
  310. the "Algorithm-specific Notes for Encryption Algorithms" section below for the details.
  311. Python 3.x: ```mode`` is a string object; ```key``` and ```IV``` must be
  312. objects interpretable as a buffer of bytes.
  313. **block_size**:
  314. An integer value; the size of the blocks encrypted by this module.
  315. Strings passed to the ``encrypt`` and ``decrypt`` functions
  316. must be a multiple of this length. For stream ciphers,
  317. ``block_size`` will be 1.
  318. **key_size**:
  319. An integer value; the size of the keys required by this module. If
  320. ``key_size`` is zero, then the algorithm accepts arbitrary-length
  321. keys. You cannot pass a key of length 0 (that is, the null string
  322. ``""`` as such a variable-length key.
  323. All cipher objects have at least three attributes:
  324. **block_size**:
  325. An integer value equal to the size of the blocks encrypted by this object.
  326. Identical to the module variable of the same name.
  327. **IV**:
  328. Contains the initial value which will be used to start a cipher
  329. feedback mode. After encrypting or decrypting a string, this value
  330. will reflect the modified feedback text; it will always be one block
  331. in length. It is read-only, and cannot be assigned a new value.
  332. Python 3.x: ```IV``` is a bytes object.
  333. **key_size**:
  334. An integer value equal to the size of the keys used by this object. If
  335. ``key_size`` is zero, then the algorithm accepts arbitrary-length
  336. keys. For algorithms that support variable length keys, this will be 0.
  337. Identical to the module variable of the same name.
  338. All ciphering objects have the following methods:
  339. **decrypt(string)**:
  340. Decrypts ``string``, using the key-dependent data in the object, and
  341. with the appropriate feedback mode. The string's length must be an exact
  342. multiple of the algorithm's block size. Returns a string containing
  343. the plaintext.
  344. Python 3.x: decrypt() will return a bytes object.
  345. Note: Do not use the same cipher object for both encryption an
  346. decryption, since both operations share the same IV buffer, so the results
  347. will probably not be what you expect.
  348. **encrypt(string)**:
  349. Encrypts a non-null ``string``, using the key-dependent data in the
  350. object, and with the appropriate feedback mode. The string's length
  351. must be an exact multiple of the algorithm's block size; for stream
  352. ciphers, the string can be of any length. Returns a string containing
  353. the ciphertext.
  354. Python 3.x: ```string``` must be an object interpretable as a buffer of bytes.
  355. encrypt() will return a bytes object.
  356. Note: Do not use the same cipher object for both encryption an
  357. decryption, since both operations share the same IV buffer, so the results
  358. will probably not be what you expect.
  359. Security Notes
  360. =======================
  361. Encryption algorithms can be broken in several ways. If you have some
  362. ciphertext and know (or can guess) the corresponding plaintext, you can
  363. simply try every possible key in a **known-plaintext** attack. Or, it
  364. might be possible to encrypt text of your choice using an unknown key;
  365. for example, you might mail someone a message intending it to be
  366. encrypted and forwarded to someone else. This is a
  367. **chosen-plaintext** attack, which is particularly effective if it's
  368. possible to choose plaintexts that reveal something about the key when
  369. encrypted.
  370. Stream ciphers are only secure if any given key is never used twice.
  371. If two (or more) messages are encrypted using the same key in a stream
  372. cipher, the cipher can be broken fairly easily.
  373. DES (5100 K/sec) has a 56-bit key; this is starting to become too small
  374. for safety. It has been shown in 2009 that a ~$10,000 machine can break
  375. DES in under a day on average. NIST has withdrawn FIPS 46-3 in 2005.
  376. DES3 (1830 K/sec) uses three DES encryptions for greater security and a 112-bit
  377. or 168-bit key, but is correspondingly slower. Attacks against DES3 are
  378. not currently feasible, and it has been estimated to be useful until 2030.
  379. Bruce Schneier endorses DES3 for its security because of the decades of
  380. study applied against it. It is, however, slow.
  381. There are no known attacks against Blowfish (9250 K/sec) or CAST (2960 K/sec),
  382. but they're all relatively new algorithms and there hasn't been time for much
  383. analysis to be performed; use them for serious applications only after careful
  384. research.
  385. pycrypto implements CAST with up to 128 bits key length (CAST-128). This
  386. algorithm is considered obsoleted by CAST-256. CAST is patented by Entrust
  387. Technologies and free for non-commercial use.
  388. Bruce Schneier recommends his newer Twofish algorithm over Blowfish where
  389. a fast, secure symmetric cipher is desired. Twofish was an AES candidate. It
  390. is slightly slower than Rijndael (the chosen algorithm for AES) for 128-bit
  391. keys, and slightly faster for 256-bit keys.
  392. AES, the Advanced Encryption Standard, was chosen by the US National
  393. Institute of Standards and Technology from among 6 competitors, and is
  394. probably your best choice. It runs at 7060 K/sec, so it's among the
  395. faster algorithms around.
  396. ARC4 ("Alleged" RC4) (8830 K/sec) has been weakened. Specifically, it has been
  397. shown that the first few bytes of the ARC4 keystream are strongly non-random,
  398. leaking information about the key. When the long-term key and nonce are merely
  399. concatenated to form the ARC4 key, such as is done in WEP, this weakness can be
  400. used to discover the long-term key by observing a large number of messages
  401. encrypted with this key.
  402. Because of these possible related-key attacks, ARC4 should only be used with
  403. keys generated by a strong RNG, or from a source of sufficiently uncorrelated
  404. bits, such as the output of a hash function.
  405. A further possible defense is to discard the initial portion of the keystream.
  406. This altered algorithm is called RC4-drop(n).
  407. While ARC4 is in wide-spread use in several protocols, its use in new protocols
  408. or applications is discouraged.
  409. ARC2 ("Alleged" RC2) is vulnerable to a related-key attack, 2^34 chosen
  410. plaintexts are needed.
  411. Because of these possible related-key attacks, ARC2 should only be used with
  412. keys generated by a strong RNG, or from a source of sufficiently uncorrelated
  413. bits, such as the output of a hash function.
  414. Credits
  415. =============
  416. The code for Blowfish was written from scratch by Dwayne Litzenberger, based
  417. on a specification by Bruce Schneier, who also invented the algorithm; the
  418. Blowfish algorithm has been placed in the public domain and can be used
  419. freely. (See http://www.schneier.com/paper-blowfish-fse.html for more
  420. information about Blowfish.) The CAST implementation was written by Wim Lewis.
  421. The DES implementation uses libtomcrypt, which was written by Tom St Denis.
  422. The Alleged RC4 code was posted to the ``sci.crypt`` newsgroup by an
  423. unknown party, and re-implemented by A.M. Kuchling.
  424. Crypto.Protocol: Various Protocols
  425. --------------------------------------------------
  426. Crypto.Protocol.AllOrNothing
  427. ==========================================
  428. This module implements all-or-nothing package transformations.
  429. An all-or-nothing package transformation is one in which some text is
  430. transformed into message blocks, such that all blocks must be obtained before
  431. the reverse transformation can be applied. Thus, if any blocks are corrupted
  432. or lost, the original message cannot be reproduced.
  433. An all-or-nothing package transformation is not encryption, although a block
  434. cipher algorithm is used. The encryption key is randomly generated and is
  435. extractable from the message blocks.
  436. **AllOrNothing(ciphermodule, mode=None, IV=None)**:
  437. Class implementing the All-or-Nothing package transform.
  438. ``ciphermodule`` is a module implementing the cipher algorithm to
  439. use. Optional arguments ``mode`` and ``IV`` are passed directly
  440. through to the ``ciphermodule.new()`` method; they are the
  441. feedback mode and initialization vector to use. All three arguments
  442. must be the same for the object used to create the digest, and to
  443. undigest'ify the message blocks.
  444. The module passed as ``ciphermodule`` must provide the PEP 272
  445. interface. An encryption key is randomly generated automatically when
  446. needed.
  447. The methods of the ``AllOrNothing`` class are:
  448. **digest(text)**:
  449. Perform the All-or-Nothing package transform on the
  450. string ``text``. Output is a list of message blocks describing the
  451. transformed text, where each block is a string of bit length equal
  452. to the cipher module's block_size.
  453. **undigest(mblocks)**:
  454. Perform the reverse package transformation on a list of message
  455. blocks. Note that the cipher module used for both transformations
  456. must be the same. ``mblocks`` is a list of strings of bit length
  457. equal to ``ciphermodule``'s block_size. The output is a string object.
  458. Crypto.Protocol.Chaffing
  459. ==================================================
  460. Winnowing and chaffing is a technique for enhancing privacy without requiring
  461. strong encryption. In short, the technique takes a set of authenticated
  462. message blocks (the wheat) and adds a number of chaff blocks which have
  463. randomly chosen data and MAC fields. This means that to an adversary, the
  464. chaff blocks look as valid as the wheat blocks, and so the authentication
  465. would have to be performed on every block. By tailoring the number of chaff
  466. blocks added to the message, the sender can make breaking the message
  467. computationally infeasible. There are many other interesting properties of
  468. the winnow/chaff technique.
  469. For example, say Alice is sending a message to Bob. She packetizes the
  470. message and performs an all-or-nothing transformation on the packets. Then
  471. she authenticates each packet with a message authentication code (MAC). The
  472. MAC is a hash of the data packet, and there is a secret key which she must
  473. share with Bob (key distribution is an exercise left to the reader). She then
  474. adds a serial number to each packet, and sends the packets to Bob.
  475. Bob receives the packets, and using the shared secret authentication key,
  476. authenticates the MACs for each packet. Those packets that have bad MACs are
  477. simply discarded. The remainder are sorted by serial number, and passed
  478. through the reverse all-or-nothing transform. The transform means that an
  479. eavesdropper (say Eve) must acquire all the packets before any of the data can
  480. be read. If even one packet is missing, the data is useless.
  481. There's one twist: by adding chaff packets, Alice and Bob can make Eve's job
  482. much harder, since Eve now has to break the shared secret key, or try every
  483. combination of wheat and chaff packet to read any of the message. The cool
  484. thing is that Bob doesn't need to add any additional code; the chaff packets
  485. are already filtered out because their MACs don't match (in all likelihood --
  486. since the data and MACs for the chaff packets are randomly chosen it is
  487. possible, but very unlikely that a chaff MAC will match the chaff data). And
  488. Alice need not even be the party adding the chaff! She could be completely
  489. unaware that a third party, say Charles, is adding chaff packets to her
  490. messages as they are transmitted.
  491. **Chaff(factor=1.0, blocksper=1)**:
  492. Class implementing the chaff adding algorithm.
  493. ``factor`` is the number of message blocks
  494. to add chaff to, expressed as a percentage between 0.0 and 1.0; the default value is 1.0.
  495. ``blocksper`` is the number of chaff blocks to include for each block
  496. being chaffed, and defaults to 1. The default settings
  497. add one chaff block to every
  498. message block. By changing the defaults, you can adjust how
  499. computationally difficult it could be for an adversary to
  500. brute-force crack the message. The difficulty is expressed as::
  501. pow(blocksper, int(factor * number-of-blocks))
  502. For ease of implementation, when ``factor`` < 1.0, only the first
  503. ``int(factor*number-of-blocks)`` message blocks are chaffed.
  504. ``Chaff`` instances have the following methods:
  505. **chaff(blocks)**:
  506. Add chaff to message blocks. ``blocks`` is a list of 3-tuples of the
  507. form ``(serial-number, data, MAC)``.
  508. Chaff is created by choosing a random number of the same
  509. byte-length as ``data``, and another random number of the same
  510. byte-length as ``MAC``. The message block's serial number is placed
  511. on the chaff block and all the packet's chaff blocks are randomly
  512. interspersed with the single wheat block. This method then
  513. returns a list of 3-tuples of the same form. Chaffed blocks will
  514. contain multiple instances of 3-tuples with the same serial
  515. number, but the only way to figure out which blocks are wheat and
  516. which are chaff is to perform the MAC hash and compare values.
  517. Crypto.PublicKey: Public-Key Algorithms
  518. --------------------------------------------------
  519. So far, the encryption algorithms described have all been *private key*
  520. ciphers. The same key is used for both encryption and decryption
  521. so all correspondents must know it. This poses a problem: you may
  522. want encryption to communicate sensitive data over an insecure
  523. channel, but how can you tell your correspondent what the key is? You
  524. can't just e-mail it to her because the channel is insecure. One
  525. solution is to arrange the key via some other way: over the phone or
  526. by meeting in person.
  527. Another solution is to use **public-key** cryptography. In a public
  528. key system, there are two different keys: one for encryption and one for
  529. decryption. The encryption key can be made public by listing it in a
  530. directory or mailing it to your correspondent, while you keep the
  531. decryption key secret. Your correspondent then sends you data encrypted
  532. with your public key, and you use the private key to decrypt it. While
  533. the two keys are related, it's very difficult to derive the private key
  534. given only the public key; however, deriving the private key is always
  535. possible given enough time and computing power. This makes it very
  536. important to pick keys of the right size: large enough to be secure, but
  537. small enough to be applied fairly quickly.
  538. Many public-key algorithms can also be used to sign messages; simply
  539. run the message to be signed through a decryption with your private
  540. key key. Anyone receiving the message can encrypt it with your
  541. publicly available key and read the message. Some algorithms do only
  542. one thing, others can both encrypt and authenticate.
  543. The currently available public-key algorithms are listed in the
  544. following table:
  545. ============= ==========================================
  546. Algorithm Capabilities
  547. ============= ==========================================
  548. RSA Encryption, authentication/signatures
  549. ElGamal Encryption, authentication/signatures
  550. DSA Authentication/signatures
  551. ============= ==========================================
  552. Many of these algorithms are patented. Before using any of them in a
  553. commercial product, consult a patent attorney; you may have to arrange
  554. a license with the patent holder.
  555. An example of using the RSA module to sign a message::
  556. >>> from Crypto.Hash import MD5
  557. >>> from Crypto.PublicKey import RSA
  558. >>> from Crypto import Random
  559. >>> rng = Random.new().read
  560. >>> RSAkey = RSA.generate(2048, rng) # This will take a while...
  561. >>> hash = MD5.new(plaintext).digest()
  562. >>> signature = RSAkey.sign(hash, rng)
  563. >>> signature # Print what an RSA sig looks like--you don't really care.
  564. ('\021\317\313\336\264\315' ...,)
  565. >>> RSAkey.verify(hash, signature) # This sig will check out
  566. 1
  567. >>> RSAkey.verify(hash[:-1], signature)# This sig will fail
  568. 0
  569. Public-key modules make the following functions available:
  570. **construct(tuple)**:
  571. Constructs a key object from a tuple of data. This is
  572. algorithm-specific; look at the source code for the details. (To be
  573. documented later.)
  574. **generate(size, randfunc, progress_func=None, e=65537)**:
  575. Generate a fresh public/private key pair. ``size`` is a
  576. algorithm-dependent size parameter, usually measured in bits; the
  577. larger it is, the more difficult it will be to break the key. Safe
  578. key sizes vary from algorithm to algorithm; you'll have to research
  579. the question and decide on a suitable key size for your application.
  580. An N-bit keys can encrypt messages up to N-1 bits long.
  581. ``randfunc`` is a random number generation function; it should
  582. accept a single integer ``N`` and return a string of random data
  583. ``N`` bytes long. You should always use a cryptographically secure
  584. random number generator, such as the one defined in the
  585. ``Crypto.Random`` module; **don't** just use the
  586. current time and the ``random`` module.
  587. ``progress_func`` is an optional function that will be called with a short
  588. string containing the key parameter currently being generated; it's
  589. useful for interactive applications where a user is waiting for a key
  590. to be generated.
  591. ``e`` is the public RSA exponent, and must be an odd positive integer.
  592. It is typically a small number with very few ones in its binary representation.
  593. The default value 65537 (=0b10000000000000001) is a safe choice: other
  594. common values are 5, 7, 17, and 257. Exponent 3 is also widely used,
  595. but it requires very special care when padding the message.
  596. If you want to interface with some other program, you will have to know
  597. the details of the algorithm being used; this isn't a big loss. If you
  598. don't care about working with non-Python software, simply use the
  599. ``pickle`` module when you need to write a key or a signature to a
  600. file. It's portable across all the architectures that Python supports,
  601. and it's simple to use.
  602. In case interoperability were important, RSA key objects can be exported
  603. and imported in two standard formats: the DER binary encoding specified in
  604. PKCS#1 (see RFC3447) or the ASCII textual encoding specified by the
  605. old Privacy Enhanced Mail services (PEM, see RFC1421).
  606. The RSA module makes the following function available for importing keys:
  607. **importKey(externKey)**:
  608. Import an RSA key (pubic or private) encoded as a string ``externKey``.
  609. The key can follow either the PKCS#1/DER format (binary) or the PEM format
  610. (7-bit ASCII).
  611. For instance:
  612. >>> from Crypto.PublicKey import RSA
  613. >>> f = open("mykey.pem")
  614. >>> RSAkey = RSA.importKey(f.read())
  615. >>> if RSAkey.has_private(): print "Private key"
  616. Every RSA object supports the following method to export itself:
  617. **exportKey(format='PEM')**:
  618. Return the key encoded as a string, according to the specified ``format``:
  619. ``'PEM'`` (default) or ``'DER'`` (also known as PKCS#1).
  620. For instance:
  621. >>> from Crypto.PublicKey import RSA
  622. >>> from Crypto import Random
  623. >>> rng = Random.new().read
  624. >>> RSAkey = RSA.generate(1024, rng)
  625. >>> f = open("keyPrivate.der","w+")
  626. >>> f.write(RSAkey.exportKey("DER"))
  627. >>> f.close()
  628. >>> f = open("keyPublic.pem","w+")
  629. >>> f.write(RSAkey.publickey().exportKey("PEM"))
  630. >>> f.close()
  631. Public-key objects always support the following methods. Some of them
  632. may raise exceptions if their functionality is not supported by the
  633. algorithm.
  634. **can_blind()**:
  635. Returns true if the algorithm is capable of blinding data;
  636. returns false otherwise.
  637. **can_encrypt()**:
  638. Returns true if the algorithm is capable of encrypting and decrypting
  639. data; returns false otherwise. To test if a given key object can encrypt
  640. data, use ``key.can_encrypt() and key.has_private()``.
  641. **can_sign()**:
  642. Returns true if the algorithm is capable of signing data; returns false
  643. otherwise. To test if a given key object can sign data, use
  644. ``key.can_sign() and key.has_private()``.
  645. **decrypt(tuple)**:
  646. Decrypts ``tuple`` with the private key, returning another string.
  647. This requires the private key to be present, and will raise an exception
  648. if it isn't present. It will also raise an exception if ``string`` is
  649. too long.
  650. **encrypt(string, K)**:
  651. Encrypts ``string`` with the private key, returning a tuple of
  652. strings; the length of the tuple varies from algorithm to algorithm.
  653. ``K`` should be a string of random data that is as long as
  654. possible. Encryption does not require the private key to be present
  655. inside the key object. It will raise an exception if ``string`` is
  656. too long. For ElGamal objects, the value of ``K`` expressed as a
  657. big-endian integer must be relatively prime to ``self.p-1``; an
  658. exception is raised if it is not.
  659. Python 3.x: ```string``` must be an object interpretable as a buffer of bytes.
  660. **has_private()**:
  661. Returns true if the key object contains the private key data, which
  662. will allow decrypting data and generating signatures.
  663. Otherwise this returns false.
  664. **publickey()**:
  665. Returns a new public key object that doesn't contain the private key
  666. data.
  667. **sign(string, K)**:
  668. Sign ``string``, returning a signature, which is just a tuple; in
  669. theory the signature may be made up of any Python objects at all; in
  670. practice they'll be either strings or numbers. ``K`` should be a
  671. string of random data that is as long as possible. Different algorithms
  672. will return tuples of different sizes. ``sign()`` raises an
  673. exception if ``string`` is too long. For ElGamal objects, the value
  674. of ``K`` expressed as a big-endian integer must be relatively prime to
  675. ``self.p-1``; an exception is raised if it is not.
  676. Python 3.x: ```string``` must be an object interpretable as a buffer of bytes.
  677. **size()**:
  678. Returns the maximum size of a string that can be encrypted or signed,
  679. measured in bits. String data is treated in big-endian format; the most
  680. significant byte comes first. (This seems to be a **de facto** standard
  681. for cryptographical software.) If the size is not a multiple of 8, then
  682. some of the high order bits of the first byte must be zero. Usually
  683. it's simplest to just divide the size by 8 and round down.
  684. **verify(string, signature)**:
  685. Returns true if the signature is valid, and false otherwise.
  686. ``string`` is not processed in any way; ``verify`` does
  687. not run a hash function over the data, but you can easily do that yourself.
  688. Python 3.x: ```string``` must be an object interpretable as a buffer of bytes.
  689. The ElGamal and DSA algorithms
  690. ==================================================
  691. For RSA, the ``K`` parameters are unused; if you like, you can just
  692. pass empty strings. The ElGamal and DSA algorithms require a real
  693. ``K`` value for technical reasons; see Schneier's book for a detailed
  694. explanation of the respective algorithms. This presents a possible
  695. hazard that can inadvertently reveal the private key. Without going into the
  696. mathematical details, the danger is as follows. ``K`` is never derived
  697. or needed by others; theoretically, it can be thrown away once the
  698. encryption or signing operation is performed. However, revealing
  699. ``K`` for a given message would enable others to derive the secret key
  700. data; worse, reusing the same value of ``K`` for two different
  701. messages would also enable someone to derive the secret key data. An
  702. adversary could intercept and store every message, and then try deriving
  703. the secret key from each pair of messages.
  704. This places implementors on the horns of a dilemma. On the one hand,
  705. you want to store the ``K`` values to avoid reusing one; on the other
  706. hand, storing them means they could fall into the hands of an adversary.
  707. One can randomly generate ``K`` values of a suitable length such as
  708. 128 or 144 bits, and then trust that the random number generator
  709. probably won't produce a duplicate anytime soon. This is an
  710. implementation decision that depends on the desired level of security
  711. and the expected usage lifetime of a private key. I can't choose and
  712. enforce one policy for this, so I've added the ``K`` parameter to the
  713. ``encrypt`` and ``sign`` methods. You must choose ``K`` by
  714. generating a string of random data; for ElGamal, when interpreted as a
  715. big-endian number (with the most significant byte being the first byte
  716. of the string), ``K`` must be relatively prime to ``self.p-1``; any
  717. size will do, but brute force searches would probably start with small
  718. primes, so it's probably good to choose fairly large numbers. It might be
  719. simplest to generate a prime number of a suitable length using the
  720. ``Crypto.Util.number`` module.
  721. Security Notes for Public-key Algorithms
  722. ==================================================
  723. Any of these algorithms can be trivially broken; for example, RSA can be
  724. broken by factoring the modulus *n* into its two prime factors.
  725. This is easily done by the following code::
  726. for i in range(2, n):
  727. if (n%i)==0:
  728. print i, 'is a factor'
  729. break
  730. However, ``n`` is usually a few hundred bits long, so this simple
  731. program wouldn't find a solution before the universe comes to an end.
  732. Smarter algorithms can factor numbers more quickly, but it's still
  733. possible to choose keys so large that they can't be broken in a
  734. reasonable amount of time. For ElGamal and DSA, discrete logarithms are
  735. used instead of factoring, but the principle is the same.
  736. Safe key sizes depend on the current state of number theory and
  737. computer technology. At the moment, one can roughly define three
  738. levels of security: low-security commercial, high-security commercial,
  739. and military-grade. For RSA, these three levels correspond roughly to
  740. 768, 1024, and 2048-bit keys.
  741. When exporting private keys you should always carefully ensure that the
  742. chosen storage location cannot be accessed by adversaries.
  743. Crypto.Util: Odds and Ends
  744. --------------------------------------------------
  745. This chapter contains all the modules that don't fit into any of the
  746. other chapters.
  747. Crypto.Util.number
  748. ==========================
  749. This module contains various number-theoretic functions.
  750. **GCD(x,y)**:
  751. Return the greatest common divisor of ``x`` and ``y``.
  752. **getPrime(N, randfunc)**:
  753. Return an ``N``-bit random prime number, using random data obtained
  754. from the function ``randfunc``. ``randfunc`` must take a single
  755. integer argument, and return a string of random data of the
  756. corresponding length; the ``get_bytes()`` method of a
  757. ``RandomPool`` object will serve the purpose nicely, as will the
  758. ``read()`` method of an opened file such as ``/dev/random``.
  759. **getStrongPrime(N, e=0, false_positive_prob=1e-6, randfunc=None)**:
  760. Return a random strong ``N``-bit prime number.
  761. In this context p is a strong prime if p-1 and p+1 have at
  762. least one large prime factor.
  763. ``N`` should be a multiple of 128 and > 512.
  764. If ``e`` is provided the returned prime p-1 will be coprime to ``e``
  765. and thus suitable for RSA where e is the public exponent.
  766. The optional ``false_positive_prob`` is the statistical probability
  767. that true is returned even though it is not (pseudo-prime).
  768. It defaults to 1e-6 (less than 1:1000000).
  769. Note that the real probability of a false-positive is far less. This is
  770. just the mathematically provable limit.
  771. ``randfunc`` should take a single int parameter and return that
  772. many random bytes as a string.
  773. If randfunc is omitted, then ``Random.new().read`` is used.
  774. **getRandomNBitInteger(N, randfunc)**:
  775. Return an ``N``-bit random number, using random data obtained from the
  776. function ``randfunc``. As usual, ``randfunc`` must take a single
  777. integer argument and return a string of random data of the
  778. corresponding length.
  779. **getRandomNBitInteger(N, randfunc)**:
  780. Return an ``N``-bit random number, using random data obtained from the
  781. function ``randfunc``. As usual, ``randfunc`` must take a single
  782. integer argument and return a string of random data of the
  783. corresponding length.
  784. **inverse(u, v)**:
  785. Return the inverse of ``u`` modulo ``v``.
  786. **isPrime(N)**:
  787. Returns true if the number ``N`` is prime, as determined by a
  788. Rabin-Miller test.
  789. Crypto.Random
  790. ==================================================
  791. For cryptographic purposes, ordinary random number generators are
  792. frequently insufficient, because if some of their output is known, it
  793. is frequently possible to derive the generator's future (or past)
  794. output. Given the generator's state at some point in time, someone
  795. could try to derive any keys generated using it. The solution is to
  796. use strong encryption or hashing algorithms to generate successive
  797. data; this makes breaking the generator as difficult as breaking the
  798. algorithms used.
  799. Understanding the concept of **entropy** is important for using the
  800. random number generator properly. In the sense we'll be using it,
  801. entropy measures the amount of randomness; the usual unit is in bits.
  802. So, a single random bit has an entropy of 1 bit; a random byte has an
  803. entropy of 8 bits. Now consider a one-byte field in a database containing a
  804. person's sex, represented as a single character ``'M'`` or ``'F'``.
  805. What's the entropy of this field? Since there are only two possible
  806. values, it's not 8 bits, but one; if you were trying to guess the value,
  807. you wouldn't have to bother trying ``'Q'`` or ``'@'``.
  808. Now imagine running that single byte field through a hash function that
  809. produces 128 bits of output. Is the entropy of the resulting hash value
  810. 128 bits? No, it's still just 1 bit. The entropy is a measure of how many
  811. possible states of the data exist. For English
  812. text, the entropy of a five-character string is not 40 bits; it's
  813. somewhat less, because not all combinations would be seen. ``'Guido'``
  814. is a possible string, as is ``'In th'``; ``'zJwvb'`` is not.
  815. The relevance to random number generation? We want enough bits of
  816. entropy to avoid making an attack on our generator possible. An
  817. example: One computer system had a mechanism which generated nonsense
  818. passwords for its users. This is a good idea, since it would prevent
  819. people from choosing their own name or some other easily guessed string.
  820. Unfortunately, the random number generator used only had 65536 states,
  821. which meant only 65536 different passwords would ever be generated, and
  822. it was easy to compute all the possible passwords and try them. The
  823. entropy of the random passwords was far too low. By the same token, if
  824. you generate an RSA key with only 32 bits of entropy available, there
  825. are only about 4.2 billion keys you could have generated, and an
  826. adversary could compute them all to find your private key. See
  827. RFC 1750,
  828. "Randomness Recommendations for Security", for an interesting discussion
  829. of the issues related to random number generation.
  830. The ``Random`` module builds strong random number generators that look
  831. like generic files a user can read data from. The internal state consists
  832. of entropy accumulators based on the best randomness sources the underlying
  833. operating is capable to provide.
  834. The ``Random`` module defines the following methods:
  835. **new()**:
  836. Builds a file-like object that outputs cryptographically random bytes.
  837. **atfork()**:
  838. This methods has to be called whenever os.fork() is invoked. Forking
  839. undermines the security of any random generator based on the operating
  840. system, as it duplicates all structures a program has. In order to
  841. thwart possible attacks, this method shoud be called soon after forking,
  842. and before any cryptographic operation.
  843. **get_random_bytes(num)**:
  844. Returns a string containing ``num`` bytes of random data.
  845. Objects created by the ``Random`` module define the following variables and methods:
  846. **read(num)**:
  847. Returns a string containing ``num`` bytes of random data.
  848. **close()**:
  849. **flush()**:
  850. Do nothing. Provided for consistency.
  851. Crypto.Util.RFC1751
  852. ==================================================
  853. The keys for private-key algorithms should be arbitrary binary data.
  854. Many systems err by asking the user to enter a password, and then
  855. using the password as the key. This limits the space of possible
  856. keys, as each key byte is constrained within the range of possible
  857. ASCII characters, 32-127, instead of the whole 0-255 range possible
  858. with ASCII. Unfortunately, it's difficult for humans to remember 16
  859. or 32 hex digits.
  860. One solution is to request a lengthy passphrase from the user, and
  861. then run it through a hash function such as SHA or MD5. Another
  862. solution is discussed in RFC 1751, "A Convention for Human-Readable
  863. 128-bit Keys", by Daniel L. McDonald. Binary keys are transformed
  864. into a list of short English words that should be easier to remember.
  865. For example, the hex key EB33F77EE73D4053 is transformed to "TIDE ITCH
  866. SLOW REIN RULE MOT".
  867. **key_to_english(key)**:
  868. Accepts a string of arbitrary data ``key``, and returns a string
  869. containing uppercase English words separated by spaces. ``key``'s
  870. length must be a multiple of 8.
  871. **english_to_key(string)**:
  872. Accepts ``string`` containing English words, and returns a string of
  873. binary data representing the key. Words must be separated by
  874. whitespace, and can be any mixture of uppercase and lowercase
  875. characters. 6 words are required for 8 bytes of key data, so
  876. the number of words in ``string`` must be a multiple of 6.
  877. Extending the Toolkit
  878. --------------------------------------------------
  879. Preserving a common interface for cryptographic routines is a good
  880. idea. This chapter explains how to write new modules for the Toolkit.
  881. The basic process is as follows:
  882. 1. Add a new ``.c`` file containing an implementation of the new
  883. algorithm.
  884. This file must define 3 or 4 standard functions,
  885. a few constants, and a C ``struct`` encapsulating the state
  886. variables required by the algorithm.
  887. 2. Add the new algorithm to ``setup.py``.
  888. 3. Send a copy of the code to me, if you like; code for new
  889. algorithms will be gratefully accepted.
  890. Adding Hash Algorithms
  891. ==================================================
  892. The required constant definitions are as follows::
  893. #define MODULE_NAME MD2 /* Name of algorithm */
  894. #define DIGEST_SIZE 16 /* Size of resulting digest in bytes */
  895. The C structure must be named ``hash_state``::
  896. typedef struct {
  897. ... whatever state variables you need ...
  898. } hash_state;
  899. There are four functions that need to be written: to initialize the
  900. algorithm's state, to hash a string into the algorithm's state, to get
  901. a digest from the current state, and to copy a state.
  902. * ``void hash_init(hash_state *self);``
  903. * ``void hash_update(hash_state *self, unsigned char *buffer, int length);``
  904. * ``PyObject *hash_digest(hash_state *self);``
  905. * ``void hash_copy(hash_state *source, hash_state *dest);``
  906. Put ``#include "hash_template.c"`` at the end of the file to
  907. include the actual implementation of the module.
  908. Adding Block Encryption Algorithms
  909. ==================================================
  910. The required constant definitions are as follows::
  911. #define MODULE_NAME AES /* Name of algorithm */
  912. #define BLOCK_SIZE 16 /* Size of encryption block */
  913. #define KEY_SIZE 0 /* Size of key in bytes (0 if not fixed size) */
  914. The C structure must be named ``block_state``::
  915. typedef struct {
  916. ... whatever state variables you need ...
  917. } block_state;
  918. There are three functions that need to be written: to initialize the
  919. algorithm's state, and to encrypt and decrypt a single block.
  920. * ``void block_init(block_state *self, unsigned char *key, int keylen);``
  921. * ``void block_encrypt(block_state *self, unsigned char *in, unsigned char *out);``
  922. * ``void block_decrypt(block_state *self, unsigned char *in, unsigned char *out);``
  923. Put ``#include "block_template.c"`` at the end of the file to
  924. include the actual implementation of the module.
  925. Adding Stream Encryption Algorithms
  926. ==================================================
  927. The required constant definitions are as follows::
  928. #define MODULE_NAME ARC4 /* Name of algorithm */
  929. #define BLOCK_SIZE 1 /* Will always be 1 for a stream cipher */
  930. #define KEY_SIZE 0 /* Size of key in bytes (0 if not fixed size) */
  931. The C structure must be named ``stream_state``::
  932. typedef struct {
  933. ... whatever state variables you need ...
  934. } stream_state;
  935. There are three functions that need to be written: to initialize the
  936. algorithm's state, and to encrypt and decrypt a single block.
  937. * ``void stream_init(stream_state *self, unsigned char *key, int keylen);``
  938. * ``void stream_encrypt(stream_state *self, unsigned char *block, int length);``
  939. * ``void stream_decrypt(stream_state *self, unsigned char *block, int length);``
  940. Put ``#include "stream_template.c"`` at the end of the file to
  941. include the actual implementation of the module.