Server : LiteSpeed
System : Linux server51.dnsbootclub.com 4.18.0-553.62.1.lve.el8.x86_64 #1 SMP Mon Jul 21 17:50:35 UTC 2025 x86_64
User : nandedex ( 1060)
PHP Version : 8.1.33
Disable Function : NONE
Directory :  /opt/cppython/lib/python3.8/site-packages/__pycache__/

Upload File :
current_dir [ Writeable ] document_root [ Writeable ]


Current File : //opt/cppython/lib/python3.8/site-packages/__pycache__/gnupg.cpython-38.pyc
U

N��gTG�@s$dZddlZddlmZddlmZddlmZddlZddlZddl	Z	ddl
Z
ddlmZm
Z
ddlZddlZdZdZd	ZdZejd
kr�zddlmZmZmZWnek
r�dZYnXzedZeZeZeefZWn&e k
r�d
ZeZeZefZYnXe�!e"�Z#e#j$�s e#�%e�&��dZ'ej(j"dk�r<dd�Z)ne	�*d�Z+dd�Z)e�,�Z-dd�Z.dd�Z/dd�Z0dd�Z1dd�Z2dd�Z3dd �Z4Gd!d"�d"e5�Z6Gd#d$�d$e6�Z7Gd%d&�d&e6�Z8e	�*d'e	j9�Z:d(d)d*d+d,d-d.�Z;Gd/d0�d0e6�Z<d1d2�Z=Gd3d4�d4e6e>�Z?Gd5d6�d6e?�Z@Gd7d8�d8e@�ZAGd9d:�d:e5�ZBd;d<d=d>d?d@dAdBdCdDdEdFdGdHdIdJ�ZCdKdL�ZDGdMdN�dNe7eB�ZEGdOdP�dPe6�ZFGdQdR�dRe6�ZGGdSdT�dTeF�ZHGdUdV�dVe6�ZIGdWdX�dXeI�ZJGdYdZ�dZe6eB�ZKGd[d\�d\e6�ZLe	�*d]�Md^��ZNe	�*d_e	j9�ZOe	�*d`�ZPGdadb�dbe5�ZQdS)ca� A wrapper for the GnuPG `gpg` command.

Portions of this module are derived from A.M. Kuchling's well-designed
GPG.py, using Richard Jones' updated version 1.3, which can be found
in the pycrypto CVS repository on Sourceforge:

http://pycrypto.cvs.sourceforge.net/viewvc/pycrypto/gpg/GPG.py

This module is *not* forward-compatible with amk's; some of the
old interface has changed.  For instance, since I've added decrypt
functionality, I elected to initialize with a 'gnupghome' argument
instead of 'keyring', so that gpg can find both the public and secret
keyrings.  I've also altered some of the returned objects in order for
the caller to not have to know as much about the internals of the
result classes.

While the rest of ISconf is released under the GPL, I am releasing
this single file under the same terms that A.M. Kuchling used for
pycrypto.

Steve Traugott, stevegt@terraluna.org
Thu Jun 23 21:27:20 PDT 2005

This version of the module has been modified from Steve Traugott's version
(see http://trac.t7a.org/isconf/browser/trunk/lib/python/isconf/GPG.py) by
Vinay Sajip to make use of the subprocess module (Steve's version uses os.fork()
and so does not work on Windows). Renamed to gnupg.py to avoid confusion with
the previous versions.

Modifications Copyright (C) 2008-2024 Vinay Sajip. All rights reserved.

For the full documentation, see https://docs.red-dove.com/python-gnupg/ or
https://gnupg.readthedocs.io/
�N)�datetime)�	parseaddr)�StringIO)�Popen�PIPEz0.5.4zVinay Sajipz$07-Jan-2025 10:13:17$�nt)�STARTUPINFO�STARTF_USESHOWWINDOW�SW_HIDEFT�ntpathcCsd|S)Nz"%s"���srr�2/opt/cppython/lib/python3.8/site-packages/gnupg.py�shell_quoteVsrz[^\w%+,./:=@-]cCsHt|t�stdt|���|s$d}n t�|�s4|}nd|�dd�}|S)au
        Quote text so that it is safe for POSIX command shells.

        For example, "*.py" would be converted to "'*.py'". If the text is considered safe it is returned unquoted.

        Args:
            s (str): The value to quote
        Returns:
            str: A safe version of the input, from the point of view of POSIX
                 command shells.
        zExpected string type, got %sz''z'%s'�'z'\'')�
isinstance�string_types�	TypeError�type�UNSAFE�search�replace)r�resultrrrr_s

cCstst|t�r|�t�}|S)z7
    Legacy function which is a no-op on Python 3.
    )�_py3kr�	text_type�encode�
fsencodingr
rrr�no_quote�s
rcCs|dkst�d}ttjd�r&tjj}nd}z|�|�}Wn&tk
r^tjddd�Yq�YnX|sfq�|t	|�7}z|�
|�Wq*tk
r�|�
|�|��Yq*tk
r�t�
d�Yq�Yq*Xq*z|��Wn"tk
r�tjddd�YnXt�d	|�dS)
Nr�encoding�asciiz Exception occurred while reading�)�exc_infozError sending dataz)Exception occurred while closing: ignoredzclosed output, %d bytes sent)�AssertionError�hasattr�sys�stdinr�read�	Exception�logger�warning�len�write�UnicodeErrorr�	exception�close�IOError�debug)�instream�	outstream�buffer_size�sent�enc�datarrr�
_copy_data�s2


r8cCsB|dkst�tjt|||fd�}d|_t�d|||�|��|S)Nr��target�argsTzdata copier: %r, %r, %r)r#�	threading�Threadr8�daemonr)r1�start)r2r3r4�wrrrr�_threaded_copy_data�srAcCs*d|}|�|�}|�|�t�d�dS)Nz%s
zWrote passphrase)rr,r)r1)�stream�
passphraserrrr�_write_passphrase�s

rDcCst|ttttf�S�N)r�list�tuple�set�	frozenset)�instancerrr�_is_sequence�srKcCs:zddlm}||�}Wntk
r4t|�}YnX|S)Nr)�BytesIO)�iorL�ImportErrorr)rrL�rvrrr�_make_memory_stream�srPcCs8trt|t�r0|�|�}nt|�tk	r0|�|�}t|�SrE)rr�strrrrP)rrrrr�_make_binary_stream�s

rRc@s$eZdZdZdZdd�Zdd�ZdS)�
StatusHandlerzA
    The base class for handling status messages from `gpg`.
    NcCs
||_dS)zq
        Initialize an instance.

        Args:
            gpg (GPG): The :class:`GPG` instance in use.
        N)�gpg��selfrTrrr�__init__�szStatusHandler.__init__cCst�dS)a.
        Handle status messages from the `gpg` child process. These are lines of the format

            [GNUPG:] <key> <value>

        Args:
            key (str): Identifies what the status message is.
            value (str): Identifies additional data, which differs depending on the key.
        N)�NotImplementedError�rV�key�valuerrr�
handle_status�s
zStatusHandler.handle_status)�__name__�
__module__�__qualname__�__doc__�on_data_failurerWr\rrrrrS�s	rSc@speZdZdZdZdZdZdZdZdZ	eeeeee	d�Z
d	d
ddd
�ZddiZdZ
dd�Zdd�ZeZdd�ZdS)�VerifyzJ
    This class handles status messages during signature verificaton.
    rr!����)�
