U +MbjW@s"ddddgZddlZddlZddlZddlmZmZmZmZm Z ddl m Z ddl m Z mZdd lmZdd lmZmZmZmZmZdd lmZdd lmZmZmZdd lmZmZm Z Gddde!Z"ddZ#d ddZ$d!ddZ%ddZ&ddZ'ddZ(ddZ)ddZ*d"ddZ+e+Z,dZ-dS)#generate constructDsaKey import_keyN)bchrbordtobytestostr iter_range)Random)PKCS8PEM)SHA256) DerObject DerSequence DerInteger DerObjectId DerBitString)Integer)test_probable_prime COMPOSITEPROBABLY_PRIME)_expand_subject_public_key_info_create_subject_public_key_info _extract_subject_public_key_infoc@seZdZdZdddddgZddZd d Zd d Zd dZddZ ddZ ddZ ddZ ddZ ddZddZddZdd Zd3d#d$ZeZe Zd%d&Zd'd(Zd)d*Zd+d,Zd-d.Zd/d0Zd1d2Zd"S)4raClass defining an actual DSA key. Do not instantiate directly. Use :func:`generate`, :func:`construct` or :func:`import_key` instead. :ivar p: DSA modulus :vartype p: integer :ivar q: Order of the subgroup :vartype q: integer :ivar g: Generator :vartype g: integer :ivar y: Public key :vartype y: integer :ivar x: Private key :vartype x: integer :undocumented: exportKey, publickey ygpqxcCspt|}td}||s2tdt||||}|rb|tdkrbtdt|tdt||_dS)Nrrrrz$Some DSA components are missing = %srzUnknown DSA components = %s)setkeysissubset ValueErrorstrdict_key)selfkey_dictZ input_setZ public_setZ extra_setr+;/tmp/pip-target-t616c12r/lib/python/Crypto/PublicKey/DSA.py__init__gs   zDsaKey.__init__c sstdd|kr&jks0ntdfdddD\}}}}tjd|d}|||}||} t||||} |||| | |} tt | | fS)Nz)DSA public key cannot be used for signingzk is not between 2 and q-1csg|]}j|qSr+r(.0compr)r+r, ysz DsaKey._sign..)rrrr)Z min_inclusiveZ max_exclusive) has_private TypeErrorrr%rZ random_rangeinversepowmapint) r)mkrrrrZ blind_factorZ inv_blind_kZblind_xrsr+r3r,_signssz DsaKey._signc s|\}}fdddD\}}}}d|kr6|krPnnd|krN|ksTndSt||} | ||} | ||} t|| |t|| |||} | |kS)Ncsg|]}j|qSr+r/r0r3r+r,r4sz"DsaKey._verify..)rrrrrF)rr7r8) r)r;sigr=r>rrrrwu1u2vr+r3r,_verifys.   zDsaKey._verifycCs d|jkS)z!Whether this is a DSA private keyrr/r3r+r+r,r5szDsaKey.has_privatecCsdS)NFr+r3r+r+r, can_encryptszDsaKey.can_encryptcCsdS)NTr+r3r+r+r,can_signszDsaKey.can_signcstfdddD}t|S)z^A matching DSA public key. Returns: a new :class:`DsaKey` object c3s|]}|j|fVqdSNr/)r1r<r3r+r, sz$DsaKey.public_key..r )r'r)r)Zpublic_componentsr+r3r, public_keyszDsaKey.public_keycCsPt|t|krdSd}|jD]$}|oHt|j|dt|j|dk}q&|S)NFT)boolr5_keydatagetattrr()r)otherresultr2r+r+r,__eq__s  z DsaKey.__eq__cCs || SrH)rP)r)rNr+r+r,__ne__sz DsaKey.__ne__cCsddlm}|dS)Nr) PicklingError)picklerR)r)rRr+r+r, __getstate__s zDsaKey.__getstate__csfdddDS)zPThe DSA domain parameters. Returns tuple : (p,q,g) csg|]}tj|qSr+)r:r(r0r3r+r,r4sz!DsaKey.domain..)rrrr+r3r+r3r,domainsz DsaKey.domaincCszg}|jD]@}|dkr6t|j}|d|fq t||r ||q |r^|dd|jjt |d |fS)Nrzp(%d)privatez <%s @0x%x %s>,) rLrr size_in_bitsappendhasattrr5 __class____name__idjoin)r)attrsr<bitsr+r+r,__repr__s    zDsaKey.__repr__cCs2zt|j|WStk r,t|YnXdSrH)r:r(KeyErrorAttributeError)r)itemr+r+r, __getattr__szDsaKey.__getattr__r Ncs|dk rt|}|dkrtj}|dkrfdddD}ddfdd|D}d g|}d d d|D} d t| dd Stjjj g}  r8|dkrd}|r|sd}t j  } tj| t||| |d} |rd} nd} d}nB|dkr |r tddjjj jj g}t| } d} n$|rFtdttt j| } d} |dkrj| S|dkrt | | d||}t|Std|dS)aExport this DSA key. Args: format (string): The encoding for the output: - *'PEM'* (default). ASCII as per `RFC1421`_/ `RFC1423`_. - *'DER'*. Binary ASN.1 encoding. - *'OpenSSH'*. ASCII one-liner as per `RFC4253`_. Only suitable for public keys, not for private keys. passphrase (string): *Private keys only*. The pass phrase to protect the output. pkcs8 (boolean): *Private keys only*. If ``True`` (default), the key is encoded with `PKCS#8`_. If ``False``, it is encoded in the custom OpenSSL/OpenSSH container. protection (string): *Only in combination with a pass phrase*. The encryption scheme to use to protect the output. If :data:`pkcs8` takes value ``True``, this is the PKCS#8 algorithm to use for deriving the secret and encrypting the private DSA key. For a complete list of algorithms, see :mod:`Crypto.IO.PKCS8`. The default is *PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC*. If :data:`pkcs8` is ``False``, the obsolete PEM encryption scheme is used. It is based on MD5 for key derivation, and Triple DES for encryption. Parameter :data:`protection` is then ignored. The combination ``format='DER'`` and ``pkcs8=False`` is not allowed if a passphrase is present. randfunc (callable): A function that returns random bytes. By default it is :func:`Crypto.Random.get_random_bytes`. Returns: byte string : the encoded key Raises: ValueError : when the format is unknown or when you try to encrypt a private key with *DER* format and OpenSSL/OpenSSH. .. warning:: If you don't provide a pass phrase, the private key will be exported in the clear! .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt .. _`PKCS#8`: http://www.ietf.org/rfc/rfc5208.txt NZOpenSSHcsg|]}j|qSr+)r(to_bytesr1rr3r+r,r4sz%DsaKey.export_key..)rrrrcSs$t|dd@rtd|S|SdS)Nr)rrr!r+r+r,funcs zDsaKey.export_key..funccsg|] }|qSr+r+rg)rir+r,r4sssh-dsscSs g|]}tdt||qS)>I)structpacklen)r1kpr+r+r,r4sssh-dss Tz"PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC)Z key_paramsrandfunczENCRYPTED PRIVATEZPRIVATEr z#DSA private key cannot be encryptedrz DSA PRIVATEz*PKCS#8 is only meaningful for private keysZPUBLICZDERz KEYz3Unknown key format '%s'. Cannot export the DSA key.)rr get_random_bytesr^binascii b2a_base64rrrrr5rrencoder wrapoidr%rrr )r)formatZpkcs8 passphraseZ protectionrsZtup1Ztup2keyparts keystringparams private_keyZ binary_keyZkey_typeZintsZpem_strr+)rir)r, export_keysp;      zDsaKey.export_keycCs tddSNz'Use module Crypto.Signature.DSS insteadNotImplementedError)r)MKr+r+r,signUsz DsaKey.signcCs tddSrr)r)r signaturer+r+r,verifyXsz DsaKey.verifycCstdSrHr)r) plaintextrr+r+r,encrypt[szDsaKey.encryptcCstdSrHr)r)Z ciphertextr+r+r,decrypt^szDsaKey.decryptcCstdSrHrr)rBr+r+r,blindasz DsaKey.blindcCstdSrHrrr+r+r,unblinddszDsaKey.unblindcCstdSrHrr3r+r+r,sizegsz DsaKey.size)r NNNN)r\ __module__ __qualname____doc__rLr-r?rEr5rFrGrJrPrQrTrUrarerZ exportKeyZ publickeyrrrrrrrr+r+r+r,rNs8       ~csdddd|}|dkr&td|tjd|dd}|d|}td }d|d>}t||tkr|d tt |d@}||BdB}qh| |kst dd|d>}fd d t |dDd d Dt fdd t |D|d|>d@d|>}t||} | |ksJt | |d} | | d} | |krt| |tkrq|d7q| d|} tdD]R} dtdt| }tt| }t|| | }|dkrqq| ||fS)z+Generate a new set of DSA domain parameters) NzInvalid modulus length (%d)r.@cs*g|]"}tt|qSr+)rnewrrfdigest)r1j)offsetseedr+r,r4sz$_generate_domain..cSsg|]}t|qSr+r from_bytes)r1rDr+r+r,r4scs g|]}|d|>qS)r.r+)r1i)Voutlenr+r,r4ssggen)getr%r digest_sizerrrrrrrXAssertionErrorr sum itertoolscountrrfr8)LrsNnZb_rZ upper_bitUWXcrerrr+)rrrrr,_generate_domainksN              rcCsB|dkrtj}|rtt|\}}}t|tk}|t|tkO}||d|dkO}||dkpb||kO}|t|||dkO}|rtdnt||\}}}}| }| } ||krtd||f|| fdkrtd|| fd|kr|ksntdtj | d |d } | |dd} t|| |} | |||| d } t | S) aGenerate a new DSA key pair. The algorithm follows Appendix A.1/A.2 and B.1 of `FIPS 186-4`_, respectively for domain generation and key pair generation. Args: bits (integer): Key length, or size (in bits) of the DSA modulus *p*. It must be 1024, 2048 or 3072. randfunc (callable): Random number generation function; it accepts a single integer N and return a string of random data N bytes long. If not specified, :func:`Crypto.Random.get_random_bytes` is used. domain (tuple): The DSA domain parameters *p*, *q* and *g* as a list of 3 integers. Size of *p* and *q* must comply to `FIPS 186-4`_. If not specified, the parameters are created anew. Returns: :class:`DsaKey` : a new DSA key object Raises: ValueError : when **bits** is too little, too big, or not a multiple of 64. .. _FIPS 186-4: http://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.186-4.pdf Nr.rzInvalid DSA domain parametersz?Mismatch between size of modulus (%d) and 'bits' parameter (%d)))rr)rr)rr)rrz;Lengths of p and q (%d, %d) are not compatibleto FIPS 186-3zIncorrent DSA generatorr)Z exact_bitsrsrrrrr) r rtr9rrrr8r%rrXrandomr)r`rsrUrrr fmt_error_rrrrrr*r+r+r,rs:    TcCsttdtt|}t|}d}|rt|jtk}|t|jtkO}||jd|jdkO}||j dkpr|j |jkO}|t |j |j|jdkO}||j dkp|j |jkO}t |dr||j dkp|j |jkO}|t |j |j |j|j kO}|rtd|S)aConstruct a DSA key from a tuple of valid DSA components. Args: tup (tuple): A tuple of long integers, with 4 or 5 items in the following order: 1. Public key (*y*). 2. Sub-group generator (*g*). 3. Modulus, finite field order (*p*). 4. Sub-group order (*q*). 5. Private key (*x*). Optional. consistency_check (boolean): If ``True``, the library will verify that the provided components fulfil the main DSA properties. Raises: ValueError: when the key being imported fails the most basic DSA validity checks. Returns: :class:`DsaKey` : a DSA key object rFr.rrzInvalid DSA key components)r'zipr9rrrrrrrr8rrZrr%)tupZconsistency_checkr*keyrr+r+r,rs  csL|r tdtj|dddddkr2tdfddd D}t|S) Nz-DSA private key already comes with parametersT)Z nr_elementsZonly_ints_expectedrzNo version foundcsg|] }|qSr+r+r0derr+r,r4'sz+_import_openssl_private..)rr.r)r%rdecoder)encodedr{r~rr+rr,_import_openssl_private!s rc Csjt|\}}}|tkrtd|r.|r.tdt|j}tt|pJ|\}}} || ||f} t| S)NzNo DSA subjectPublicKeyInfozToo many DSA parameters) rryr%rrvaluelistrr) rr{r~ZalgoidZ encoded_keyZ emb_paramsrrrrrr+r+r,_import_subjectPublicKeyInfo+s rcCst|}t|d|SrH)rr)rr{r~Zsp_infor+r+r,_import_x509_cert9src Csv|r tdt||}|dtkr,tdt|dj}tt|d\}}}t |||||||f}t |S)Nz"PKCS#8 already includes parametersrzNo PKCS#8 encoded DSA keyr.r) r%r unwrapryrrrrrr8r) rr{r~r<rrrrrr+r+r, _import_pkcs8?s  rc CsJttttf}|D],}z||||WStk r:YqXqtddS)z?Import a DSA key (public or private half), encoded in DER form.DSA key format is not supportedN)rrrrr%)Zkey_datar{r~Z decodingsZdecodingr+r+r,_import_key_derKsrcst|}|dk rt|}|drLtt||\}}}|r@d}t||dS|drt|dd}gt |dkrt d|ddd} |dd||d|d}qndd krfd d d D}t |St |dkr t|dd kr t||dStddS)aImport a DSA key. Args: extern_key (string or byte string): The DSA key to import. The following formats are supported for a DSA **public** key: - X.509 certificate (binary DER or PEM) - X.509 ``subjectPublicKeyInfo`` (binary DER or PEM) - OpenSSH (ASCII one-liner, see `RFC4253`_) The following formats are supported for a DSA **private** key: - `PKCS#8`_ ``PrivateKeyInfo`` or ``EncryptedPrivateKeyInfo`` DER SEQUENCE (binary or PEM) - OpenSSL/OpenSSH custom format (binary or PEM) For details about the PEM encoding, see `RFC1421`_/`RFC1423`_. passphrase (string): In case of an encrypted private key, this is the pass phrase from which the decryption key is derived. Encryption may be applied either at the `PKCS#8`_ or at the PEM level. Returns: :class:`DsaKey` : a DSA key object Raises: ValueError : when the given key cannot be parsed (possibly because the pass phrase is wrong). .. _RFC1421: http://www.ietf.org/rfc/rfc1421.txt .. _RFC1423: http://www.ietf.org/rfc/rfc1423.txt .. _RFC4253: http://www.ietf.org/rfc/rfc4253.txt .. _PKCS#8: http://www.ietf.org/rfc/rfc5208.txt Ns-----rq r.rrlrrjcsg|]}t|qSr+rrgr|r+r,r4szimport_key..)rrr.r0r)r startswithr rr rru a2b_base64splitrormunpackrYrrr%)Z extern_keyr{rmarkerZenc_flagr}lengthrr+rr,r\s*(       z1.2.840.10040.4.1)NN)T)N).__all__rurmrZCrypto.Util.py3compatrrrr r ZCryptor Z Crypto.IOr r Z Crypto.HashrZCrypto.Util.asn1rrrrrZCrypto.Math.NumbersrZCrypto.Math.PrimalityrrrZCrypto.PublicKeyrrrobjectrrrrrrrrrrZ importKeyryr+r+r+r,s2     5 I 8   G