
    Ki                         d dl Z d dlZd dlmZmZmZ d dlmZmZ d dl	m
Z
 d dlmZmZmZ d dlmZ d dlmZ d dlmZ d	Zd
Zeegef   Zeeegef   Z G d de      Zy)    N)CallableMappingSequence)AnySupportsFloat)SerializationError)CorruptedDataErrorDecryptionErrorEncryptionError)override)AsyncKeyValue)BaseWrapper__encrypted_data____encryption_version__c                   l    e Zd ZdZ	 ddedededededdf fd	Z	d
e
eef   de
eef   fdZd
e
eef   deeef   fdZd
e
eef   dz  de
eef   dz  fdZedddededz  de
eef   dz  fd       Zedddee   dedz  dee
eef   dz     fd       Zedddededz  dee
eef   dz  edz  f   fd       Zedddee   dedz  deee
eef   dz  edz  f      fd       Zedddded
eeef   dedz  dedz  ddf
d       Zeddddee   deeeef      dedz  dedz  ddf
d       Z xZS )BaseEncryptionWrapperaC  Wrapper that encrypts values before storing and decrypts on retrieval.

    This wrapper encrypts the JSON-serialized value using a custom encryption function
    and stores it as a base64-encoded string within a special key in the dictionary.
    This allows encryption while maintaining the dict[str, Any] interface.
    	key_valueencryption_fndecryption_fnencryption_versionraise_on_decryption_errorreturnNc                 h    || _         || _        || _        || _        || _        t
        |           y)a0  Initialize the encryption wrapper.

        Args:
            key_value: The store to wrap.
            encryption_fn: The encryption function to use. A callable that takes bytes and returns encrypted bytes.
            decryption_fn: The decryption function to use. A callable that takes bytes and an
                           encryption version int and returns decrypted bytes.
            encryption_version: The encryption version to use.
            raise_on_decryption_error: Whether to raise an exception if decryption fails. Defaults to True.
        N)r   r   r   _encryption_fn_decryption_fnsuper__init__)selfr   r   r   r   r   	__class__s         r/home/jay/workspace/scripts/.codegraph-venv/lib/python3.12/site-packages/key_value/aio/wrappers/encryption/base.pyr   zBaseEncryptionWrapper.__init__   s7    $ )2/H&'9,9,9    valuec                 v   	 t        j                  |d      }|j                  d      }	 | j                  |      }t        j                  |      j                  d      }t        |t        | j                  iS # t        $ r}d| }t	        |      |d}~ww xY w# t        $ r}d}t        |      |d}~ww xY w)	zEncrypt a value into the encrypted format.

        The encrypted format looks like:
        {
            "__encrypted_data__": "base64-encoded-encrypted-data",
            "__encryption_version__": 1
        }
        ),:)
separatorsutf-8encodingz$Failed to serialize object to JSON: NasciizFailed to encrypt value)jsondumpsencode	TypeErrorr   r   base64	b64encodedecode	Exceptionr   _ENCRYPTED_DATA_KEY_ENCRYPTION_VERSION_KEYr   )r   r"   json_str
json_bytesemsgencrypted_bytes
base64_strs           r    _encrypt_valuez$BaseEncryptionWrapper._encrypt_value9   s    	1 JJuDH ( AJ
	.%)%8%8%DO$..?FFPWFXJ  #T%<%<
 	
  	1=aSAC$S)q0	1  	.+C!#&A-	.s.   )A: 6B :	BBB	B8%B33B8c                 &   t         |vrd}t        |      |t            }t        |t              sdt	        |       }t        |      t
        |vrd}t        |      |t
           }t        |t              sdt	        |       }t        |      ||fS )Nzmissing encryption version keyz.expected encryption version to be an int, got zmissing encrypted data keyz)expected encrypted data to be a str, got )r4   r	   