TRUST_EXPIRED�TRUST_UNDEFINED�TRUST_NEVER�TRUST_MARGINAL�TRUST_FULLY�TRUST_ULTIMATEzpermission deniedzfile existszfile not foundznot a directory)r!�#�Q�a�zincorrect passphraseNcCsvt�||�d|_d|_|_|_d|_|_d|_d|_d|_	d|_
d|_d|_d|_
d|_d|_i|_g|_dS�NF)rSrW�valid�fingerprint�
creation_date�	timestamp�signature_id�key_id�username�
key_status�status�pubkey_fingerprint�expire_timestamp�
sig_timestamp�
trust_text�trust_level�sig_info�problemsrUrrrrWszVerify.__init__cCs|jSrE)rr�rVrrr�__nonzero__)szVerify.__nonzero__cs��fdd�}|�jkrB|�_�j|�_|�j�jd�d�_�n@|dkr\t�d||��n&|dkr�d�_d�_|�dd	�\�_	�_
�j��j�j	�j
d
��|�j	�j
�jd��n�|dk�r>d�_|��}|dd
�\�_	}}}�_
t|�dkr�|d�_d�_|�j	�j
�j�jd��j��j�j	�j
�jd���nD|dk�r�d�_d�_|�dd	�\�_	�_
|�j	�j
�jd��j��j�j	�j
d
���n�|dk�r�d�_d�_|�dd	�\�_	�_
|�j	�j
�jd��n�|dk�rX|��}|dd�\}}	}
}||	|
|f\�_�_�_�_t|�dk�r6|d�_d�_|||	|
|�j�jd��n*|dk�r�|��\}}	}
|	|
d��j|<||	|
�_�_�_
�n�|d k�r�d�_|�_	d!�_�j��j�j	d"���n�|d#k�rd�_|�_	d$�_�j��j�j	d"���n||d%k�rnd�_|��d&�_	|d'k�r6d(�_nd)�_�j�_|�j�j	d"��j��j�j	d"���n|d*k�r>d�_|d+k�r�d,�_n�d-|}|�d.d	�\}}|���r.t|�d/@}�jj�r�|�jjk�r�d0|�jj|f}nBt|d1@�}|d2@}|�r�j}n�j}||k�r.d0|||f}�j�s�|�_nD|d3k�rVd�_d4�_n,|d5k�rbn |d6k�rtd�_nt�d7||�dS)8Ncs0�j}|r �j|}|�|�nt�d|�dS)Nz!Ignored due to missing sig iD: %s)rvr��updater)r1)�kwargs�sig_id�infor�rr�update_sig_info0s

z-Verify.handle_status.<locals>.update_sig_info)rr~��WARNING�ERROR�potential problem: %s: %sZBADSIGFz
signature badr!)rz�keyid�user)r�rxrzZERRSIGrf��zsignature error)r�rursrz)rzr�rursZEXPSIGzsignature expiredZGOODSIGTzsignature goodZVALIDSIGre�
�	zsignature valid)rsrtruZexpiryr{rzZSIG_ID)rtruZ	NO_PUBKEYz
no public key)rzr�Z	NO_SECKEY�
no secret key)�	EXPKEYSIGZ	REVKEYSIGrr�zsigning key has expiredzsigning key was revoked)�
UNEXPECTED�FAILUREr�zunexpected dataz
error - %s� i����%s: %si�i��NODATAz signature expected but not found)ZDECRYPTION_INFOZ	PLAINTEXTZPLAINTEXT_LENGTH�
BEGIN_SIGNING�KEY_CONSIDERED)ZNEWSIGzmessage ignored: %r, %r)�TRUST_LEVELSr~rrvr)r*rrrz�splitrwrxr��appendrur+rsrtr}r|r{r�ry�rsplit�isdigit�intrT�	error_map�bool�GPG_SYSTEM_ERROR_CODES�GPG_ERROR_CODESr1)rVrZr[r��parts�algo�	hash_algo�clsrsrtZsig_tsZ	expire_tsr�ru�messageZ	operation�codeZsystem_error�mappingrr�rr\.s�



��



�
�












zVerify.handle_status)r]r^r_r`rgrhrirjrkrlr�r�r��
returncoderWr��__bool__r\rrrrrb�s6���rbc@sbeZdZdZd��ZdZdd�Zdd�ZeZ	dd	d
ddd
d�Z
dddddd�Zdd�Zdd�Z
dS)�ImportResultz?
    This class handles status messages during key import.
    z�count no_user_id imported imported_rsa unchanged n_uids n_subk n_sigs n_revoc sec_read sec_imported
            sec_dups not_importedNcCs4t�||�g|_g|_|jD]}t||d�qdS)Nr)rSrW�results�fingerprints�counts�setattr)rVrTrrrrrW�s

zImportResult.__init__cCst|jo|j�SrE)r��not_importedr�r�rrrr��szImportResult.__nonzero__zNot actually changedzEntirely new keyzNew user IDszNew signatureszNew subkeyszContains private key)�0�1�2�4�8Z16zNo specific reason givenzInvalid CertificatezIssuer Certificate missingzCertificate Chain too longzError storing certificate)r�r�r��3r�cCs�|dkrt�d||��n�|dkr&�n�|dkrF|j�dddd���n�|dkr�|��\}}g}t|j���D]*\}}t|�t|�Bt|�krl|�|�qld	�	|�d	}|j�|||d
��|j
�|��n|dk�r z|��\}}Wntk
�r|}d}YnX|j�|||j|d��n�|d
k�r^|��}	t
|j�D]\}
}t||t|	|
���q<nn|dk�r~|j�dddd��nN|dk�r�|j�dddd��n.|dk�r�|j�dddd��nt�d||�dS)Nr�r�)�IMPORTEDr�r�r�zNo valid data found)rs�problem�textZ	IMPORT_OK�
)rs�okr�ZIMPORT_PROBLEMz	<unknown>Z
IMPORT_RES�
KEYEXPIREDzKey expired�
SIGEXPIREDzSignature expiredr�z
Other failure�message ignored: %s, %s)r)r*r�r�r�rF�	ok_reason�itemsr��joinr�r(�problem_reason�	enumerater�r�r1)rVrZr[�reasonrs�reasonsr�r�Z
reasontextZ
import_res�i�countrrrr\�sB





zImportResult.handle_statuscCs4g}|�d|j�|jr*|�d|j�d�|�S)zi
        Return a summary indicating how many keys were imported and how many were not imported.
        z%d importedz%d not imported�, )r�Zimportedr�r�)rVrrrr�summarys
zImportResult.summary)r]r^r_r`r�r�r�rWr�r�r�r�r\r�rrrrr��s*�
�%r�z\\x([0-9a-f][0-9a-f])r��
����)z\nz\rz\fz\vz\bz\0c@seZdZdZdZdd�ZdS)�
SendResultz@
    This class handles status messages during key sending.
    NcCst�d||�dS)NzSendResult: %s: %s)r)r1rYrrrr\szSendResult.handle_status)r]r^r_r`r�r\rrrrr�sr�cCs8t|�D]*\}}|t|�kr*||||<qd||<qdS)N�unavailable)r�r+)r:�
fieldnamesr;r��varrrr�_set_fields#sr�c@sHeZdZdZdZd��ZdZdd�Zdd�Z	d	d
�Z
dd�Zd
d�ZdS)�
SearchKeysz?
    This class handles status messages during key search.
    r!z#type keyid algo length date expiresNcCs"t�||�d|_g|_g|_dSrE)rSrW�curkeyr��uidsrUrrrrW7szSearchKeys.__init__cCs&i}t||j|�g|d<g|d<|S)�Z
        Internal method used to update the instance from a `gpg` status message.
        r��sigs)r��FIELDS)rVr;rrrr�
get_fields=s
zSearchKeys.get_fieldscCs|�|�|_}|�|�dS)r�N)r�r�r��rVr;r�rrr�pubGszSearchKeys.pubcCsX||j}t�dd�|�}t��D]\}}|�||�}q"|jd�|�|j�|�dS)r�cSstt|�d�d��S)Nr!�)�chrr��group)�mrrr�<lambda>S�z SearchKeys.uid.<locals>.<lambda>r�N)	�	UID_INDEX�ESCAPE_PATTERN�sub�
BASIC_ESCAPESr�rr�r�r�)rVr;�uid�k�vrrrr�Ns
zSearchKeys.uidcCsdSrErrYrrrr\YszSearchKeys.handle_status)
r]r^r_r`r�r�r�r�rWr�r�r�r\rrrrr�+s
r�csleZdZdZdZd��Z�fdd�Zdd�ZeZ	Z
dd	�Zd
d�Zdd
�Z
dd�Zdd�Zdd�Z�ZS)�ListKeysa�
    This class handles status messages during listing keys and signatures.

    Handle pub and uid (relating the latter to the former).

    We don't care about (info from GnuPG DETAILS file):

    crt = X.509 certificate
    crs = X.509 certificate and private key available
    uat = user attribute (same as user id except for field 10).
    sig = signature
    rev = revocation signature
    pkd = public key data (special field format, see below)
    grp = reserved for gpgsm
    rvk = revocation key
    r�z�type trust length algo keyid date expires dummy ownertrust uid sig cap issuer flag token hash curve compliance updated origin keygripcs tt|��|�d|_i|_dSrq)�superr�rW�	in_subkey�key_maprU��	__class__rrrWsszListKeys.__init__cCsL|�|�|_}|dr*|d�|d�|d=g|d<|�|�d|_dS)r�r�r��subkeysFN)r�r�r�r�r�rrrrZxs
