
    ,hjW                        g d Z ddlZddlZddlZddlmZmZmZmZm	Z	 ddl
mZ ddlmZmZ ddlmZ ddlmZmZmZmZmZ ddlmZ dd	lmZmZmZ dd
lmZmZm Z   G d de!      Z"d Z#ddZ$ddZ%d Z&d Z'd Z(d Z)d Z*ddZ+e+Z,dZ-y))generate	constructDsaKey
import_key    N)bchrbordtobytestostr
iter_range)Random)PKCS8PEM)SHA256)	DerObjectDerSequence
DerIntegerDerObjectIdDerBitString)Integer)test_probable_prime	COMPOSITEPROBABLY_PRIME)_expand_subject_public_key_info_create_subject_public_key_info _extract_subject_public_key_infoc                       e Zd ZdZg dZd Zd Zd Zd Zd Z	d Z
d	 Zd
 Zd Zd Zd Zd Zd Z	 	 ddZeZeZd Zd Zd Zd Zd Zd Zd Zy)r   a  Class 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
    ygpqxc           	      2   t        |j                               }t        d      }|j                  |      st        dt	        ||z
        z        ||z
  }|r1|t        d      k7  r#t        dt	        |t        d      z
        z        t        |      | _        y )Nr   r   r    r!   z$Some DSA components are missing = %sr"   zUnknown DSA components = %s)setkeysissubset
ValueErrorstrdict_key)selfkey_dict	input_set
public_set	extra_sets        V/var/www/html/Resume-Scraper/venv/lib/python3.12/site-packages/Crypto/PublicKey/DSA.py__init__zDsaKey.__init__g   s    (	./
""9-C i!789 : :
*	c&k1: S[!89: ; ;N	    c                    | j                         st        d      d|cxk  r| j                  k  st        d       t        d      dD cg c]  }| j                  |    c}\  }}}}t        j                  d|      }||z  j                  |      }	||z  }
t        |||      |z  }|	||z  |
|z  z   z  |z  }t        t        ||f      S c c}w )Nz)DSA public key cannot be used for signing   zk is not between 2 and q-1)r"   r!   r    r   )min_inclusivemax_exclusive)has_private	TypeErrorr!   r)   r,   r   random_rangeinversepowmapint)r-   mkcompr"   r!   r    r   blind_factorinv_blind_kblind_xrss                r2   _signzDsaKey._signs   s    !GHHA9:: 9::2FG$diioG
1a++!9:<#a'003l"1aL1L1,w{:;q@3A Hs   Cc                 2   |\  }}dD cg c]  }| j                   |    c}\  }}}}	d|cxk  r|k  rn yd|cxk  r|k  sy yt        |      j                  |      }
|
|z  |z  }|
|z  |z  }t        |	||      t        |||      z  |z  |z  }||k(  S c c}w )N)r   r!   r    r   r   F)r,   r   r<   r=   )r-   r@   sigrF   rG   rB   r   r!   r    r   wu1u2vs                 r2   _verifyzDsaKey._verify   s    12FG$diioG
1aA		 $%q919 $-AJq!!eq[!eq[B]SB]*Q.!3Av Hs   Bc                     d| j                   v S )z!Whether this is a DSA private keyr"   r,   r-   s    r2   r9   zDsaKey.has_private   s     diir4   c                      y)NF rR   s    r2   can_encryptzDsaKey.can_encrypt   s    r4   c                      y)NTrT   rR   s    r2   can_signzDsaKey.can_sign   s    r4   c                 B     t         fddD              }t        |      S )z^A matching DSA public key.

        Returns:
            a new :class:`DsaKey` object
        c              3   @   K   | ]  }|j                   |   f  y wNrQ   ).0rA   r-   s     r2   	<genexpr>z$DsaKey.public_key.<locals>.<genexpr>   s      Qq!TYYq\!2 Qs   r$   )r+   r   )r-   public_componentss   ` r2   
public_keyzDsaKey.public_key   s#     ! Q<P QQ'((r4   c                     t        | j                               t        |j                               k7  ryd}| j                  D ]5  }|xr/ t        | j                  |d       t        |j                  |d       k(  }7 |S )NFT)boolr9   _keydatagetattrr,   )r-   otherresultrB   s       r2   __eq__zDsaKey.__eq__   sz      "#tE,=,=,?'@@MM 	BD BD$!?!(T4!@"AF	B r4   c                 &    | j                  |       S rZ   )re   )r-   rc   s     r2   __ne__zDsaKey.__ne__   s    ;;u%%%r4   c                     ddl m} |)Nr   )PicklingError)pickleri   )r-   ri   s     r2   __getstate__zDsaKey.__getstate__   s    (r4   c                 X    dD cg c]  }t        | j                  |          c}S c c}w )zPThe DSA domain parameters.

        Returns
            tuple : (p,q,g)
        )r    r!   r   )r?   r,   )r-   rB   s     r2   domainzDsaKey.domain   s&     2AADIIdO$AAAs   'c                    g }| j                   D ]^  }|dk(  r9t        | j                        j                         }|j	                  d|fz         At        | |      sN|j	                  |       ` | j                         r|j	                  d       d| j                  j                  t        |       dj                  |      fz  S )Nr    zp(%d)privatez<%s @0x%x %s>,)ra   r   r    size_in_bitsappendhasattrr9   	__class____name__idjoin)r-   attrsrA   bitss       r2   __repr__zDsaKey.__repr__   s     	 ACxtvv335Ww./q!Q	  LL#$.."9"92d8SXXe_!UUUr4   c                 d    	 t        | j                  |         S # t        $ r t        |      w xY wrZ   )r?   r,   KeyErrorAttributeError)r-   items     r2   __getattr__zDsaKey.__getattr__   s4    	'tyy'' 	' &&	's    /Nc                    |t        |      }|t        j                  }|dk(  rdD cg c]  }| j                  |   j	                         ! }}d }|D cg c]
  } ||       }	}dg|	z   }
dj                  |
D cg c]$  }t        j                  dt        |            |z   & c}      }dt        j                  |      dd	 z   S t        | j                  | j                  | j                  g      }| j                         r|d
}|rP|sd}t!        | j"                        j%                         }t'        j(                  |t*        ||||      }|rd}nd}d}n|dk7  r|rt-        d      d| j                  | j                  | j                  | j.                  | j"                  g}t        |      j%                         }d}n3|rt-        d      t1        t*        t!        | j.                        |      }d}|dk(  r|S |dk(  r&t3        j$                  ||dz   ||      }t        |      S t-        d|z        c c}w c c}w c c}w )a  Export 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
        NOpenSSH)r    r!   r   r   c                 D    t        | d         dz  rt        d      | z   S | S )Nr      )r   r   r%   s    r2   funczDsaKey.export_key.<locals>.func  s%    1J%7Q;&Hr4      ssh-dssr4   >I   ssh-dss Tz"PBKDF2WithHMAC-SHA1AndDES-EDE3-CBC)
key_paramsrandfunczENCRYPTED PRIVATEPRIVATEr   z#DSA private key cannot be encryptedr   zDSA PRIVATEz*PKCS#8 is only meaningful for private keysPUBLICDERz KEYz3Unknown key format '%s'. Cannot export the DSA key.)r	   r   get_random_bytesr,   to_bytesrw   structpacklenbinascii
b2a_base64r   r    r!   r   r9   r   r"   encoder   wrapoidr)   r   r   r   )r-   formatpkcs8
passphrase
protectionr   r"   tup1r   tup2keypartskp	keystringparamsprivate_key
binary_keykey_typeintspem_strs                      r2   
export_keyzDsaKey.export_key   s6   v ! ,J..HY5IJDIIaL))+JDJ &**DG*D*"|d*HGOPV[[s2w7"<PI !4!4Y!?!DDD dffdffdff56}!!EJ(0779"ZZ +S* *v)1"

 2H(H!
U?z$%JKK466466466466466B(.557
( !MNN8 *466 2F<JHU?U?jj *Hv,= *HG 7##NQWWXXs K + Qs   $H4H9<)H>c                     t        d      Nz'Use module Crypto.Signature.DSS insteadNotImplementedError)r-   MKs      r2   signzDsaKey.signU      !"KLLr4   c                     t        d      r   r   )r-   r   	signatures      r2   verifyzDsaKey.verifyX  r   r4   c                     t         rZ   r   )r-   	plaintextr   s      r2   encryptzDsaKey.encrypt[      !!r4   c                     t         rZ   r   )r-   
ciphertexts     r2   decryptzDsaKey.decrypt^  r   r4   c                     t         rZ   r   r-   r   Bs      r2   blindzDsaKey.blinda  r   r4   c                     t         rZ   r   r   s      r2   unblindzDsaKey.unblindd  r   r4   c                     t         rZ   r   rR   s    r2   sizezDsaKey.sizeg  r   r4   )r   NNNN)ru   
__module____qualname____doc__ra   r3   rH   rO   r9   rU   rW   r^   re   rg   rk   rm   rz   r   r   	exportKey	publickeyr   r   r   r   r   r   r   rT   r4   r2   r   r   N   s    , )H
# "	 
)&
BV' ?C,0{Y| IIMM"""""r4   r   c           
         ddddj                  |       }|t        d| z        t        j                  dz  }| |z   dz
  |z  dz
  }| dz
  ||z  z
  }t	        d      }d|dz
  z  }t        ||      t        k7  r` |d	      }t	        j                  t        j                  |      j                               |dz
  z  }	|	|z  dz  }t        ||      t        k7  r`|j                         |k(  sJ d}
