
    ÿigW                        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-dS ))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dS )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           	         t          |                                          }t          d          }|                    |          s"t          dt	          ||z
            z            ||z
  }|rB|t          d          k    r/t          dt	          |t          d          z
            z            t          |          | _        d S )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        T/var/www/html/afkarena/venv/lib/python3.11/site-packages/Cryptodome/PublicKey/DSA.py__init__zDsaKey.__init__g   s    ((	.//
""9-- 	:C i!7889 : : :
*	 	;c&kk11: S[[!899: ; ; ;NN			    c                                                       st          d          d|cxk     r j        k     sn t          d           fddD             \  }}}}t	          j        d|          }||z                      |          }||z  }	t          |||          |z  }
|||z  |	|
z  z   z  |z  }t          t          |
|f          S )Nz)DSA public key cannot be used for signing   zk is not between 2 and q-1c                 *    g | ]}j         |         S  r,   .0compr-   s     r2   
<listcomp>z DsaKey._sign.<locals>.<listcomp>y       GGG$dioGGGr4   )r"   r!   r    r   )min_inclusivemax_exclusive)
has_private	TypeErrorr!   r)   r   random_rangeinversepowmapint)r-   mkr"   r!   r    r   blind_factorinv_blind_kblind_xrss   `           r2   _signzDsaKey._signs   s    !! 	IGHHHA9:::GGGG2FGGG
1a+!9:< < <#a'0033l"1aLL1L1,w{:;q@3Ar4   c                 8    |\  }} fddD             \  }}}}d|cxk     r|k     rn nd|cxk     r|k     sn dS t          |                              |          }	|	|z  |z  }
|	|z  |z  }t          ||
|          t          |||          z  |z  |z  }||k    S )Nc                 *    g | ]}j         |         S r8   r9   r:   s     r2   r=   z"DsaKey._verify.<locals>.<listcomp>   r>   r4   )r   r!   r    r   r   F)r   rD   rE   )r-   rH   sigrM   rN   r   r!   r    r   wu1u2vs   `            r2   _verifyzDsaKey._verify   s    1GGGG2FGGG
1aA									1q9999199995AJJq!!!eq[!eq[B]]SB]]*Q.!3Avr4   c                     d| j         v S )z!Whether this is a DSA private keyr"   r9   r-   s    r2   rA   zDsaKey.has_private   s     dir4   c                     dS )NFr8   rY   s    r2   can_encryptzDsaKey.can_encrypt   s    ur4   c                     dS )NTr8   rY   s    r2   can_signzDsaKey.can_sign   s    tr4   c                 X     t           fddD                       }t          |          S )z^A matching DSA public key.

        Returns:
            a new :class:`DsaKey` object
        c              3   6   K   | ]}|j         |         fV  d S Nr9   )r;   rI   r-   s     r2   	<genexpr>z$DsaKey.public_key.<locals>.<genexpr>   s.       Q Qq!TYq\!2 Q Q Q Q Q Qr4   r$   )r+   r   )r-   public_componentss   ` r2   
public_keyzDsaKey.public_key   s8     ! Q Q Q Q<P Q Q QQQ'(((r4   c                 
   t          |                                           t          |                                          k    rdS d}| j        D ]2}|o-t          | j        |d           t          |j        |d           k    }3|S )NFT)boolrA   _keydatagetattrr,   )r-   otherresultr<   s       r2   __eq__zDsaKey.__eq__   s      ""##tE,=,=,?,?'@'@@@5M 	B 	BD BD$!?!?!(T4!@!@"AFFr4   c                 .    |                      |           S r`   )rj   )r-   rh   s     r2   __ne__zDsaKey.__ne__   s    ;;u%%%%r4   c                     ddl m} |)Nr   )PicklingError)picklern   )r-   rn   s     r2   __getstate__zDsaKey.__getstate__   s    ((((((r4   c                        fddD             S )zPThe DSA domain parameters.

        Returns
            tuple : (p,q,g)
        c                 D    g | ]}t          j        |                   S r8   )rG   r,   r:   s     r2   r=   z!DsaKey.domain.<locals>.<listcomp>   s'    AAADIdO$$AAAr4   )r    r!   r   r8   rY   s   `r2   domainzDsaKey.domain   s      BAAAAAAAr4   c                    g }| j         D ]m}|dk    r@t          | j                                                  }|                    d|fz             Ht          | |          r|                    |           n|                                 r|                    d           d| j        j        t          |           d
                    |          fz  S )Nr    zp(%d)privatez<%s @0x%x %s>,)rf   r   r    size_in_bitsappendhasattrrA   	__class____name__idjoin)r-   attrsrI   bitss       r2   __repr__zDsaKey.__repr__   s     	  	 ACxxtv3355Ww.////q!!  Q 	$LL###$."92d88SXXe__!UUUr4   c                 r    	 t          | j        |                   S # t          $ r t          |          w xY wr`   )rG   r,   KeyErrorAttributeError)r-   items     r2   __getattr__zDsaKey.__getattr__   sD    	'ty''' 	' 	' 	' &&&	's    6r   Nc                     |t          |          }|t          j        }|dk    rc fddD             }d fd|D             }dg|z   }d                    d	 |D                       }	d