zListKeys.keycCsr|d}||jkr&|jjr&td|��|jsP||jd<|j�|�|j|j|<n||jddd<|j|j|<dS)r�r�z$Unexpected fingerprint collision: %srsr����rcN)r�rT�check_fingerprint_collisions�
ValueErrorr�r�r�r�)rVr;�fprrr�fpr�s
zListKeys.fprcCs0|d}|js||jd<n||jddd<dS)r�r�Zkeygripr�r�rdN)r�r�)rVr;�grprrrr��szListKeys.grpcCs.|�di�}i}t||j|�|||d<dS)NZsubkey_infore)�
setdefaultr�r�)rVr�r;Zinfo_mapr�rrr�_collect_subkey_info�szListKeys._collect_subkey_infocCs<|d|dddg}|jd�|�|�|j|�d|_dS)r�rerpNr�T�r�r�r�r��rVr;�subkeyrrrr��szListKeys.subcCs8|ddddg}|jd�|�|�|j|�d|_dS)r�reNr�Tr�r�rrr�ssb�szListKeys.ssbcCs&|jd�|d|d|df�dS)r�r�rer�r�N)r�r��rVr;rrr�sig�szListKeys.sig)r]r^r_r`r�r�r�rWrZr��secr�r�r�r�rr�
__classcell__rrr�rr�]s
	r�c@seZdZdZdd�ZdS)�ScanKeyszB
    This class handles status messages during scanning keys.
    cCs<|d|dddg}|jd�|�|�|j|�d|_dS)r�rer�Nr�Tr�r�rrrr��szScanKeys.subN)r]r^r_r`r�rrrrr�src@s*eZdZdd�ZereZneZdd�ZdS)�TextHandlercCs|j�|jj|jj�SrE)r7�decoderTr�
decode_errorsr�rrr�_as_text�szTextHandler._as_textcCs|jSrE)r7r�rrr�__str__�szTextHandler.__str__N)r]r^r_r	rr
�__unicode__rrrrr�s
rzno specific reason givenz	not foundzambiguous specificationzwrong key usage�key revoked�key expiredzno crl knownzcrl too oldzpolicy mismatchznot a secret keyzkey not trustedzmissing certificatezmissing issuer certificatezkey disabledzsyntax error in specification)rr!rcrdrerfr�r��r�r�rp��
�cCsx|��}t|�dkr&|dd�\}}n|d}d}d|}zt|�}t�||�}Wntk
rj|}YnXd||fS)Nrcrz
<no ident>zunexpected return code %rz%s:%s)r�r+r��_INVALID_KEY_REASONS�getr�)rr�r��identZ
unexpectedrZrrrr�&_determine_invalid_recipient_or_signer�s
rc@s,eZdZdZdd�Zdd�ZeZdd�ZdS)	�CryptzN
    This class handles status messages during encryption and decryption.
    cCs.t�||�d|_d|_d|_d|_d|_dS)N�F)rbrWr7r�rz�
status_detailrwrUrrrrW	szCrypt.__init__cCs
t|j�SrE)r�r�r�rrrr�szCrypt.__nonzero__cCsx|dkrt�d||��nZ|dkr6|jdkr2d|_�n>|dkrT|�dd���|_�n |d	krp|jd
krld|_�n|dkr�d
|_n�|dkr�|jd
kr�d|_n�|dkr�d|_n�|dkr�d|_d|_n�|dkr�d|_d|_n�|dk�r|js�d|_nd|j|_t|�|_nn|dk�rd|_n\|dk�r*d|_nJ|dk�r<d|_n8|d k�rZ|�dd!�d"|_	n|d#k�rfnt
�|||�dS)$Nr�r�r�)�decryption failedzno data was provided)�NEED_PASSPHRASE�BAD_PASSPHRASE�GOOD_PASSPHRASEZMISSING_PASSPHRASE�KEY_NOT_CREATEDZNEED_PASSPHRASE_PIN�_r��DECRYPTION_FAILEDr�rZNEED_PASSPHRASE_SYMzneed symmetric passphraseZBEGIN_DECRYPTIONzdecryption incompleteZBEGIN_ENCRYPTIONzencryption incompleteZDECRYPTION_OKAYz
decryption okTZEND_ENCRYPTIONz
encryption ok�INV_RECPzinvalid recipientzinvalid recipient: %sr�r
�SIG_CREATEDzsig createdr�zsig expiredZENC_TOr!r)�USERID_HINTZGOODMDCZEND_DECRYPTIONZCARDCTRLZBADMDCZ
SC_OP_FAILUREZ
SC_OP_SUCCESSZPINENTRY_LAUNCHED)r)r*rzr�lowerr�rrr�rwrbr\rYrrrr\sN










