⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pycrypt.tex

📁 python的加密库
💻 TEX
📖 第 1 页 / 共 4 页
字号:
Chaff is created by choosing a random number of the samebyte-length as \var{data}, and another random number of the samebyte-length as \var{MAC}.  The message block's serial number is placedon the chaff block and all the packet's chaff blocks are randomlyinterspersed with the single wheat block.  This method thenreturns a list of 3-tuples of the same form.  Chaffed blocks willcontain multiple instances of 3-tuples with the same serialnumber, but the only way to figure out which blocks are wheat andwhich are chaff is to perform the MAC hash and compare values.\end{methoddesc}%======================================================================\section{Crypto.PublicKey: Public-Key Algorithms}So far, the encryption algorithms described have all been \dfn{privatekey} ciphers.  The same key is used for both encryption and decryptionso all correspondents must know it.  This poses a problem: you maywant encryption to communicate sensitive data over an insecurechannel, but how can you tell your correspondent what the key is?  Youcan't just e-mail it to her because the channel is insecure.  Onesolution is to arrange the key via some other way: over the phone orby meeting in person.Another solution is to use \dfn{public-key} cryptography.  In a publickey system, there are two different keys: one for encryption and one fordecryption.  The encryption key can be made public by listing it in adirectory or mailing it to your correspondent, while you keep thedecryption key secret.  Your correspondent then sends you data encryptedwith your public key, and you use the private key to decrypt it.  Whilethe two keys are related, it's very difficult to derive the private keygiven only the public key; however, deriving the private key is alwayspossible given enough time and computing power.  This makes it veryimportant to pick keys of the right size: large enough to be secure, butsmall enough to be applied fairly quickly.Many public-key algorithms can also be used to sign messages; simplyrun the message to be signed through a decryption with your privatekey key.  Anyone receiving the message can encrypt it with yourpublicly available key and read the message.  Some algorithms do onlyone thing, others can both encrypt and authenticate.The currently available public-key algorithms are listed in thefollowing table:\begin{tableii}{c|l}{}{Algorithm}{Capabilities}\lineii{RSA}{Encryption, authentication/signatures}\lineii{ElGamal}{Encryption, authentication/signatures}\lineii{DSA}{Authentication/signatures}\lineii{qNEW}{Authentication/signatures}\end{tableii}Many of these algorithms are patented.  Before using any of them in acommercial product, consult a patent attorney; you may have to arrangea license with the patent holder.An example of using the RSA module to sign a message:\begin{verbatim}>>> from Crypto.Hash import MD5>>> from Crypto.PublicKey import RSA>>> RSAkey = RSA.generate(384, randfunc)   # This will take a while...>>> hash = MD5.new(plaintext).digest()>>> signature = RSAkey.sign(hash, "")>>> signature   # Print what an RSA sig looks like--you don't really care.('\021\317\313\336\264\315' ...,)>>> RSAkey.verify(hash, signature)     # This sig will check out1>>> RSAkey.verify(hash[:-1], signature)# This sig will fail0\end{verbatim}Public-key modules make the following functions available:\begin{funcdesc}{construct}{tuple}Constructs a key object from a tuple of data.  This isalgorithm-specific; look at the source code for the details.  (To bedocumented later.)\end{funcdesc}\begin{funcdesc}{generate}{size, randfunc, progress_func=\code{None}}Generate a fresh public/private key pair.  \var{size} is aalgorithm-dependent size parameter, usually measured in bits; thelarger it is, the more difficult it will be to break the key.  Safekey sizes vary from algorithm to algorithm; you'll have to researchthe question and decide on a suitable key size for your application.An N-bit keys can encrypt messages up to N-1 bits long.\var{randfunc} is a random number generation function; it shouldaccept a single integer \var{N} and return a string of random data\var{N} bytes long.  You should always use a cryptographically securerandom number generator, such as the one defined in the\module{Crypto.Util.randpool} module; \emph{don't} just use thecurrent time and the \module{random} module. \var{progress_func} is an optional function that will be called with a shortstring containing the key parameter currently being generated; it'suseful for interactive applications where a user is waiting for a keyto be generated.\end{funcdesc}If you want to interface with some other program, you will have to knowthe details of the algorithm being used; this isn't a big loss.  If youdon't care about working with non-Python software, simply use the\module{pickle} module when you need to write a key or a signature to afile.  It's portable across all the architectures that Python supports,and it's simple to use.Public-key objects always support the following methods.  Some of themmay raise exceptions if their functionality is not supported by thealgorithm.\begin{methoddesc}{can_blind}{}Returns true if the algorithm is capable of blinding data; returns false otherwise.  \end{methoddesc}\begin{methoddesc}{can_encrypt}{}Returns true if the algorithm is capable of encrypting and decryptingdata; returns false otherwise.  To test if a given key object can encryptdata, use \code{key.can_encrypt() and key.has_private()}.\end{methoddesc}\begin{methoddesc}{can_sign}{}Returns true if the algorithm is capable of signing data; returns falseotherwise.  To test if a given key object can sign data, use\code{key.can_sign() and key.has_private()}.\end{methoddesc}\begin{methoddesc}{decrypt}{tuple}Decrypts \var{tuple} with the private key, returning another string.This requires the private key to be present, and will raise an exceptionif it isn't present.  It will also raise an exception if \var{string} istoo long.\end{methoddesc}\begin{methoddesc}{encrypt}{string, K}Encrypts \var{string} with the private key, returning a tuple ofstrings; the length of the tuple varies from algorithm to algorithm.  \var{K} should be a string of random data that is as long aspossible.  Encryption does not require the private key to be presentinside the key object.  It will raise an exception if \var{string} istoo long.  For ElGamal objects, the value of \var{K} expressed as abig-endian integer must be relatively prime to \code{self.p-1}; anexception is raised if it is not.\end{methoddesc}\begin{methoddesc}{has_private}{}Returns true if the key object contains the private key data, whichwill allow decrypting data and generating signatures.Otherwise this returns false.\end{methoddesc}\begin{methoddesc}{publickey}{}Returns a new public key object that doesn't contain the private keydata. \end{methoddesc}\begin{methoddesc}{sign}{string, K}Sign \var{string}, returning a signature, which is just a tuple; intheory the signature may be made up of any Python objects at all; inpractice they'll be either strings or numbers.  \var{K} should be astring of random data that is as long as possible.  Different algorithmswill return tuples of different sizes.  \code{sign()} raises anexception if \var{string} is too long.  For ElGamal objects, the valueof \var{K} expressed as a big-endian integer must be relatively prime to\code{self.p-1}; an exception is raised if it is not.\end{methoddesc}\begin{methoddesc}{size}{}Returns the maximum size of a string that can be encrypted or signed,measured in bits.  String data is treated in big-endian format; the mostsignificant byte comes first.  (This seems to be a \emph{de facto} standardfor cryptographical software.)  If the size is not a multiple of 8, thensome of the high order bits of the first byte must be zero.  Usuallyit's simplest to just divide the size by 8 and round down.\end{methoddesc}\begin{methoddesc}{verify}{string, signature}Returns true if the signature is valid, and false otherwise.\var{string} is not processed in any way; \code{verify} doesnot run a hash function over the data, but you can easily do that yourself.\end{methoddesc}\subsection{The ElGamal and DSA algorithms}For RSA, the \var{K} parameters are unused; if you like, you can justpass empty strings.  The ElGamal and DSA algorithms require a real\var{K} value for technical reasons; see Schneier's book for a detailedexplanation of the respective algorithms.  This presents a possiblehazard that can  inadvertently reveal the private key.  Without going into themathematical details, the danger is as follows. \var{K} is never derivedor needed by others; theoretically, it can be thrown away once theencryption or signing operation is performed.  However, revealing\var{K} for a given message would enable others to derive the secret keydata; worse, reusing the same value of \var{K} for two differentmessages would also enable someone to derive the secret key data.  Anadversary could intercept and store every message, and then try derivingthe secret key from each pair of messages.This places implementors on the horns of a dilemma.  On the one hand,you want to store the \var{K} values to avoid reusing one; on the otherhand, storing them means they could fall into the hands of an adversary.One can randomly generate \var{K} values of a suitable length such as128 or 144 bits, and then trust that the random number generatorprobably won't produce a duplicate anytime soon.  This is animplementation decision that depends on the desired level of securityand the expected usage lifetime of a private key.  I can't choose andenforce one policy for this, so I've added the \var{K} parameter to the\method{encrypt} and \method{sign} methods.  You must choose \var{K} bygenerating a string of random data; for ElGamal, when interpreted as abig-endian number (with the most significant byte being the first byteof the string), \var{K} must be relatively prime to \code{self.p-1}; anysize will do, but brute force searches would probably start with smallprimes, so it's probably good to choose fairly large numbers.  It might besimplest to generate a prime number of a suitable length using the\module{Crypto.Util.number} module.\subsection{Security Notes for Public-key Algorithms}Any of these algorithms can be trivially broken; for example, RSA can bebroken by factoring the modulus \emph{n} into its two prime factors.This is easily done by the following code:\begin{verbatim}for i in range(2, n):     if (n%i)==0:         print i, 'is a factor'         break\end{verbatim}However, \emph{n} is usually a few hundred bits long, so this simpleprogram wouldn't find a solution before the universe comes to an end.Smarter algorithms can factor numbers more quickly, but it's stillpossible to choose keys so large that they can't be broken in areasonable amount of time.  For ElGamal and DSA, discrete logarithms areused instead of factoring, but the principle is the same.Safe key sizes depend on the current state of number theory andcomputer technology.  At the moment, one can roughly define threelevels of security: low-security commercial, high-security commercial,and military-grade.  For RSA, these three levels correspond roughly to768, 1024, and 2048-bit keys.%======================================================================\section{Crypto.Util: Odds and Ends}This chapter contains all the modules that don't fit into any of theother chapters.  \subsection{Crypto.Util.number}This module contains various number-theoretic functions.  \begin{funcdesc}{GCD}{x,y}Return the greatest common divisor of \var{x} and \var{y}.\end{funcdesc}\begin{funcdesc}{getPrime}{N, randfunc}Return an \var{N}-bit random prime number, using random data obtainedfrom the function \var{randfunc}.  \var{randfunc} must take a singleinteger argument, and return a string of random data of thecorresponding length; the \method{get_bytes()} method of a\class{RandomPool} object will serve the purpose nicely, as will the\method{read()} method of an opened file such as \file{/dev/random}.\end{funcdesc}\begin{funcdesc}{getRandomNumber}{N, randfunc}Return an \var{N}-bit random number, using random data obtained from thefunction \var{randfunc}.  As usual, \var{randfunc} must take a singleinteger argument and return a string of random data of thecorresponding length.\end{funcdesc}\begin{funcdesc}{inverse}{u, v}Return the inverse of \var{u} modulo \var{v}.\end{funcdesc}\begin{funcdesc}{isPrime}{N}Returns true if the number \var{N} is prime, as determined by aRabin-Miller test.\end{funcdesc}\subsection{Crypto.Util.randpool}For cryptographic purposes, ordinary random number generators arefrequently insufficient, because if some of their output is known, itis frequently possible to derive the generator's future (or past)output.  Given the generator's state at some point in time, someonecould try to derive any keys generated using it.  The solution is touse strong encryption or hashing algorithms to generate successivedata; this makes breaking the generator as difficult as breaking thealgorithms used.Understanding the concept of \dfn{entropy} is important for using therandom number generator properly.  In the sense we'll be using it,entropy measures the amount of randomness; the usual unit is in bits.So, a single random bit has an entropy of 1 bit; a random byte has an

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -