U  W[w@sdZddlmZmZddlZddlZddlZddlZddlm Z e eddZ e rXe j ZnddZGdd d eZGd d d eZGd d d eZeZejZejZ[ddd gZdS)zQ Cryptographically secure random implementation, with fallback on normal random. )divisionabsolute_importN)_PY3 getrandbitscCs |dS)Nhex)decode)hexBytesr :/usr/lib/python3/dist-packages/twisted/python/randbytes.py_fromhexsr c@seZdZdZdS)SecureRandomNotAvailablezD Exception raised when no secure random algorithm is found. N__name__ __module__ __qualname____doc__r r r r r sr c@seZdZdZdS)SourceNotAvailablezQ Internal exception used when a specific random source is not available. Nr r r r r rsrc@sfeZdZdZdZeZddZdddZdd Ze rBe j Z d d Z nej Z d d Z e d d ZddZdS) 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 c Cs@z t|WSttfk r:}z t|W5d}~XYnXdS)zO Wrapper around C{os.urandom} that cleanly manage its absence. N)osurandomAttributeErrorNotImplementedErrorr)selfnbyteser r r _osUrandom5s zRandomFactory._osUrandomFcCsLz ||WStk r YnX|r@tjdtdd||StddS)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 availableN)rrwarningswarnRuntimeWarninginsecureRandomr )rrZfallbackr r r secureRandom?s   zRandomFactory.secureRandomcCs<|jdk r0||d}d|d|}t|StddS)z3 Wrapper around C{os.getrandbits}. Nz%%0%dxrz#random.getrandbits is not available)rr r)rrnrr r r _randBits\s  zRandomFactory._randBitscsdfddt|DS)> Wrapper around the C{random} module. csg|]}ttjgqSr )bytesrandomchoice_BYTES.0irr r ms-RandomFactory._randModule..joinrangerrr r0r _randModuleiszRandomFactory._randModulecsdfddt|DS)r'r(csg|]}tjqSr )r*r+r,r-r0r r r1usr2r3r6r r0r r7qsr(c Cs8dD].}zt|||WStk r0YqXqdS)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&r7N)getattrr)rrsrcr r r r"{s zRandomFactory.insecureRandomN)F)rrrrZ randomSourcesrrr#r&rr) maketransZ _maketransr7stringr,r"r r r r r&s     rr#r")rZ __future__rrrrr*r;Ztwisted.python.compatrr8rr)fromhexr RuntimeErrorr robjectrfactoryr#r"__all__r r r r s   g