zCrypt.handle_statusN)r]r^r_r`rWr�r�r\rrrrrs
rc@s8eZdZdZdZdd�Zdd�ZeZdd�Zd	d
�Z	dS)�GenKeyzC
    This class handles status messages during key generation.
    NcCs"t�||�d|_d|_d|_dS�Nr�rSrWrrsrzrUrrrrWLszGenKey.__init__cCs
t|j�SrE�r�rsr�rrrr�RszGenKey.__nonzero__cCs|jSrE�rsr�rrrr
WszGenKey.__str__cCs||dkrt�d||�n`|dkrD|��}|dd�\|_|_d|_n4|dkr`|�dd���|_n|d	krjnt�d
||�dS)Nr�r��KEY_CREATEDrcr�rrr�)ZPROGRESSrr�)	r)r*r�rrsrzrr#r1)rVrZr[r�rrrr\ZszGenKey.handle_status�
r]r^r_r`r�rWr�r�r
r\rrrrr$Esr$c@s8eZdZdZdZdd�Zdd�ZeZdd�Zd	d
�Z	dS)�	AddSubkeyzD
    This class handles status messages during subkey addition.
    NcCs"t�||�d|_d|_d|_dSr%r&rUrrrrWpszAddSubkey.__init__cCs
t|j�SrEr'r�rrrr�vszAddSubkey.__nonzero__cCs|jSrEr(r�rrrr
{szAddSubkey.__str__cCsJ|dkrt�d||�n.|dkr8|��\|_|_d|_nt�d||�dS)Nr�r�r)r�r�)r)r*r�rrsrzr1rYrrrr\~szAddSubkey.handle_statusr*rrrrr+isr+cs eZdZdZ�fdd�Z�ZS)�ExportResultz?
    This class handles status messages during key export.
    cs |dkr
ntt|��||�dS)N)ZEXPORTEDZ
EXPORT_RES)r�r,r\rYr�rrr\�szExportResult.handle_status)r]r^r_r`r\rrrr�rr,�sr,c@sDeZdZdZdZdd�Zdd�Zddd	d
�Zdd�Zd
d�Z	e	Z
dS)�DeleteResultzA
    This class handles status messages during key deletion.
    NcCst�||�d|_dS�Nr�)rSrWrzrUrrrrW�szDeleteResult.__init__cCs|jSrE�rzr�rrrr
�szDeleteResult.__str__zNo such keyzMust delete secret key firstzAmbiguous specification)r�r�r�cCs0|dkr|j�|d|�|_nt�d||�dS)NZDELETE_PROBLEMzUnknown error: %rr�)r�rrzr)r1rYrrrr\�szDeleteResult.handle_statuscCs
|jdkSr.r/r�rrrr��szDeleteResult.__nonzero__)r]r^r_r`r�rWr
r�r\r�r�rrrrr-�s�r-c@seZdZdZdS)�TrustResultzF
    This class handles status messages during key trust setting.
    N)r]r^r_r`rrrrr0�sr0c@s0eZdZdZdZdd�Zdd�ZeZdd�ZdS)	�Signz<
    This class handles status messages during signing.
    NcCs:t�||�d|_d|_d|_d|_d|_d|_d|_dSrE)	rSrWrr�rsrzrrwrxrUrrrrW�sz
Sign.__init__cCs
|jdk	SrEr(r�rrrr��szSign.__nonzero__cCs�|dkrt�d||�n�|dkr(d|_n�|dkr8d|_n�|dkrd|��\|_}|_}|_|_d|_nt|d	kr�|�d
d�\|_|_	nV|dkr�d
|_nF|dkr�|js�d|_nd|j|_t
|�|_n|dkr�nt�d||�dS)N)r�r�r�r�)r�r�r
Z
KEYREVOKEDrr!zsignature createdr"r�r!rzbad passphrase)ZINV_SGNRr zinvalid signerzinvalid signer: %s)rrr�r�)
r)r*rzr�rr�rursrwrxrrr1)rVrZr[r�r�rrrr\�s*zSign.handle_status)	r]r^r_r`r�rWr�r�r\rrrrr1�s
r1c@s@eZdZdZdd�Zdd�Zdd�Zdd	�Zd
d�Zdd
�Z	dS)�
AutoLocateKeyz�
    This class handles status messages during key auto-locating.
    fingerprint: str
    key_length: int
    created_at: date
    email: str
    email_real_name: str
    cCs.t�||�d|_d|_d|_d|_d|_dSrE)rSrWrsr�
created_at�email�email_real_namerUrrrrW�szAutoLocateKey.__init__cCsJ|dkr,|��\}}}||_|dd�|_n|dkrF|����d|_dS)Nr�r!r�r�r)r�r4r5�striprs)rVrZr[rr4�display_namerrrr\szAutoLocateKey.handle_statuscCsdS)z�
        Internal method to handle the 'pub' status message.
        `pub` message contains the fingerprint of the public key, its type and its creation date.
        Nrrrrrr�
szAutoLocateKey.pubcCs8t�t|d��|_|d}t|�\}}||_||_dS)Nrfr�)r�
fromtimestampr�r3rr4r5)rVr;Zraw_email_contentr4Z	real_namerrrr�s
zAutoLocateKey.uidcCst|d�|_dS)Nrc)r�Z
key_lengthrrrrr�szAutoLocateKey.subcCs|jp|d|_dS)Nr�r(rrrrr�szAutoLocateKey.fprN)
r]r^r_r`rWr\r�r�r�r�rrrrr2�s		r2z^cfg:version:(\d+(\.\d+)*)r z
[0-9a-f]+$zgpg: public key is (\w+)c@s�eZdZdZdZdZdZeee	e
eee
eeeeeeed�Zd\dd	�Zd
d�Zd]dd
�Zdd�Zd^dd�Zd_dd�Zdd�Zdd�Zd`dd�Zdd�Zdd�Z dd �Z!dad"d#�Z"d$d%�Z#dbd&d'�Z$dcd(d)�Z%ddd*d+�Z&d,d-�Z'd.d/�Z(d0d1�Z)ded2d3�Z*dfd4d5�Z+d6d7�Z,d8d9�Z-dgd:d;�Z.d<d=�Z/d>d?�Z0dhdAdB�Z1didCdD�Z2dEdF�Z3dGdH�Z4djdLdM�Z5dkdNdO�Z6dPdQ�Z7dRdS�Z8dldTdU�Z9dVdW�Z:dmdXdY�Z;dZd[�Z<dS)n�GPGzL
    This class provides a high-level programmatic interface for `gpg`.
    N�stricti@)�crypt�delete�generate�	addSubkey�import�sendrF�scanr�sign�trust�verify�export�auto-locate-keyrTFc	Cs�||_||_||_|r.tj�|�s.td|��|rBt|t�rB|g}||_	|r\t|t�r\|g}||_
||_||_t|t
�r~|g}||_d|_d|_|r�tj�|j�s�t�|jd�z|�ddg�}	Wn0tk
r�d|j}
t�|
�t|
��YnX|jd|�}|j|	||	jd	�|	jd
k�r4td|	j|jf��t�|j�}|�sNd|_n,d�d
�}
t dd�|�!�d
�"|
�D��|_d|_#dS)a9Initialize a GPG process wrapper.

        Args:
            gpgbinary (str): A pathname for the GPG binary to use.

            gnupghome (str): A pathname to where we can find the public and private keyrings. The default is
                             whatever `gpg` defaults to.

            keyring (str|list): The name of alternative keyring file to use, or a list of such keyring files. If
                                specified, the default keyring is not used.

            options (list): A list of additional options to pass to the GPG binary.

            secret_keyring (str|list): The name of an alternative secret keyring file to use, or a list of such
                                       keyring files.

            env (dict): A dict of environment variables to be used for the GPG subprocess.
        z.gnupghome should be a directory (it isn't): %sNzlatin-1i�z
--list-config�
--with-colonsz1Unable to run gpg (%s) - it may not be available.rD�r&rzError invoking gpg: %s: %s�.r cSsg|]}t|��qSr)r���.0rrrr�
<listcomp>�sz GPG.__init__.<locals>.<listcomp>F)$�	gpgbinary�	gnupghome�env�os�path�isdirr�rr�keyring�secret_keyring�verbose�	use_agentrQ�options�on_datar�makedirs�_open_subprocess�OSErrorr)r.�
result_map�_collect_outputr&r��stderr�
VERSION_RE�matchr7�versionrrG�groupsr�r�)rVrMrNrUrVrSrWrTrO�p�msgrr��dotrrrrWAsL





"zGPG.__init__cCs|jddddg}dtjkr(|�ddg�|rPt|d�rP|jd	krPd
dg|dd�<|�d
ddg�|jrz|�dt|j�g�|jr�|�	d�|jD]}|�dt|�g�q�|j
r�|j
D]}|�dt|�g�q�|r�|�ddg�|jr�|�	d�|j�r|�|j�|�|�|S)aN
        Make a list of command line elements for GPG. The value of ``args``
        will be appended. The ``passphrase`` argument needs to be True if
        a passphrase will be sent to `gpg`, else False.

        Args:
            args (list[str]): A list of arguments.
            passphrase (str): The passphrase to use.
        z--status-fdr�z--no-ttyz--no-verboseZ	DEBUG_IPCz--debugZipcra�rcr!z--pinentry-modeZloopbackr!�--fixed-list-modez--batchrGz	--homedirz--no-default-keyringz	--keyringz--secret-keyringz--passphrase-fdr�z--use-agent)
rMrP�environ�extendr$rarNrrSr�rTrVrW)rVr;rC�cmd�fnrrr�	make_args�s0







z
GPG.make_argsc	Csvddlm}|�||�}|jr*t||��ts4d}nt�}t|_t|_	t
|dttt||jd�}t
�d|j||��|S)Nr)�list2cmdlineF)�shellr&�stdoutr^�startupinforOr�)�
subprocessrmrlrU�printrr	ZdwFlagsr
ZwShowWindowrrrOr)r1�pid)rVr;rC�debug_printrj�sirrrrrZ�szGPG._open_subprocesscCs�g}|��}t|�dkrq�|�|�|��}|jr:t|�t�d|�|dd�dkr|dd�}|�dd�}|d}t|�dkr�|d}nd}|�	||�qd�
|�|_dS)Nrz%sr�z	[GNUPG:] r!r)�readliner+r��rstriprUrrr)r1r�r\r�r^)rVrBr�lines�line�L�keywordr[rrr�_read_response�s$

zGPG._read_response�c
Cs|dkst�g}d}|�|�}t|�dkrl|r�z||�Wq�tk
rh}z|dkrX|}W5d}~XYq�Xq�tr�t�d|dd��d}	|r�z||�}
|
dk	}	Wn.tk
r�}z|dkr�|}W5d}~XYnX|	r|�|�qtr�t	|���
|�|_nd�
|�|_|�r||_dS)Nrz	chunk: %r�TFr)
r#r'r+r(�log_everythingr)r1r�rrr�r7ra)rVrBrrXr4�chunksrar7�er�Zon_data_resultrrr�
_read_data�s:
zGPG._read_datac
Cst�|j�|j�}tj|j||fd�}d|_t�	d|�|�
�|j}tj|j|||j
|jfd�}d|_t�	d|�|�
�|��|��|dk	r�|�d�|��|j|_}	|	dkr�t�d|	�|dk	r�z|��Wntk
r�YnX|��|��|	S)	a
        Drain the subprocesses output streams, writing the collected output to the result. If a writer thread (writing
        to the subprocess) is given, make sure it's joined before returning. If a stdin stream is given, close it
        before returning.
        r9Tzstderr reader: %rzstdout reader: %rN�{�G�z�?rz&gpg returned a non-zero error code: %d)�codecs�	getreaderrr^r<r=r|r>r)r1r?ror�rXr4r��waitr�r*r/r0)
rV�processr�writerr&r^ZrrroZdr�rcrrrr]s4
zGPG._collect_outputcCs
t|d�S)z�
        A simplistic check for a file-like object.

        Args:
            fileobj (object): The object to test.
        Returns:
            bool: ``True`` if it's a file-like object, else ``False``.
        r')r$)rV�fileobjrrr�
is_valid_file(s	zGPG.is_valid_filecCsP|�|�r|}n<t|t�s(td|��n$tj�|�sBtd|��n
t|d�}|S)NzNot a valid file or path: %szNo such file: %s�rb)	r�r�
path_typesrrPrQ�existsr��open)rV�fileobj_or_pathrrrr�_get_fileobj3s


zGPG._get_fileobjc
	Cs�|�|�}zj|�||dk	�}|s4t�|j�|j�}	n|j}	d}|rPt|	||j�t	||	|j
�}|�||||	�|W�S|r�|�d�||k	r�|��XdS)z;Handle a call to GPG - pass input data, collect output datar�N)r�r�r/rZr��	getwriterrr&rDrAr4r])
rVr;r�rrC�binaryr�r�rcr&rrr�
_handle_io>s 

zGPG._handle_iocKs&t||j�}|j|f|�}|��|S)a�
        Sign a message. This method delegates most of the work to the `sign_file()` method.

        Args:
            message (str|bytes): The data to sign.
            kwargs (dict): Keyword arguments, which are passed to `sign_file()`:

                * keyid (str): The key id of the signer.

                * passphrase (str): The passphrase for the key.

                * clearsign (bool): Whether to use clear signing.

                * detach (bool): Whether to produce a detached signature.

                * binary (bool): Whether to produce a binary signature.

                * output (str): The path to write a detached signature to.

                * extra_args (list[str]): Additional arguments to pass to `gpg`.
        )rRr�	sign_filer/)rVr�r��frrrrrBYszGPG.signcCs.tj�|�r|�dg�|�dt|�g�dS)a:
        If writing to a file which exists, avoid a confirmation message by
        updating the *args* value in place to set the output path and avoid
        any cpmfirmation prompt.

        Args:
            args (list[str]): A list of arguments.
            output (str): The path to the outpur file.
        �--yesz--outputN)rPrQr�rir)rVr;�outputrrr�set_output_without_confirmationts
z#GPG.set_output_without_confirmationcCsd|kod|kod|kS)a�
        Confirm that the passphrase doesn't contain newline-type characters - it is passed in a pipe to `gpg`,
        and so not checking could lead to spoofing attacks by passing arbitrary text after passphrase and newline.

        Args:
            passphrase (str): The passphrase to test.

        Returns:
            bool: ``True`` if it's a valid passphrase, else ``False``.
        r�r�r�r)rVrCrrr�is_valid_passphrase�szGPG.is_valid_passphraseTc		Cs:|r|�|�std��t�d|�|r.dg}	ndg}	|rD|	�d�n|rR|	�d�|rh|	�dt|�g�|rx|�|	|�|r�|	�|�|jd|�}
|�	|�}|�
|	|d	k	�}zRz*|j
}|r�t|||j�t|||j�}
Wn"tk
r�t�d�d	}
YnXW5|
�r|
�d
�||k	�r$|��X|�||
|
|�|
S)a]
        Sign data in a file or file-like object.

        Args:
            fileobj_or_path (str|file): The file or file-like object to sign.

            keyid (str): The key id of the signer.

            passphrase (str): The passphrase for the key.

            clearsign (bool): Whether to use clear signing.

            detach (bool): Whether to produce a detached signature.

            binary (bool): Whether to produce a binary signature.

            output (str): The path to write a detached signature to.

            extra_args (list[str]): Additional arguments to pass to `gpg`.
        �Invalid passphrasez
sign_file: %sz-sz-saz
--detach-signz--clearsign�
--default-keyrBNr�zerror writing message)r�r�r)r1r�rirr�r\r�rZr�r/r&rDrrAr4r0�loggingr.r])rVr�r�rCZ	clearsign�detachr�r��
extra_argsr;rr�rcr�r&rrrr��sB






z
GPG.sign_filecKs&t||j�}|j|f|�}|��|S)a�
        Verify the signature on the contents of the string *data*. This method delegates most of the work to
        `verify_file()`.

        Args:
            data (str|bytes): The data to verify.
            kwargs (dict): Keyword arguments, which are passed to `verify_file()`:

                * fileobj_or_path (str|file): A path to a signature, or a file-like object containing one.

                * data_filename (str): If the signature is a detached one, the path to the data that was signed.

                * close_file (bool): If a file-like object is passed in, whether to close it.

                * extra_args (list[str]): Additional arguments to pass to `gpg`.
        )rRr�verify_filer/)rVr7r�r�rrrrrD�sz
GPG.verifyc	Cs�t�d||�|jd|�}dg}|r0|�|�|dkrL|j|||dd�n�t�d�ddl}|jd	d
�\}}	|��}
|r�|��t�d|
�t	�
||
�t	�|�|�t|	��|�t|��z |�|�}|j|||jd�W5t	�
|	�X|S)
a�
        Verify a signature.

        Args:
            fileobj_or_path (str|file): A path to a signature, or a file-like object containing one.

            data_filename (str): If the signature is a detached one, the path to the data that was signed.

            close_file (bool): If a file-like object is passed in, whether to close it.

            extra_args (list[str]): Additional arguments to pass to `gpg`.
        zverify_file: %r, %rrD�--verifyNT�r�zHandling detached verificationr�pygpg-��prefixzWrote to temp file: %rrH)r)r1r\rir��tempfile�mkstempr'r/rPr,r�r�removerZr]r&)rVr�Z
data_filenameZ
close_filer�rr;r��fdrkrrcrrrr��s.




zGPG.verify_filecCsht�d||dd��|jd|�}dg}|r8|�|�|�t|�dg�t|�}|j|||dd�|S)	a
        Verify the signature in sig_filename against data in memory

        Args:
            sig_filename (str): The path to a signature.

            data (str|bytes): The data to be verified.

            extra_args (list[str]): Additional arguments to pass to `gpg`.
        zverify_data: %r, %r ...Nr�rDr��-Tr�)r)r1r\rirrPr�)rVZsig_filenamer7r�rr;rBrrr�verify_datas
zGPG.verify_datacCsp|jd|�}t�d|dd��t||j�}dg}|rB|�|�|j||||dd�t�d|j�|��|S)	a
        Import the key_data into our keyring.

        Args:
            key_data (str|bytes): The key data to import.

            passphrase (str): The passphrase to use.

            extra_args (list[str]): Additional arguments to pass to `gpg`.
        r?zimport_keys: %rNr~�--importT�rCr�zimport_keys result: %r)	r\r)r1rRrrir��__dict__r/)rV�key_datar�rCrr7r;rrr�import_keys-s
zGPG.import_keysc
Ks4t|d�� }|j|��f|�W5QR�SQRXdS)z�
        Import the key data in key_path into our keyring.

        Args:
            key_path (str): A path to the key data to be imported.
        r�N)r�r�r')rVZkey_pathr�r�rrr�import_keys_fileCszGPG.import_keys_filecOs�|jd|�}t�d|�td|j�}dt|�g}d|krH|�|d�|�d�|�dd�|D��|j|||d	d
�t�d|j	�|�
�|S)z�
        Import one or more keys from a keyserver.

        Args:
            keyserver (str): The key server hostname.

            keyids (str): A list of key ids to receive.
        r?z
recv_keys: %rr�--keyserverr�z--recv-keyscSsg|]}t|��qSr�r�rKr�rrrrL]sz!GPG.recv_keys.<locals>.<listcomp>Tr�zrecv_keys result: %r�r\r)r1rRrrrir�r�r�r/�rV�	keyserver�keyidsr�rr7r;rrr�	recv_keysMs	
z
GPG.recv_keyscOs�|jd|�}t�d|�td|j�}dt|�g}d|krH|�|d�|�d�|�dd�|D��|j|||d	d
�t�d|j	�|�
�|S)z�
        Send one or more keys to a keyserver.

        Args:
            keyserver (str): The key server hostname.

            keyids (list[str]): A list of key ids to send.
        r@z
send_keys: %rrr�r�z--send-keyscSsg|]}t|��qSrr�r�rrrrLysz!GPG.send_keys.<locals>.<listcomp>Tr�zsend_keys result: %rr�r�rrr�	send_keyses

z
GPG.send_keyscCs|r|�|�std��d}|r@|jdkr<|dkr<|r<td��d}t|�rXdd�|D�}n
t|�g}|rtd	d�|D�}d
|g}|r�|jdkr�|�dd�|�|�|jd
|�}|r�|jdkr�|�|�}	|j	|	||	j
d�n0td|j�}
z|j||
||dd�W5|
�
�X|S)a9
        Delete the indicated keys.

        Args:
            fingerprints (str|list[str]): The keys to delete.

            secret (bool): Whether to delete secret keys.

            passphrase (str): The passphrase to use.

            expect_passphrase (bool): Whether a passphrase is expected.

            exclamation_mode (bool): If specified, a `'!'` is appended to each fingerprint. This deletes only a subkey
                                     or an entire key, depending on what the fingerprint refers to.

        .. note:: Passphrases

           Since GnuPG 2.1, you can't delete secret keys without providing a passphrase. However, if you're expecting
           the passphrase to go to `gpg` via pinentry, you should specify expect_passphrase=False. (It's only checked
           for GnuPG >= 2.1).
        r�rZrfNzHFor GnuPG >= 2.1, deleting secret keys needs a passphrase to be providedz
secret-keycSsg|]}t|��qSrr�rJrrrrL�sz#GPG.delete_keys.<locals>.<listcomp>cSsg|]}|d�qS)�!r)rKr�rrrrL�sz--delete-%srr�r<rHrTr�)r�r�rarKr�insertrir\rZr]r&rRrr/r�)rVr��secretrC�expect_passphraseZexclamation_mode�whichr;rrcr�rrr�delete_keyss2




