�
Ϫ�f�
� �� � d Z ddlZddlZddlZ eedd� Zej Z G d� de � Z
G d� de � Z G d� d � Z e� Z
e
j Ze
j Z[
g d
�Zy)zQ
Cryptographically secure random implementation, with fallback on normal random.
� N�getrandbitsc � � e Zd ZdZy)�SecureRandomNotAvailablezD
Exception raised when no secure random algorithm is found.
N��__name__�
__module__�__qualname__�__doc__� � �:/usr/lib/python3/dist-packages/twisted/python/randbytes.pyr r � � �r r c � � e Zd ZdZy)�SourceNotAvailablezQ
Internal exception used when a specific random source is not available.
Nr r r r
r r r r r c � � e Zd ZdZdZeZdedefd�Zd
dede defd�Z
dedefd�Zej Z
e
d d � Zdedefd
�Zdedefd�Zy)�
RandomFactoryz�
Factory providing L{secureRandom} and L{insecureRandom} methods.
You shouldn't have to instantiate this class, use the module level
functions instead: it is an implementation detail and could be removed or
changed arbitrarily.
r �nbytes�returnc �r � t j |� S # t t f$ r}t |� �d}~ww xY w)zO
Wrapper around C{os.urandom} that cleanly manage its absence.
N)�os�urandom�AttributeError�NotImplementedErrorr )�selfr �es r
�
_osUrandomzRandomFactory._osUrandom- s7 � � (��:�:�f�%�%��� 3�4� (�$�Q�'�'�� (�s � �6�1�6�fallbackc � � | j |� S # t $ r Y nw xY w|r-t j dt d�� | j |� S t
d� �)ak
Return a number of secure random bytes.
@param nbytes: number of bytes to generate.
@type nbytes: C{int}
@param fallback: Whether the function should fallback on non-secure
random or not. Default to C{False}.
@type fallback: C{bool}
@return: a string of random bytes.
@rtype: C{str}
zPurandom unavailable - proceeding with non-cryptographically secure random source� )�category�
stacklevelz!No secure random source available)r r �warnings�warn�RuntimeWarning�insecureRandomr )r r r s r
�secureRandomzRandomFactory.secureRandom6 sd � � ��?�?�6�*�*��!� �� �� ��M�M�M�'��
� �&�&�v�.�.�*�+N�O�O� � � �c � � | j �*| j |dz � }d|dz z |z }t |� S t d� �)z3
Wrapper around C{os.getrandbits}.
� z%%0%dxr z#random.getrandbits is not available)r �_fromhexr )r r �n�hexBytess r
� _randBitszRandomFactory._randBitsS sN � � ���'�� � ��!��,�A� �F�Q�J�/�1�4�H��H�%�%� �!F�G�Gr r c
� � dj t |� D �cg c]+ }t t j | j
� g� ��- c}� S c c}w )z6
Wrapper around the C{random} module.
r )�join�range�bytes�random�choice�_BYTES)r r �is r
�_randModulezRandomFactory._randModule` s: � � �x�x�e�F�m�T����
�
�d�k�k� :�;�<�T�U�U��Ts �0Ac �f � | j |� S # t $ r Y nw xY w| j |� S )z�
Return a number of non secure random bytes.
@param nbytes: number of bytes to generate.
@type nbytes: C{int}
@return: a string of random bytes.
@rtype: C{str}
)r- r r6 )r r s r
r% zRandomFactory.insecureRandomf s9 � � ��>�>�&�)�)��!� �� ������'�'r' |