U
    ÓEnj   ã                   @   sr   d Z ddlZddlZddlZddlmZmZmZ ddlm	Z	 e
edœdd„Ze
e
e
dœd	d
„Ze
e
dœdd„ZdS )uÛ  
AES-256-CBC encrypt/decrypt for secrets stored in the `app_secret` table.

Interoperable with the PHP side (utils/secret-crypto.php):
  - key    = SHA-256(passphrase)                      -> 32 bytes (AES-256)
  - iv      = random 16 bytes, per value
  - padding = PKCS7
  - stored  = base64(iv) + ":" + base64(ciphertext)

The passphrase is the deployment secret `SECRETS_ENC_KEY` â€” the SAME value must
be set in the Python .env and in the PHP config/secrets.config.php.
é    N)ÚCipherÚ
algorithmsÚmodes)Úpadding)Ú
passphraseÚreturnc                 C   s   t  |  d¡¡ ¡ S )Núutf-8)ÚhashlibÚsha256ÚencodeÚdigest)r   © r   úM/var/www/api.dyntland.com/public_html/python_social_comments/secret_crypto.pyÚ
_key_bytes   s    r   )Ú	plaintextr   r   c                 C   s„   t |ƒ}t d¡}t d¡ ¡ }| |  d¡¡| ¡  }t	t
 |¡t |¡ƒ ¡ }| |¡| ¡  }t |¡ ¡ d t |¡ ¡  S )Né   é€   r   ú:)r   ÚosÚurandomr   ÚPKCS7ÚpadderÚupdater   Úfinalizer   r   ÚAESr   ÚCBCÚ	encryptorÚbase64Ú	b64encodeÚdecode)r   r   ÚkeyÚivr   Údatar   Úctr   r   r   Úencrypt   s    
r$   )Ústoredr   c           
      C   sŽ   | rd| krd S |   dd¡\}}t|ƒ}t |¡}t |¡}tt |¡t |¡ƒ 	¡ }| 
|¡| ¡  }t d¡ ¡ }	|	 
|¡|	 ¡   d¡S )Nr   é   r   r   )Úsplitr   r   Ú	b64decoder   r   r   r   r   Ú	decryptorr   r   r   r   Úunpadderr   )
r%   r   Ziv_b64Zct_b64r    r!   r#   r)   Úpaddedr*   r   r   r   Údecrypt$   s    

r,   )Ú__doc__r   r   r	   Ú&cryptography.hazmat.primitives.ciphersr   r   r   Úcryptography.hazmat.primitivesr   ÚstrÚbytesr   r$   r,   r   r   r   r   Ú<module>   s   