t	          j        |	          dd         z   S t           j         j         j	        g          }
 
                                r|d}|rS|sd}t           j                                                  }t          j        |t           |||
|          }|rd}nd}d}n|dk    r|rt#          d          d j         j         j	         j         j        g}t          |                                          }d}n;|rt#          d          t'          t           t           j                  |
          }d}|dk    r|S |dk    r)t)          j        ||dz   ||          }t          |          S t#          d|z            )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:`Cryptodome.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:`Cryptodome.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OpenSSHc                 N    g | ]!}j         |                                         "S r8   )r,   to_bytes)r;   r"   r-   s     r2   r=   z%DsaKey.export_key.<locals>.<listcomp>  s+    JJJDIaL))++JJJr4   )r    r!   r   r   c                 Z    t          | d                   dz  rt          d          | z   S | S )Nr      )r   r   r%   s    r2   funczDsaKey.export_key.<locals>.func  s.    1JJ% 77Q;&Hr4   c                 &    g | ]} |          S r8   r8   )r;   r"   r   s     r2   r=   z%DsaKey.export_key.<locals>.<listcomp>  s!    ***DDGG***r4      ssh-dssr4   c                 X    g | ]'}t          j        d t          |                    |z   (S )>I)structpacklen)r;   kps     r2   r=   z%DsaKey.export_key.<locals>.<listcomp>  s/    PPPV[s2ww77"<PPPr4      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}   binascii
b2a_base64r   r    r!   r   rA   r   r"   encoder   wrapoidr)   r   r   r   )r-   formatpkcs8
passphrase
protectionr   tup1tup2keyparts	keystringparamsprivate_key
binary_keykey_typeintspem_strr   s   `               @r2   
export_keyzDsaKey.export_key   sg   v ! ,,J.HYJJJJ5IJJJD   +***T***D"|d*HPPxPPP I !4Y!?!?!DDD dfdfdf566 	 } )! F!EJ(007799"Z +S* *v)1" " "

  )2HH(H!

U??z?$%JKKK4646464646B(..5577
( O !MNNN8 *46 2 2F< <JHU??U??j *Hv,= *H G 7###NQWWXXXr4   c                      t          d          Nz+Use module Cryptodome.Signature.DSS insteadNotImplementedError)r-   MKs      r2   signzDsaKey.signU      !"OPPPr4   c                      t          d          r   r   )r-   r   	signatures      r2   verifyzDsaKey.verifyX  r   r4   c                     t           r`   r   )r-   	plaintextr   s      r2   encryptzDsaKey.encrypt[      !!r4   c                     t           r`   r   )r-   
ciphertexts     r2   decryptzDsaKey.decrypt^  r   r4   c                     t           r`   r   r-   r   Bs      r2   blindzDsaKey.blinda  r   r4   c                     t           r`   r   r   s      r2   unblindzDsaKey.unblindd  r   r4   c                     t           r`   r   rY   s    r2   sizezDsaKey.sizeg  r   r4   )r   NNNN)r{   
__module____qualname____doc__rf   r3   rO   rW   rA   r[   r]   rc   rj   rl   rp   rs   r   r   r   	exportKey	publickeyr   r   r   r   r   r   r   r8   r4   r2   r   r   N   s        , )((H
# 
# 
#     "	 	 	     
    ) ) )  & & &  
B B BV V V' ' ' ?C,0{Y {Y {Y {Y| IIQ Q QQ Q Q" " "" " "" " "" " "" " " " "r4   r   c                 T   dddd                     |           }|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          k    rj |d
          t	          j        t          j                  	                                          |dz
  z  }||z  dz  }t          ||          t          k    j|
                                |k    sJ dd| dz
  z  }	 fdt          |dz             D             d D             t          fdt          |          D             |         d|z  dz
  z  d|z  z  z            }t	          ||z             }	|	
                                | k    sJ |	|dz  z  }
|	|
dz
  z
  }|
                                | k    rt          ||          t          k    rn	|dz   z  |dz
  |z  }t          j        d          D ]}dz   t          d          z   t	          |                                          z   }t	          j        t          j        |          	                                          }t#          |||          }|dk    r n|||fS )z+Generate a new set of DSA domain parameters         )         NzInvalid modulus length (%d)   r6      @   Tc           	          g | ]M}t          j        t          |z                                             z                                             NS r8   )r   newr   r   digest)r;   joffsetseeds     r2   r=   z$_generate_domain.<locals>.<listcomp>  s\     + + + j
 3 3 < < > >>??FFHH + + +r4   c                 6    g | ]}t          j        |          S r8   r   
from_bytes)r;   rV   s     r2   r=   z$_generate_domain.<locals>.<listcomp>  s#    000g ##000r4   c                 2    g | ]}|         d |z  z  z  S )r6   r8   )r;   iVoutlens     r2   r=   z$_generate_domain.<locals>.<listcomp>  s+    CCC1q6z*+CCCr4      s   ggen)getr)   r   digest_sizer   r   r   r   r   r   rw   r   sum	itertoolscountr   r   rE   )Lr   Nnb_r!   	upper_bitUWXcr    er   r   r   r   r   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
<
<x||vz$//668899Y]K	MA a
*
*n
<
<
 >>q     Fa!eI+ + + + +!!a%((+ + +00Q000CCCCCZ]]CCC1!r'Q'A!f*,=>@ @ A	M""~~1$$$$QKQK>>q  q(++~==!a%$ 
Q1A##  7NT!WW$wu~~'>'>'@'@@vz!}}3355661aLL66E  q!T?r4   c                     |t           j        }|rt          t          |          \  }}}t	          |          t
          k    }|t	          |          t
          k    z  }||dz
  |z  dk    z  }||dk    p||k    z  }|t          |||          dk    z  }|rt          d          nt          | |          \  }}}}|	                                }|	                                }	|| k    rt          d|| fz            ||	fdvrt          d||	fz            d|cxk     r|k     sn 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:`Cryptodome.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
    Nr6   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   rF   r   r   r   rE   r)   r   rw   randomr   )r   r   rs   r    r!   r   	fmt_error_r   r   r   r"   r   r.   s                 r2   r   r     s   < * 6gv&&1a (**i7	(++y88	q1uka''	Q!V%qAv%	SAq\\Q&&	 	><===	> &dH55
1a	A	ADyy 69:D	B C C 	C 	
1v 0 0 0 ),-q62 3 3 	3 q9999199992333 	!b&8<<<A	QUaAAq!AA1!44H(r4   Tc           	         t          t          dt          t          |                               }t	          |          }d}|rt          |j                  t          k    }|t          |j                  t          k    z  }||j        dz
  |j        z  dk    z  }||j	        dk    p|j	        |j        k    z  }|t          |j	        |j        |j                  dk    z  }||j        dk    p|j        |j        k    z  }t          |d          rJ||j        dk    p|j        |j        k    z  }|t          |j	        |j        |j                  |j        k    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+   ziprF   r   r   r   r    r   r!   r   rE   r   ry   r"   r)   )tupconsistency_checkr.   keyr   s        r2   r   r     sS   2 C13w3D3DEEFFH


CI ;'..);	(//9<<	suqyCE)a//	SUaZ135CE>1	Ssu--22	SUaZ135CE>1	3 	;!5su~5ISUCE3511SU::I 75666Jr4   c                     |rt          d          t                                          | dd          d         dk    rt          d          fddD             }t          |          S )	Nz-DSA private key already comes with parameters   T)nr_elementsonly_ints_expectedr   zNo version foundc                      g | ]
}|         S r8   r8   )r;   r<   ders     r2   r=   z+_import_openssl_private.<locals>.<listcomp>'  s    
1
1
13t9
1
1
1r4   )r      r6   r      )r)   r   decoder   )encodedr   r   r   r  s       @r2   _import_openssl_privater  !  sz     JHIII
--

wA$

O
OC
1v{{+,,,
1
1
1
1
1
1
1CS>>r4   c                 `   t          |           \  }}}|t          k    rt          d          |r|rt          d          t                                          |          j        }t          t                                          |p|                    \  }}}	||	||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'O#FK}}6777 4* 42333K((.A;==''(<*==>>GAq!aA,CS>>r4   c                 B    t          |           }t          |d |          S r`   )r   r  )r  r   r   sp_infos       r2   _import_x509_certr  9  s!    .w77G'v>>>r4   c                    |rt          d          t          j        | |          }|d         t          k    rt          d          t	                                          |d                   j        }t          t                                          |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   rE   r   )	r  r   r   rI   r"   r    r!   r   r   s	            r2   _import_pkcs8r  ?  s     ?=>>>Wj))Ats{{4555AaD!!'A;==''!--..GAq!q!Q<<Aq!
$CS>>r4   c                     t           t          t          t          f}|D ]!}	  || ||          c S # t          $ r Y w xY wt	          d          )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  sx     )-" I
   	8Hj&99999 	 	 	D	 6
