📄 pycrypt.tex
字号:
\begin{tableii}{c|l}{}{Cipher}{Key Size/Block Size}\lineii{AES}{16, 24, or 32 bytes/16 bytes}\lineii{ARC2}{Variable/8 bytes}\lineii{Blowfish}{Variable/8 bytes}\lineii{CAST}{Variable/8 bytes}\lineii{DES}{8 bytes/8 bytes}\lineii{DES3 (Triple DES)}{16 bytes/8 bytes}\lineii{IDEA}{16 bytes/8 bytes}\lineii{RC5}{Variable/8 bytes}\end{tableii}In a strict formal sense, \dfn{stream ciphers} encrypt data bit-by-bit;practically, stream ciphers work on a character-by-character basis.Stream ciphers use exactly thesame interface as block ciphers, with a block length that will alwaysbe 1; this is how block and stream ciphers can be distinguished. The only feedback mode available for stream ciphers is ECB mode. The currently available stream ciphers are listed in the following table:\begin{tableii}{c|l}{}{Cipher}{Key Size}\lineii{Cipher}{Key Size} \lineii{ARC4}{Variable} \lineii{XOR}{Variable}\end{tableii}ARC4 is short for `Alleged RC4'. In September of 1994, someone postedC code to both the Cypherpunks mailing list and to the Usenetnewsgroup \code{sci.crypt}, claiming that it implemented the RC4algorithm. This claim turned out to be correct. Note that there's adamaging class of weak RC4 keys; this module won't warn you about such keys.% XXX other analyses of RC4?A similar anonymous posting was made for Alleged RC2 in January, 1996.An example usage of the DES module:\begin{verbatim}>>> from Crypto.Cipher import DES>>> obj=DES.new('abcdefgh', DES.MODE_ECB)>>> plain="Guido van Rossum is a space alien.">>> len(plain)34>>> obj.encrypt(plain)Traceback (innermost last): File "<stdin>", line 1, in ?ValueError: Strings for DES must be a multiple of 8 in length>>> ciph=obj.encrypt(plain+'XXXXXX')>>> ciph'\021,\343Nq\214DY\337T\342pA\372\255\311s\210\363,\300j\330\250\312\347\342I\3215w\03561\303dgb/\006'>>> obj.decrypt(ciph)'Guido van Rossum is a space alien.XXXXXX'\end{verbatim}All cipher algorithms share a common interface. After importing agiven module, there is exactly one function and two variablesavailable.\begin{funcdesc}{new}{key, mode\optional{, IV}}Returns a ciphering object, using \var{key} and feedback mode\var{mode}. If \var{mode} is \constant{MODE_CBC} or \constant{MODE_CFB}, \var{IV} must be provided,and must be a string of the same length as the block size. Somealgorithms support additional keyword arguments to this function; seethe "Algorithm-specific Notes for Encryption Algorithms" section below for the details.\end{funcdesc}\begin{datadesc}{block_size}An integer value; the size of the blocks encrypted by this module.Strings passed to the \code{encrypt} and \code{decrypt} functionsmust be a multiple of this length. For stream ciphers,\code{block_size} will be 1. \end{datadesc}\begin{datadesc}{key_size}An integer value; the size of the keys required by this module. If\code{key_size} is zero, then the algorithm accepts arbitrary-lengthkeys. You cannot pass a key of length 0 (that is, the null string\code{''} as such a variable-length key. \end{datadesc}All cipher objects have at least three attributes:\begin{memberdesc}{block_size}An integer value equal to the size of the blocks encrypted by this object.Identical to the module variable of the same name.\end{memberdesc}\begin{memberdesc}{IV}Contains the initial value which will be used to start a cipherfeedback mode. After encrypting or decrypting a string, this valuewill reflect the modified feedback text; it will always be one blockin length. It is read-only, and cannot be assigned a new value.\end{memberdesc}\begin{memberdesc}{key_size}An integer value equal to the size of the keys used by this object. If\code{key_size} is zero, then the algorithm accepts arbitrary-lengthkeys. For algorithms that support variable length keys, this will be 0.Identical to the module variable of the same name. \end{memberdesc}All ciphering objects have the following methods:\begin{methoddesc}{decrypt}{string}Decrypts \var{string}, using the key-dependent data in the object, andwith the appropriate feedback mode. The string's length must be an exactmultiple of the algorithm's block size. Returns a string containingthe plaintext.\end{methoddesc}\begin{methoddesc}{encrypt}{string}Encrypts a non-null \var{string}, using the key-dependent data in theobject, and with the appropriate feedback mode. The string's lengthmust be an exact multiple of the algorithm's block size; for streamciphers, the string can be of any length. Returns a string containingthe ciphertext.\end{methoddesc}\subsection{Algorithm-specific Notes for Encryption Algorithms}RC5 has a bunch of parameters; see Ronald Rivest's paper at\url{http://theory.lcs.mit.edu/~rivest/rc5rev.ps} for theimplementation details. The keyword parameters are:\begin{itemize}\item \code{version}:The versionof the RC5 algorithm to use; currently the only legal value is\code{0x10} for RC5 1.0. \item \code{wordsize}:The word size to use;16 or 32 are the only legal values. (A larger word size is better, sousually 32 will be used. 16-bit RC5 is probably only of academicinterest.) \item \code{rounds}:The number of rounds to apply, the larger the more secure: thiscan be any value from 0 to 255, so you will have to choose a valuebalanced between speed and security. \end{itemize}\subsection{Security Notes}Encryption algorithms can be broken in several ways. If you have someciphertext and know (or can guess) the corresponding plaintext, you cansimply try every possible key in a \dfn{known-plaintext} attack. Or, itmight be possible to encrypt text of your choice using an unknown key;for example, you might mail someone a message intending it to beencrypted and forwarded to someone else. This is a\dfn{chosen-plaintext} attack, which is particularly effective if it'spossible to choose plaintexts that reveal something about the key whenencrypted.DES (5100 K/sec) has a 56-bit key; this is starting to become too smallfor safety. It has been estimated that it would only cost \$1,000,000 tobuild a custom DES-cracking machine that could find a key in 3 hours. Achosen-ciphertext attack using the technique of \dfn{linearcryptanalysis} can break DES in \code{pow(2, 43)} steps. However,unless you're encrypting data that you want to be safe from majorgovernments, DES will be fine. DES3 (1830 K/sec) uses three DESencryptions for greater security and a 112-bit or 168-bit key, but iscorrespondingly slower.There are no publicly known attacks against IDEA (3050 K/sec), andit's been around long enough to have been examined. There are noknown attacks against ARC2 (2160 K/sec), ARC4 (8830 K/sec), Blowfish(9250 K/sec), CAST (2960 K/sec), or RC5 (2060 K/sec), but they're allrelatively new algorithms and there hasn't been time for much analysisto be performed; use them for serious applications only after carefulresearch.AES, the Advanced Encryption Standard, was chosen by the US NationalInstitute of Standards and Technology from among 6 competitors, and isprobably your best choice. It runs at 7060 K/sec, so it's among thefaster algorithms around.\subsection{Credits}The code for Blowfish was written by Bryan Olson, partially based on aprevious implementation by Bruce Schneier, who also invented thealgorithm; the Blowfish algorithm has been placed in the public domainand can be used freely. (See \url{http://www.counterpane.com} for moreinformation about Blowfish.) The CAST implementation was written by Wim Lewis. The DES implementation was written by Eric Young, and theIDEA implementation by Colin Plumb. The RC5 implementationwas written by A.M. Kuchling.The Alleged RC4 code was posted to the \code{sci.crypt} newsgroup by anunknown party, and re-implemented by A.M. Kuchling. %======================================================================\section{Crypto.Protocol: Various Protocols}\subsection{Crypto.Protocol.AllOrNothing}This module implements all-or-nothing package transformations.An all-or-nothing package transformation is one in which some text istransformed into message blocks, such that all blocks must be obtained beforethe reverse transformation can be applied. Thus, if any blocks are corruptedor lost, the original message cannot be reproduced.An all-or-nothing package transformation is not encryption, although a blockcipher algorithm is used. The encryption key is randomly generated and isextractable from the message blocks.\begin{classdesc}{AllOrNothing}{ciphermodule, mode=None, IV=None}Class implementing the All-or-Nothing package transform.\var{ciphermodule} is a module implementing the cipher algorithm touse. Optional arguments \var{mode} and \var{IV} are passed directlythrough to the \var{ciphermodule}.\code{new()} method; they are thefeedback mode and initialization vector to use. All three argumentsmust be the same for the object used to create the digest, and toundigest'ify the message blocks.The module passed as \var{ciphermodule} must provide the \pep{272}interface. An encryption key is randomly generated automatically whenneeded.\end{classdesc}The methods of the \class{AllOrNothing} class are:\begin{methoddesc}{digest}{text}Perform the All-or-Nothing package transform on the string \var{text}. Output is a list of message blocks describing thetransformed text, where each block is a string of bit length equalto the cipher module's block_size.\end{methoddesc}\begin{methoddesc}{undigest}{mblocks}Perform the reverse package transformation on a list of messageblocks. Note that the cipher module used for both transformationsmust be the same. \var{mblocks} is a list of strings of bit lengthequal to \var{ciphermodule}'s block_size. The output is a string object.\end{methoddesc}\subsection{Crypto.Protocol.Chaffing}Winnowing and chaffing is a technique for enhancing privacy without requiringstrong encryption. In short, the technique takes a set of authenticatedmessage blocks (the wheat) and adds a number of chaff blocks which haverandomly chosen data and MAC fields. This means that to an adversary, thechaff blocks look as valid as the wheat blocks, and so the authenticationwould have to be performed on every block. By tailoring the number of chaffblocks added to the message, the sender can make breaking the messagecomputationally infeasible. There are many other interesting properties ofthe winnow/chaff technique.For example, say Alice is sending a message to Bob. She packetizes themessage and performs an all-or-nothing transformation on the packets. Thenshe authenticates each packet with a message authentication code (MAC). TheMAC is a hash of the data packet, and there is a secret key which she mustshare with Bob (key distribution is an exercise left to the reader). She thenadds a serial number to each packet, and sends the packets to Bob.Bob receives the packets, and using the shared secret authentication key,authenticates the MACs for each packet. Those packets that have bad MACs aresimply discarded. The remainder are sorted by serial number, and passedthrough the reverse all-or-nothing transform. The transform means that aneavesdropper (say Eve) must acquire all the packets before any of the data canbe read. If even one packet is missing, the data is useless.There's one twist: by adding chaff packets, Alice and Bob can make Eve's jobmuch harder, since Eve now has to break the shared secret key, or try everycombination of wheat and chaff packet to read any of the message. The coolthing is that Bob doesn't need to add any additional code; the chaff packetsare already filtered out because their MACs don't match (in all likelihood --since the data and MACs for the chaff packets are randomly chosen it ispossible, but very unlikely that a chaff MAC will match the chaff data). AndAlice need not even be the party adding the chaff! She could be completelyunaware that a third party, say Charles, is adding chaff packets to hermessages as they are transmitted.\begin{classdesc}{Chaff}{factor=1.0, blocksper=1}Class implementing the chaff adding algorithm. \var{factor} is the number of message blocks to add chaff to, expressed as a percentage between 0.0 and 1.0; the default value is 1.0.\var{blocksper} is the number of chaff blocks to include for each block being chaffed, and defaults to 1. The default settings add one chaff block to every message block. By changing the defaults, you can adjust how computationally difficult it could be for an adversary to brute-force crack the message. The difficulty is expressed as:\begin{verbatim}pow(blocksper, int(factor * number-of-blocks))\end{verbatim}For ease of implementation, when \var{factor} < 1.0, only the first\code{int(\var{factor}*number-of-blocks)} message blocks are chaffed.\end{classdesc}\class{Chaff} instances have the following methods:\begin{methoddesc}{chaff}{blocks}Add chaff to message blocks. \var{blocks} is a list of 3-tuples of theform (\var{serial-number}, \var{data}, \var{MAC}).
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -