def _cipher(cls, data, salt): """xor static key against data - encrypts & decrypts""" key = cls._key key_size = len(key) return join_byte_values( value ^ ord(key[(salt + idx) % key_size]) for idx, value in enumerate(iter_byte_values(data)))
def getrandbytes(rng, count): """return byte-string containing *count* number of randomly generated bytes, using specified rng""" # NOTE: would be nice if this was present in stdlib Random class ###just in case rng provides this... ##meth = getattr(rng, "getrandbytes", None) ##if meth: ## return meth(count) if not count: return _BEMPTY def helper(): # XXX: break into chunks for large number of bits? value = rng.getrandbits(count<<3) i = 0 while i < count: yield value & 0xff value >>= 3 i += 1 return join_byte_values(helper())
def decode_bytes(self, source): """decode bytes from base64 string. :arg source: byte string to decode. :returns: byte string containing decoded data. """ if not isinstance(source, bytes): raise TypeError("source must be bytes, not %s" % (type(source),)) ##padding = self.padding ##if padding: ## # TODO: add padding size check? ## source = source.rstrip(padding) chunks, tail = divmod(len(source), 4) if tail == 1: # only 6 bits left, can't encode a whole byte! raise ValueError("input string length cannot be == 1 mod 4") next_value = nextgetter(imap(self._decode64, source)) try: return join_byte_values(self._decode_bytes(next_value, chunks, tail)) except KeyError as err: raise ValueError("invalid character: %r" % (err.args[0],))
#: all hex chars HEX_CHARS = u("0123456789abcdefABCDEF") #: upper case hex chars UPPER_HEX_CHARS = u("0123456789ABCDEF") #: lower case hex chars LOWER_HEX_CHARS = u("0123456789abcdef") #------------------------------------------------------------- # byte strings #------------------------------------------------------------- #: special byte string containing all possible byte values #: NOTE: for efficiency, this is treated as singleton by some of the code ALL_BYTE_VALUES = join_byte_values(irange(256)) #: some string constants we reuse B_EMPTY = b'' B_NULL = b'\x00' B_EQUAL = b'=' #============================================================================= # byte translation #============================================================================= #: base list used to compile byte translations _TRANSLATE_SOURCE = list(iter_byte_chars(ALL_BYTE_VALUES)) def compile_byte_translation(mapping, source=None): """