3
( È\X  ã               @   s’   d Z ddlmZ ddlZddlZddlZddlZddlmZ ddl	m
Z
 ddlmZ ddlmZ dZejd	 Zd
d„ Zdd„ Zdd„ Zdd„ ZdS )z This File Provides Cryptography.é    )ÚdivisionN)Údefault_backend)ÚCipher)ÚAES)ÚCFB8ó   }é   c             C   s\   t jtƒ}ttt|ƒƒt|ƒtƒ ƒ}|jƒ }t	| t
jƒr@| jƒ } tj||j| ƒ |jƒ  ƒS )z—
    Encrypt the plaintext with AES method.

    Parameters:
        plaintext -- String to be encrypted.
        key       -- Key for encryption.
    )ÚosÚurandomÚiv_sizer   r   Úpadr   r   Ú	encryptorÚ
isinstanceÚsixÚ	text_typeÚencodeÚbase64Z	b64encodeÚupdateÚfinalize)Z	plaintextÚkeyÚivÚcipherr   © r   ú//usr/share/pgadmin4/web/pgadmin/utils/crypto.pyÚencrypt   s    	
r   c             C   sR   t j| ƒ} | dt… }ttt|ƒƒt|ƒtƒ ƒ}|jƒ }|j	| td… ƒ|j
ƒ  S )z¯
    Decrypt the AES encrypted string.

    Parameters:
        ciphertext -- Encrypted string with AES method.
        key        -- key to decrypt the encrypted string.
    N)r   Z	b64decoder   r   r   r   r   r   Ú	decryptorr   r   )Z
ciphertextr   r   r   r   r   r   r   Údecrypt3   s
    	
r   c             C   s<   t | tjƒr| jƒ } | dd… } t| ƒdkr0| S | jdtƒS )zAdd padding to the key.Né    é   é   )r   r   r   )r   r   r   r   ÚlenÚljustÚpadding_string)r   r   r   r   r   D   s    r   c             C   sX   t jƒ }ttdƒr(| jdƒ} |jdƒ}n| jƒ } |jƒ }|j| ƒ |j|ƒ d|jƒ  S )aÑ  
    pqencryptpassword -- to encrypt a password
    This is intended to be used by client applications that wish to send
    commands like ALTER USER joe PASSWORD 'pwd'.  The password need not
    be sent in cleartext if it is encrypted on the client side.  This is
    good because it ensures the cleartext password won't end up in logs,
    pg_stat displays, etc. We export the function so that clients won't
    be dependent on low-level details like whether the enceyption is MD5
    or something else.

    Arguments are the cleartext password, and the SQL name of the user it
    is for.

    Return value is "md5" followed by a 32-hex-digit MD5 checksum..

    Args:
      password:
      user:

    Returns:

    Údecodezutf-8Úmd5)Úhashlibr$   ÚhasattrÚstrr   r   Z	hexdigest)ZpasswordÚuserÚmr   r   r   ÚpqencryptpasswordU   s    



r*   )Ú__doc__Z
__future__r   r   r%   r	   r   Zcryptography.hazmat.backendsr   Z&cryptography.hazmat.primitives.ciphersr   Z1cryptography.hazmat.primitives.ciphers.algorithmsr   Z,cryptography.hazmat.primitives.ciphers.modesr   r"   Z
block_sizer   r   r   r   r*   r   r   r   r   Ú<module>
   s   