d| dz
  z  }	 t        |dz         D cg c]B  }t        j                  t	        |
|z         j                         z         j                         D }}|D cg c]  }t	        j                  |       }}t        t        |      D cg c]  }||   d||z  z  z   c}||   d|z  dz
  z  d||z  z  z        }t	        ||z         }|j                         | k(  sJ ||d
z  z  }||dz
  z
  }|j                         | k(  rt        ||      t        k(  rn
|
|dz   z  }
#|dz
  |z  }t        j                  d      D ]w  }dz   t!        d      z   t	        |      j                         z   }	t	        j                  t        j                  |	      j                               }t#        |||      }|dk7  sw n ||fS c c}w c c}w c c}w )z+Generate a new set of DSA domain parameters         )         zInvalid modulus length (%d)   r6      @      s   ggen)getr)   r   digest_sizer   r   r   
from_bytesnewdigestrq   r   r   sum	itertoolscountr   r=   )Lr   Noutlennb_r!   	upper_bitseedUoffsetjVrN   iWXcr    er   r   s                         r2   _generate_domainr   k  s    3(,,Q/Ay6:;;!#F	
VaF"Q&A	
Q!f*	B 	
Aa!eI
a
*n
<|vzz$/6689Y]K	MA a
*n
<
 >>q ! Fa!eI
!!a%(+ jj
 3 < < >>?FFH + +-.0g  #00Z]C1q6z*+C1!r'Q'A!f*,=>@ A	M"~~1$%QKQK>>q q(+~=!a% $ 
Q1A# 7NT!W$wu~'>'>'@@vzz!}33561aL6 q!T?3+0Cs   AJ8J=Kc                    |t         j                  }|rxt        t        |      \  }}}t	        |      t
        k(  }|t	        |      t
        k(  z  }||dz
  |z  dk7  z  }||dk  xs ||k\  z  }|t        |||      dk7  z  }|rt        d      t        | |      \  }}}}|j                         }|j                         }	|| k7  rt        d|| fz        ||	fdvrt        d||	fz        d|cxk  r|k  st        d       t        d      t        j                  |	dz   |	      }
|
|dz
  z  dz   }t        |||      }|||||d
}t        |      S )a  Generate 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
    r6   r   zInvalid DSA domain parametersz?Mismatch between size of modulus (%d) and 'bits' parameter (%d)))r   r   )r   r   )r   r   )r   r   z;Lengths of p and q (%d, %d) are not compatibleto FIPS 186-3zIncorrent DSA generatorr   )
exact_bitsr   r   )r   r   r>   r   r   r   r=   r)   r   rq   randomr   )ry   r   rm   r    r!   r   	fmt_error_r   r   r   r"   r   r.   s                 r2   r   r     s   < **gv&1a (*i7	(+y88	q1uka''	Q!V%qAv%	SAq\Q&&	<==%dH5
1a	A	ADy 69:D	B C 	C 	
1v 0 0 ),-q62 3 	3 q919233 233 	!b&8<A	QUaAAq!AA1!4H(r4   c           	      >   t        t        dt        t        |                   }t	        |      }d}|r\t        |j                        t        k(  }|t        |j                        t        k(  z  }||j                  dz
  |j                  z  dk7  z  }||j                  dk  xs |j                  |j                  k\  z  }|t        |j                  |j                  |j                        dk7  z  }||j                  dk  xs |j                  |j                  k\  z  }t        |d      rh||j                  dk  xs |j                  |j                  k\  z  }|t        |j                  |j                  |j                        |j                  k7  z  }|rt        d      |S )a  Construct 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
    r   Fr6   r   r"   zInvalid DSA key components)r+   zipr>   r   r   r   r    r   r!   r   r=   r   rs   r"   r)   )tupconsistency_checkr.   keyr   s        r2   r   r     sN   2 C13w3DEFH

CI'.);	(/9<<	suuqyCEE)a//	SUUaZ1355CEE>1	Ssuu-22	SUUaZ1355CEE>1	3!5suu~5ISUUCEE3551SUU::I566Jr4   c                     |rt        d      t               j                  | dd      }|d   dk7  rt        d      dD cg c]  }||   	 }}t        |      S c c}w )Nz-DSA private key already comes with parameters   T)nr_elementsonly_ints_expectedr   zNo version found)r      r6   r      )r)   r   decoder   )encodedr   r   derrB   r   s         r2   _import_openssl_privater   !  sg    HII
-

wA$

OC
1v{+,,!0
13t9
1C
1S> 2s   Ac                 "   t        |       \  }}}|t        k7  rt        d      |r|rt        d      t               j	                  |      j
                  }t        t               j	                  |xs |            \  }}}	||	||f}
t        |
      S )NzNo DSA subjectPublicKeyInfozToo many DSA parameters)	r   r   r)   r   r   valuelistr   r   )r   r   r   algoidencoded_key
emb_paramsr   r    r!   r   r   s              r2   _import_subjectPublicKeyInfor  +  s    'Fw'O#FK}677*233K(..A;=''(<*=>GAq!aA,CS>r4   c                 2    t        |       }t        |d |      S rZ   )r   r  )r   r   r   sp_infos       r2   _import_x509_certr  9  s    .w7G'v>>r4   c                 N   |rt        d      t        j                  | |      }|d   t        k7  rt        d      t	               j                  |d         j                  }t        t               j                  |d               \  }}}t        |||      ||||f}t        |      S )Nz"PKCS#8 already includes parametersr   zNo PKCS#8 encoded DSA keyr6   r   )r)   r   unwrapr   r   r   r   r  r   r=   r   )	r   r   r   rA   r"   r    r!   r   r   s	            r2   _import_pkcs8r  ?  s    =>>Wj)Ats{455AaD!''A;=''!-.GAq!q!Q<Aq!
$CS>r4   c                     t         t        t        t        f}|D ]  }	  || ||      c S  t	        d      # t        $ r Y 'w xY w)z?Import a DSA key (public or private half), encoded in DER form.DSA key format is not supported)r   r  r  r  r)   )key_datar   r   	decodingsdecodings        r2   _import_key_derr  K  s^     )-" I
  	Hj&99 6
77  		s   	5	A Ac                    t        |       } |t        |      }| j                  d      r4t        j                  t	        |       |      \  }}}|rd}t        ||d      S | j                  d      rt        j                  | j                  d      d         }g }t        |      dkD  rJt        j                  d|dd       d   }|j                  |dd|z           |d|z   d }t        |      dkD  rJ|d   d	k(  r0d
D cg c]  }t        j                  ||          }	}t        |	      S t        |       dkD  rt!        | d         dk(  rt        | |d      S t#        d      c c}w )a  Import 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   -----r       r6   r   r   r   r   )r   r   r6   r   0   r  )r	   
startswithr   r   r
   r  r   
a2b_base64splitr   r   unpackrr   r   r   r   r   r)   )

extern_keyr   r   markerenc_flagr   r   lengthr"   r   s
             r2   r   r   \  sf   P $JZ(
X&"%**U:->
"KfhJsJ55[)''
(8(8(>q(AB	)nq ]]42A7:FOOIaF
34!!f*+.I )nq  A;*$<HIq7%%hqk2ICIS>!
:tJqM2d:z:t<<
6
77 Js   <Ez1.2.840.10040.4.1)NN)TrZ   ).__all__r   r   r   Crypto.Util.py3compatr   r   r	   r
   r   Cryptor   	Crypto.IOr   r   Crypto.Hashr   Crypto.Util.asn1r   r   r   r   r   Crypto.Math.Numbersr   Crypto.Math.Primalityr   r   r   Crypto.PublicKeyr   r   r   objectr   r   r   r   r   r  r  r  r  r   	importKeyr   rT   r4   r2   <module>r(     s   2 =    H H      (3 3@ @@Z"V Z"z2jFR.p?	8"C8N 	 r4   