7
77s   /
<<c                 B   t          |           } |t          |          }|                     d          r;t          j        t	          |           |          \  }}}|rd}t          ||d          S |                     d          rt          j        |                     d          d                   }g t          |          dk    rct          j        d|dd                   d         }                    |dd|z                       |d|z   d         }t          |          dk    cd         d	k    rfd
dD             }t          |          S t          |           dk    r*t          | d                   dk    rt          | |d          S t          d          )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   c                 D    g | ]}t          j        |                   S r8   r   )r;   r"   r   s     r2   r=   zimport_key.<locals>.<listcomp>  s(    IIIq7%hqk22IIIr4   )r   r  r6   r   0   r  )r	   
startswithr   r
  r
   r  r   
a2b_base64splitr   r   unpackrx   r   r   r)   )	
extern_keyr   r  markerenc_flagr   lengthr   r   s	           @r2   r   r   \  s   P $$JZ((
X&& 6"%*U:->->
"K"Kfh 	JsJ555[)) 
"'
(8(8(>(>q(ABB	)nnq  ]42A277:FOOIaF
l3444!!f*++.I )nnq   A;*$$IIIILIIICS>>!
:tJqM22d::z:t<<<
6
7
77r4   z1.2.840.10040.4.1)NN)Tr`   ).__all__r   r   r   Cryptodome.Util.py3compatr   r   r	   r
   r   
Cryptodomer   Cryptodome.IOr   r   Cryptodome.Hashr   Cryptodome.Util.asn1r   r   r   r   r   Cryptodome.Math.Numbersr   Cryptodome.Math.Primalityr   r   r   Cryptodome.PublicKeyr   r   r   objectr   r   r   r   r  r  r  r  r  r   	importKeyr   r8   r4   r2   <module>r7     sF  2 =
<
<       L L L L L L L L L L L L L L       $ $ $ $ $ $ $ $ " " " " " "              , + + + + +3 3 3 3 3 3 3 3 3 3@ @ @ @ @ @ @ @ @ @@Z" Z" Z" Z" Z"V Z" Z" Z"z2 2 2jF F F FR. . . .p    ? ? ?	 	 	8 8 8"C8 C8 C8 C8N 	 r4   