isinstanceinttyper3   str)r   r"   r8   r   encrypted_datas        r    _validate_encrypted_payloadz1BaseEncryptionWrapper._validate_encrypted_payloadY   s    "%/2C$S))"#:;,c2B4HZC[B\]C$S))e+.C$S))23.#.=d>>R=STC$S))!>11r!   c                    |yt         |vrt        |t              r|S 	 | j                  |      \  }}t	        j
                  |d      }| j                  ||      }|j                  d      }t        j                  |      S # t        $ r | j                  r Y yt        $ r$}d}| j                  rt        |      |Y d}~yd}~ww xY w)z*Decrypt a value from the encrypted format.NT)validater'   r(   zFailed to decrypt value)r3   r=   dictrB   r/   	b64decoder   r1   r+   loadsr	   r   r2   r
   )	r   r"   r   rA   r9   r6   r5   r7   r8   s	            r    _decrypt_valuez$BaseEncryptionWrapper._decrypt_valueo   s    = e+
5$0GL	151Q1QRW1X.%+%5%5nt%TO $ 3 3OEW XJ&--w-?H::h''! 	-- 	+C--%c*1		s   A#B CC#CC)
collectionkeyrI   c                z   K   | j                   j                  ||       d {   }| j                  |      S 7 wN)rJ   rI   )r   getrH   )r   rJ   rI   r"   s       r    rM   zBaseEncryptionWrapper.get   s9     nn((SZ(HH""5)) Is   !;9;keysc                   K   | j                   j                  ||       d {   }|D cg c]  }| j                  |       c}S 7 #c c}w wN)rN   rI   )r   get_manyrH   )r   rN   rI   valuesr"   s        r    rQ   zBaseEncryptionWrapper.get_many   sG     ~~..DZ.PP8>?u##E*?? Q?s    !AAAA	A	Ac                   K   | j                   j                  ||       d {   \  }}| j                  |      |fS 7 wrL   )r   ttlrH   )r   rJ   rI   r"   rT   s        r    rT   zBaseEncryptionWrapper.ttl   sB     >>--#*-MM
s""5)3.. Ns   !A >A c                   K   | j                   j                  ||       d {   }|D cg c]  \  }}| j                  |      |f c}}S 7 *c c}}w wrP   )r   ttl_manyrH   )r   rN   rI   resultsr"   rT   s         r    rV   zBaseEncryptionWrapper.ttl_many   sP     //Tj/QQDKLjeS$$U+S1LL RLs    !AA	AA
AA)rI   rT   rT   c                   K   | j                  t        |            }| j                  j                  ||||       d {   S 7 w)N)rJ   r"   rI   rT   )r;   rE   r   put)r   rJ   r"   rI   rT   encrypted_values         r    rY   zBaseEncryptionWrapper.put   s@     --d5k:^^''CS]cf'ggggs   =AA ArR   c                   K   |D cg c]  }| j                  t        |             }}| j                  j                  ||||       d {   S c c}w 7 	w)N)rN   rR   rI   rT   )r;   rE   r   put_many)r   rN   rR   rI   rT   r"   encrypted_valuess          r    r\   zBaseEncryptionWrapper.put_many   sZ      KQQD//U<QQ^^,,$?O\flo,ppp Rps   A!A$AA
A)T)__name__
__module____qualname____doc__r   EncryptionFnDecryptionFnr>   boolr   rE   r@   r   r;   tuplerB   rH   r   rM   r   listrQ   floatrT   rV   r   r   rY   r\   __classcell__)r   s   @r    r   r      s    +/  $ $	
   $( 
8
DcN 
tCH~ 
@2c3h 2E#s(O 2,DcNT$9 d38nt>S : >B *S *t *tCQTH~X\G\ * * NR @8C= @t @W[\`adfiai\jmq\qWr @ @ >B /S /t /uTRUWZRZ^^bMbdilpdpMpGq / / NR M8C= Mt MW[\abfgjlogobpswbwy~  BF  zF  cF  ]G  XH M M X\z~ hS hc): h3QU: hcpswcw h  DH h h  "&$(	qsm	q c*+	q
 $J	q T!	q 
	q 	qr!   r   )r/   r+   collections.abcr   r   r   typingr   r   !key_value.shared.errors.key_valuer   +key_value.shared.errors.wrappers.encryptionr	   r
   r   typing_extensionsr   !key_value.aio.protocols.key_valuer   key_value.aio.wrappers.baser   r3   r4   bytesrb   r>   rc   r    r!   r    <module>rr      sg      7 7 % @ l l & ; 3* 2  'e+,ZqK Zqr!   