zGPG.delete_keysc
CsF|r|�|�std��d}|r@d}|jdkr@|dkr@|r@td��t|�rXdd�|D�}n
t|�g}d	|g}	|rz|	�d
�|r�|	�ddg�|r�|�|	|�|	�|�|jd
|�}
|r�|jdkr�|�	|	�}|j
||
|jd�n0td|j
�}z|j|	||
|dd�W5|��Xt�d|
jdd��|
j}
|�rB|
�|j
|j�}
|
S)at
        Export the indicated keys. A 'keyid' is anything `gpg` accepts.

        Args:
            keyids (str|list[str]): A single keyid or a list of them.

            secret (bool): Whether to export secret keys.

            armor (bool): Whether to ASCII-armor the output.

            minimal (bool): Whether to pass `--export-options export-minimal` to `gpg`.

            passphrase (str): The passphrase to use.

            expect_passphrase (bool): Whether a passphrase is expected.

            output (str): If specified, the path to write the exported key(s) to.

        .. note:: Passphrases

           Since GnuPG 2.1, you can't export secret keys without providing a passphrase. However, if you're expecting
           the passphrase to go to `gpg` via pinentry, you should specify expect_passphrase=False. (It's only checked
           for GnuPG >= 2.1).
        r�rz-secret-keyrfNzIFor GnuPG >= 2.1, exporting secret keys needs a passphrase to be providedcSsg|]}t|��qSrr�r�rrrrL�sz#GPG.export_keys.<locals>.<listcomp>z
--export%s�--armorz--export-optionszexport-minimalrErHTr�zexport_keys result[:100]: %r�d)r�r�rarKrr�rir�r\rZr]r&rRrr/r�r)r1r7rr)
rVr�r��armorZminimalrCr�r�r�r;rrcr�rrr�export_keys�s> 





zGPG.export_keyscCs�|j�|j|j���}d��}|D]\}|jr4t|�t�	d|�
��|sLq�|���d�}|s`q"|d}||kr"t||�|�q"|S)Nzpub uid sec fpr sub ssb sig grp�line: %r�:r)
r7rrr�
splitlinesr�rUrrr)r1rwr6�getattr)rVrrx�valid_keywordsryrzr{rrr�_decode_result�szGPG._decode_resultcCs*|j||�}|j|||jd�|�|�S)NrH)r\r]r&r�)rVrc�kindrrrr�_get_list_outputszGPG._get_list_outputcCsl|r
d}n|rdnd}d|ddg}|jdkr8|�d�|rVt|t�rL|g}|�|�|�|�}|�|d�S)	aZ
        List the keys currently in the keyring.

        Args:
            secret (bool): Whether to list secret keys.

            keys (str|list[str]): A list of key ids to match.

            sigs (bool): Whether to include signature information.

        Returns:
            list[dict]: A list of dictionaries with key information.
        zsecret-keysr��keysz	--list-%s�
--fingerprintrfz--with-keygriprF)rar�rrrirZr�)rVr�r�r�r�r;rcrrr�	list_keyss




z
GPG.list_keyscCsP|jdkrddddg}nt�d�ddd	g}|�t|��|�|�}|�|d
�S)a
        List details of an ascii armored or binary key file without first importing it to the local keyring.

        Args:
            filename (str): The path to the file containing the key(s).

        .. warning:: Warning:
            Care is needed. The function works on modern GnuPG by running:

                $ gpg --dry-run --import-options import-show --import filename

            On older versions, it does the *much* riskier:

                $ gpg --with-fingerprint --with-colons filename
        rf�	--dry-run�--import-options�import-showr��TTrying to list packets, but if the file is not a keyring, might accidentally decrypt�--with-fingerprintrGrgrA)rar)r*r�rrZr�)rV�filenamer;rcrrr�	scan_keys5s



z
GPG.scan_keyscCs�|jd|�}t�d|dd��t||j�}|jdkrFdddd	g}nt�d
�ddd
g}|j|||dd�t�d|j�|�	�|�
|�S)a�
        List details of an ascii armored or binary key without first importing it to the local keyring.

        Args:
            key_data (str|bytes): The key data to import.

        .. warning:: Warning:
            Care is needed. The function works on modern GnuPG by running:

                $ gpg --dry-run --import-options import-show --import filename

            On older versions, it does the *much* riskier:

                $ gpg --with-fingerprint --with-colons filename
        rAz
scan_keys: %rNr~rfr�r�r�r�r�r�rGrgTr�zscan_keys result: %r)r\r)r1rRrrar*r�r�r/r�)rVr�rr7r;rrr�
scan_keys_memOs


zGPG.scan_keys_mem�pgp.mit.educCs�|��}t�|�rd|}ddt|�g}|r6|�|�|�dt|�g�|�|�}|jd|�}|j|||jd�|j	�
|j|j��
�}ddg}|D]Z}	|jr�t|	�t�d	|	���|	s�q�|	���d
�}
|
s�q�|
d}||kr�t||�|
�q�|S)a

        search a keyserver by query (using the `--search-keys` option).

        Args:
            query(str): The query to use.

            keyserver (str): The key server hostname.

            extra_args (list[str]): Additional arguments to pass to `gpg`.
        �0xr�r�z
--search-keysrrHr�r�r�r�r)r6�
HEX_DIGITS_REr`rrirZr\r]r&r7rrrr�rUrrr)r1rwr�r�)rV�queryr�r�r;rcrrxr�ryrzr{rrr�search_keysms2


zGPG.search_keyscKst|pddddddg}dd�|�d	|g}|jd
|�}d|krJ|�|d�|�|�}|j|||jd�|�|�|S)
a�
        Auto locate a public key by `email`.

        Args:
            email (str): The email address to search for.
            mechanisms (list[str]): A list of mechanisms to use. Valid mechanisms can be found
            here https://www.gnupg.org/documentation/manuals/gnupg/GPG-Configuration-Options.html
            under "--auto-key-locate". Default: ['wkd', 'ntds', 'ldap', 'cert', 'dane', 'local']
        ZwkdZntdsZldap�certZdane�localz--auto-key-locate�,z
--locate-keysrFr�rH)r�r\rirZr]r&r�)rVr4Z
mechanismsr�r;rr�rrr�auto_locate_key�s


zGPG.auto_locate_keycCs>dg}|jd|�}t||j�}|j|||dd�|��|S)z�
        Generate a key; you might use `gen_key_input()` to create the input.

        Args:
            input (str): The input to the key creation operation.
        z	--gen-keyr=Tr�)r\rRrr�r/)rV�inputr;rr�rrr�gen_key�szGPG.gen_keyc	Ksi}|�dd�}t|���D],\}}|�dd���}t|���r|||<q|�dd�d|krj|�dd	�|�d
d�tj	�
d�p�tj	�
d
�p�d}t��}|�dd|�dd�|f�d|�d�}t|���D]\}}|d||f7}q�|r�|d7}|d7}|S)z�
        Generate `--gen-key` input  (see `gpg` documentation in DETAILS).

        Args:
            kwargs (dict): A list of keyword arguments.
        Returns:
            str: A string suitable for passing to the `gen_key()` method.
        �
no_protectionFrr�zKey-TypeZRSAZ	key_curvez
Key-Lengthiz	Name-RealzAutogenerated Key�LOGNAME�USERNAME�unspecifiedz
Name-Emailz%s@%sr�z
Key-Type: %s
z%s: %s
z%no-protection
z%commit
)
�poprFr�r�titlerQr6r�rPrhr�socket�gethostname)	rVr�Zparmsr�rZ�valZlogname�hostname�outrrr�
gen_key_input�s(

zGPG.gen_key_input�rsa�encryptr�c	Cs||jddkrtd��|s"td��|r8|�|�s8td��d|||t|�g}|jd|�}td|j�}|j||||d	d
�|S)ae
        Add subkeys to a master key,

        Args:
            master_key (str): The master key.

            master_passphrase (str): The passphrase for the master key.

            algorithm (str): The key algorithm to use.

            usage (str): The desired uses for the subkey.

            expire (str): The expiration date of the subkey.
        rrczNot available in GnuPG 1.xz#No master key fingerprint specifiedr�z--quick-add-keyr>rTr�)	rarXr�r�rQr\rRrr�)	rVZ
master_keyZmaster_passphrase�	algorithm�usageZexpirer;rr�rrr�
add_subkey�szGPG.add_subkeyc

Cs|r|�|�std��dg}
|rBdg}
|dk	rx|
�dt|�g�n6|sNtd��t|�s\|f}|D]}|
�dt|�g�q`|r�|
�d�|r�|�|
|�|dkr�|
�d	�n|r�|
�d	d
t|�g�|r�|
�ddg�|	r�|
�|	�|jd
|�}|j|
|||dd�t	�
d|jdd��|S)a*
        Encrypt data in a file or file-like object.

        Args:
            fileobj_or_path (str|file): A path to a file or a file-like object containing the data to be encrypted.

            recipients (str|list): A key id of a recipient of the encrypted data, or a list of such key ids.

            sign (str): If specified, the key id of a signer to sign the encrypted data.

            always_trust (bool): Whether to always trust keys.

            passphrase (str): The passphrase to use for a signature.

            armor (bool): Whether to ASCII-armor the output.

            output (str): A path to write the encrypted output to.

            symmetric (bool): Whether to use symmetric encryption,

            extra_args (list[str]): A list of additional arguments to pass to `gpg`.
        r�z	--encryptz--symmetricTz
--cipher-algoz2No recipients specified with asymmetric encryptionz--recipientr�z--signr��
--trust-model�alwaysr;r�zencrypt result[:100]: %rNr�)r�r�rirrKr�r�r\r�r)r1r7)
rVr��
recipientsrB�always_trustrCr�r�Z	symmetricr�r;Z	recipientrrrr�encrypt_files: 

zGPG.encrypt_filecKs(t||j�}|j||f|�}|��|S)a�
        Encrypt the message contained in the string *data* for *recipients*. This method delegates most of the work to
        `encrypt_file()`.

        Args:
            data (str|bytes): The data to encrypt.

            recipients (str|list[str]): A key id of a recipient of the encrypted data, or a list of such key ids.

            kwargs (dict): Keyword arguments, which are passed to `encrypt_file()`:
                * sign (str): If specified, the key id of a signer to sign the encrypted data.

                * always_trust (bool): Whether to always trust keys.

                * passphrase (str): The passphrase to use for a signature.

                * armor (bool): Whether to ASCII-armor the output.

                * output (str): A path to write the encrypted output to.

                * symmetric (bool): Whether to use symmetric encryption,

                * extra_args (list[str]): A list of additional arguments to pass to `gpg`.
        )rRrr�r/)rVr7r�r�rrrrr�VszGPG.encryptcKs&t||j�}|j|f|�}|��|S)ac
        Decrypt the data in *message*. This method delegates most of the work to
        `decrypt_file()`.

        Args:
            message (str|bytes): The data to decrypt. A default key will be used for decryption.

            kwargs (dict): Keyword arguments, which are passed to `decrypt_file()`:

                * always_trust: Whether to always trust keys.

                * passphrase (str): The passphrase to use.

                * output (str): If specified, the path to write the decrypted data to.

                * extra_args (list[str]): A list of extra arguments to pass to `gpg`.
        )rRr�decrypt_filer/�rVr�r�r7rrrr�decrypttszGPG.decryptcCsr|r|�|�std��dg}|r,|�||�|r>|�ddg�|rL|�|�|jd|�}|j||||dd�|S)a�
        Decrypt data in a file or file-like object.

        Args:
            fileobj_or_path (str|file): A path to a file or a file-like object containing the data to be decrypted.

            always_trust: Whether to always trust keys.

            passphrase (str): The passphrase to use.

            output (str): If specified, the path to write the decrypted data to.

            extra_args (list[str]): A list of extra arguments to pass to `gpg`.
        r��	--decryptr�r�r;Tr�)r�r�r�rir\r�)rVr�r�rCr�r�r;rrrrr��s
zGPG.decrypt_filecKs&t||j�}|j|f|�}|��|S)a� Get the list of recipients for an encrypted message. This method delegates most of the work to
        `get_recipients_file()`.

        Args:
            message (str|bytes): The encrypted message.

            kwargs (dict): Keyword arguments, which are passed to `get_recipients_file()`:

                * extra_args (list[str]): A list of extra arguments to pass to `gpg`.
        )rRr�get_recipients_filer/r�rrr�get_recipients�szGPG.get_recipientscCsbdddg}|r|�|�|jd|�}|j|||dd�g}t�|j�D]}|�|�d��qH|S)a0
        Get the list of recipients for an encrypted message in a file or file-like object.

        Args:
            fileobj_or_path (str|file): A path to a file or file-like object containing the encrypted data.

            extra_args (list[str]): A list of extra arguments to pass to `gpg`.
        r�z--list-onlyz-vr;Tr�r!)rir\r��
PUBLIC_KEY_RE�finditerr^r�r�)rVr�r�r;rZidsr�rrrr��s	

zGPG.get_recipients_filec
	Cstj}||kr,d�t|��}td||f��||d}ddl}z�|jdd�\}}g}t	|t
�rf|g}|D]}	|�d|	|f�qjtj�|�tj}
t
�d	|
�t�||
�|j��t�|�|jd
|�}|�d|g�}|j|||jd�|jdk�rtd
|j��W5t�|�X|S)aY
        Set the trust level for one or more keys.

        Args:
            fingerprints (str|list[str]): A key id for which to set the trust level, or a list of such key ids.

            trustlevel (str): The trust level. This is one of the following.

                                  * ``'TRUST_EXPIRED'``
                                  * ``'TRUST_UNDEFINED'``
                                  * ``'TRUST_NEVER'``
                                  * ``'TRUST_MARGINAL'``
                                  * ``'TRUST_FULLY'``
                                  * ``'TRUST_ULTIMATE'``
        r�z-Invalid trust level: "%s" (must be one of %s)r!rNr�r�z%s:%s:zwriting ownertrust info: %srCz--import-ownertrustrHz&gpg returned an error - return code %d)rbr�r��sortedr�r�rPr�r�rrr��linesepr)r1r,rrr/r\rZr]r&r�)
rVr�Z
trustlevelZlevelsZpossr�rkr�rxr�rrrcrrr�
trust_keys�s0

zGPG.trust_keys)rTNFFNNNN)F)Nr})NN)NF)NNTFFNN)NTN)N)NN)FNTF)FTFNTN)FNF)r�N)N)Nr�r�r�)NFNTNFN)FNNN)N)=r]r^r_r`r�rr4rr-r$r+r�r�r�rr�r1r0rbr,r2r\rWrlrZr|r�r]r�r�r�rBr�r�r�rDr�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�r�rrrrrr9%s���
O#

#
#
�
G
'



9�
I

'
5
&�
D

r9)Rr`r�r�email.utilsrrMrr�rP�rer�rqrrr%r<�__version__�
__author__�__date__r�namer	r
rN�unicoder�
basestringrr�bytesrQr��	NameError�	getLoggerr]r)�handlers�
addHandler�NullHandlerrrQr�compiler�getfilesystemencodingrrr8rArDrKrPrR�objectrSrbr��Ir�r�r�r�rFr�r�rrrrrr$r+r,r-r0r1r2rr_r�r�r9rrrr�<module>s�#




!	$		
CW�
2e�A$ 11


F1le Man4ger