我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用base64.b32decode()。
def generate_token(seed): """Summary Args: seed (TYPE): Description Returns: TYPE: Description """ seed = base64.b32decode(seed, True) hmacHash = hmac.new( seed, struct.pack( ">Q", int( time.time() // 30)), hashlib.sha1).digest() hashOffset = ord(hmacHash[19]) & 0xf token = (struct.unpack( ">I", hmacHash[hashOffset:hashOffset + 4])[0] & 0x7fffffff) % 10 ** 6 return token
def clean_response(self): code = self.cleaned_data['response'] verifier = oath.TOTP(base64.b32decode(self.device.base32_secret), drift=self.device.drift) # lock verifier to now verifier.time = verifier.time last_t = self.device.last_t or -1 ok = verifier.verify(code, tolerance=TOTP_TOLERANCE, min_t=last_t + 1) if not ok: raise forms.ValidationError(_('That code could not be verified.')) # persist data self.device.last_t = verifier.t() self.device.drift = verifier.drift self.device.last_used_at = timezone.now() self.device.save() return code
def main(): usage = '''%(prog)s [--str="data"]''' parser = argparse.ArgumentParser(usage=usage) parser.add_argument('--str', action='store', type=str, dest='txt', help='The String Decode') parser.add_argument("--version", action="version", version="%(prog)s 1.0b") args = parser.parse_args() txt = args.txt if len(sys.argv) == 1: parser.print_help() sys.exit(1) try: msg = base64.b32decode(txt) print (color("[+] Base32: ", 2, 1) + "%s" % msg) except TypeError: print(color("\n[!] This data non-base32", 1, 1)) print(color("[*] Please try usage data with how2decoded-brute-force.py\n", 3, 1)) sys.exit(1)
def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode(b'', True), b'') eq(base64.b32decode(b'ME======', True), b'a') eq(base64.b32decode(b'MFRA====', True), b'ab') eq(base64.b32decode(b'MFRGG===', True), b'abc') eq(base64.b32decode(b'MFRGGZA=', True), b'abcd') eq(base64.b32decode(b'MFRGGZDF', True), b'abcde') # Lower cases eq(base64.b32decode(b'me======', True), b'a') eq(base64.b32decode(b'mfra====', True), b'ab') eq(base64.b32decode(b'mfrgg===', True), b'abc') eq(base64.b32decode(b'mfrggza=', True), b'abcd') eq(base64.b32decode(b'mfrggzdf', True), b'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode, b'me======') # Mapping zero and one eq(base64.b32decode(b'MLO23456'), b'b\xdd\xad\xf3\xbe') eq(base64.b32decode(b'M1023456', map01=b'L'), b'b\xdd\xad\xf3\xbe') eq(base64.b32decode(b'M1023456', map01=b'I'), b'b\x1d\xad\xf3\xbe') self.assertRaises(TypeError, base64.b32decode, b"", map01="")
def test_b32decode_casefold(self): eq = self.assertEqual eq(base64.b32decode('', True), '') eq(base64.b32decode('ME======', True), 'a') eq(base64.b32decode('MFRA====', True), 'ab') eq(base64.b32decode('MFRGG===', True), 'abc') eq(base64.b32decode('MFRGGZA=', True), 'abcd') eq(base64.b32decode('MFRGGZDF', True), 'abcde') # Lower cases eq(base64.b32decode('me======', True), 'a') eq(base64.b32decode('mfra====', True), 'ab') eq(base64.b32decode('mfrgg===', True), 'abc') eq(base64.b32decode('mfrggza=', True), 'abcd') eq(base64.b32decode('mfrggzdf', True), 'abcde') # Expected exceptions self.assertRaises(TypeError, base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode('MLO23456'), 'b\xdd\xad\xf3\xbe') eq(base64.b32decode('M1023456', map01='L'), 'b\xdd\xad\xf3\xbe') eq(base64.b32decode('M1023456', map01='I'), 'b\x1d\xad\xf3\xbe')
def from_ascii(s_ascii, prefix="", encoding="base64"): """This is the opposite of to_ascii. It will throw BadPrefixError if the prefix is not found. """ if isinstance(s_ascii, bytes): s_ascii = s_ascii.decode('ascii') if isinstance(prefix, bytes): prefix = prefix.decode('ascii') s_ascii = remove_prefix(s_ascii.strip(), prefix) if encoding == "base64": s_ascii += "="*((4 - len(s_ascii)%4)%4) s_bytes = base64.b64decode(s_ascii) elif encoding == "base32": s_ascii += "="*((8 - len(s_ascii)%8)%8) s_bytes = base64.b32decode(s_ascii.upper()) elif encoding in ("base16", "hex"): s_bytes = base64.b16decode(s_ascii.upper()) else: raise NotImplementedError return s_bytes
def _from_safe_path_param_name(safe_parameter): """Takes a safe regex group name and converts it back to the original value. Only alphanumeric characters and underscore are allowed in variable name tokens, and numeric are not allowed as the first character. The safe_parameter is a base32 representation of the actual value. Args: safe_parameter: A string that was generated by _to_safe_path_param_name. Returns: A string, the parameter matched from the URL template. """ assert safe_parameter.startswith('_') safe_parameter_as_base32 = safe_parameter[1:] padding_length = - len(safe_parameter_as_base32) % 8 padding = '=' * padding_length return base64.b32decode(safe_parameter_as_base32 + padding)
def test_b32decode(self): eq = self.assertEqual tests = {b'': b'', b'AA======': b'\x00', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes self.check_other_types(base64.b32decode, b'MFRGG===', b"abc") self.check_decode_type_errors(base64.b32decode)
def compute_totp(secret, offset=0): """ Computes the current TOTP code. :param secret: Base32 encoded secret. :type secret: unicode :param offset: Time offset (in steps, use eg -1, 0, +1 for compliance with RFC6238) for which to compute TOTP. :type offset: int :returns: TOTP for current time (+/- offset). :rtype: unicode """ assert(type(secret) == six.text_type) assert(type(offset) in six.integer_types) try: key = base64.b32decode(secret) except TypeError: raise Exception('invalid secret') interval = offset + int(time.time()) // 30 msg = struct.pack('>Q', interval) digest = hmac.new(key, msg, hashlib.sha1).digest() o = 15 & (digest[19] if six.PY3 else ord(digest[19])) token = (struct.unpack('>I', digest[o:o + 4])[0] & 0x7fffffff) % 1000000 return u'{0:06d}'.format(token)
def D32(secret): #s=secret.strip().decode('hex') #s=s[::-1] #s=base64.b32decode(s) ch=secret.strip() #print ch result='' if len(ch) % 2 == 0: ch=ch.decode('hex') else: ch=('0'+ch).decode('hex') s=base64.b64decode(ch) print s for i in range(1000,10000): hash=hashlib.md5(str(i)).hexdigest()[8:-8] if hash==s: result=i break return str(result)
def get_hotp_token(secret, intervals_no): """This is where the magic happens.""" key = base64.b32decode(normalize(secret), True) # True is to fold lower into uppercase msg = struct.pack(">Q", intervals_no) h = hmac.new(key, msg, hashlib.sha1).digest() o = ord(h[19]) & 15 h = str((struct.unpack(">I", h[o:o+4])[0] & 0x7fffffff) % 1000000) return prefix0(h)
def normalize(key): """Normalizes secret by removing spaces and padding with = to a multiple of 8""" k2 = key.strip().replace(' ','') # k2 = k2.upper() # skipped b/c b32decode has a foldcase argument if len(k2)%8 != 0: k2 += '='*(8-len(k2)%8) return k2
def packOnionAddress(onion, port): onion = onion.replace(".onion", "") return base64.b32decode(onion.upper()) + struct.pack("H", port) # From 12byte format to ip, port
def extract_secret(self, resp, user=None): setup_signer = self.signer(user or self.user) return base64.b32decode(setup_signer.unsign(resp.context[-1]['form'].secret))
def __init__(self, folder, file_lock_time_wait=0.1): self.folder = folder self.key_filter_in = lambda key: key self.key_filter_out = lambda key: key self.file_lock_time_wait = file_lock_time_wait # How long we should wait before retrying to lock a file held by another process # We still need a mutex for each file as portalocker only blocks other processes self.file_locks = defaultdict(thread.allocate_lock) # Make sure we use valid filenames. if sys.platform == "win32": import base64 def key_filter_in_windows(key): """ Windows doesn't allow \ / : * ? "< > | in filenames. To go around this encode the keys with base32. """ return to_native(base64.b32encode(to_bytes(key))) def key_filter_out_windows(key): """ We need to decode the keys so regex based removal works. """ return to_native(base64.b32decode(to_bytes(key))) self.key_filter_in = key_filter_in_windows self.key_filter_out = key_filter_out_windows
def validate_external_mode_cli( cls, args ): """ Assign the given command line arguments to local variables. """ uniformDHSecret = None try: uniformDHSecret = base64.b32decode(util.sanitiseBase32( args.uniformDHSecret)) except (TypeError, AttributeError) as error: log.error(error.message) raise base.PluggableTransportError("Given password '%s' is not " \ "valid Base32! Run 'generate_password.py' to generate " \ "a good password." % args.uniformDHSecret) parentalApproval = super( ScrambleSuitTransport, cls).validate_external_mode_cli(args) if not parentalApproval: # XXX not very descriptive nor helpful, but the parent class only # returns a boolean without telling us what's wrong. raise base.PluggableTransportError( "Pluggable Transport args invalid: %s" % args ) if uniformDHSecret: rawLength = len(uniformDHSecret) if rawLength != const.SHARED_SECRET_LENGTH: raise base.PluggableTransportError( "The UniformDH password must be %d bytes in length, ", "but %d bytes are given." % (const.SHARED_SECRET_LENGTH, rawLength)) else: cls.uniformDHSecret = uniformDHSecret
def b32_to_b16(s): return b16encode(b32decode(s.upper()))
def __init__(self, folder, file_lock_time_wait=0.1): self.folder = folder self.key_filter_in = lambda key: key self.key_filter_out = lambda key: key self.file_lock_time_wait = file_lock_time_wait # How long we should wait before retrying to lock a file held by another process # We still need a mutex for each file as portalocker only blocks other processes self.file_locks = defaultdict(thread.allocate_lock) # Make sure we use valid filenames. if sys.platform == "win32": import base64 def key_filter_in_windows(key): """ Windows doesn't allow \ / : * ? "< > | in filenames. To go around this encode the keys with base32. """ return base64.b32encode(key) def key_filter_out_windows(key): """ We need to decode the keys so regex based removal works. """ return base64.b32decode(key) self.key_filter_in = key_filter_in_windows self.key_filter_out = key_filter_out_windows
def _b32_decode(v): assert v.startswith("u_"), "{0} didn't start with 'u_'".format(v) v = v[2:] assert len(v) == 26, "u_{0} is the wrong length".format(v) # append padding and uppercase so that b32decode will work v = v.upper() + (6 * "=") return str(uuid.UUID(bytes=base64.b32decode(v)))
def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(b''), b'') eq(base64.b32decode(b'AA======'), b'\x00') eq(base64.b32decode(b'ME======'), b'a') eq(base64.b32decode(b'MFRA===='), b'ab') eq(base64.b32decode(b'MFRGG==='), b'abc') eq(base64.b32decode(b'MFRGGZA='), b'abcd') eq(base64.b32decode(b'MFRGGZDF'), b'abcde') self.assertRaises(TypeError, base64.b32decode, "")
def test_b32decode_error(self): self.assertRaises(binascii.Error, base64.b32decode, b'abc') self.assertRaises(binascii.Error, base64.b32decode, b'ABCDEF==')
def test_b32decode(self): eq = self.assertEqual eq(base64.b32decode(''), '') eq(base64.b32decode('AA======'), '\x00') eq(base64.b32decode('ME======'), 'a') eq(base64.b32decode('MFRA===='), 'ab') eq(base64.b32decode('MFRGG==='), 'abc') eq(base64.b32decode('MFRGGZA='), 'abcd') eq(base64.b32decode('MFRGGZDF'), 'abcde') # Non-bytes self.assertRaises(TypeError, base64.b32decode, bytearray('MFRGG==='))
def test_b32decode_error(self): self.assertRaises(TypeError, base64.b32decode, 'abc') self.assertRaises(TypeError, base64.b32decode, 'ABCDEF==')
def dec_filename(self, enc_name): enc_name += '=' * ((8 - len(enc_name)) % 8) byte_name = self._aes_dec(b32decode(enc_name.encode())) return byte_name.rstrip(bytes(1)).decode()
def __init__(self, s: str='ABCDEFGHIJKLMNOP'): """ Initializes the class with a secret key, using an application-wide default if none is provided. :param s: Expected to be a base32-encoded string, 16 characters long. :type s: str :return: :rtype: """ if '-' in s: s = s.replace('-', '') self._raw_secret = s.upper().rjust(16, 'A')[0:16] self._secret = base64.b32decode(self._raw_secret.encode())
def secret(self, s: str): """ Reset the class with a new secret key. :param s: Expected to be a base32-encoded string, 16 characters long. :type s: str :return: :rtype: """ if '-' in s: s = s.replace('-', '') self._raw_secret = s.upper().rjust(16, 'A')[0:16] self._secret = base64.b32decode(self._raw_secret.encode())
def test_b32decode(self): eq = self.assertEqual tests = {b'': b'', b'AA======': b'\x00', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data), res) eq(base64.b32decode(data.decode('ascii')), res) # Non-bytes eq(base64.b32decode(bytearray(b'MFRGG===')), b'abc')
def test_b32decode_casefold(self): eq = self.assertEqual tests = {b'': b'', b'ME======': b'a', b'MFRA====': b'ab', b'MFRGG===': b'abc', b'MFRGGZA=': b'abcd', b'MFRGGZDF': b'abcde', # Lower cases b'me======': b'a', b'mfra====': b'ab', b'mfrgg===': b'abc', b'mfrggza=': b'abcd', b'mfrggzdf': b'abcde', } for data, res in tests.items(): eq(base64.b32decode(data, True), res) eq(base64.b32decode(data.decode('ascii'), True), res) self.assertRaises(binascii.Error, base64.b32decode, b'me======') self.assertRaises(binascii.Error, base64.b32decode, 'me======') # Mapping zero and one eq(base64.b32decode(b'MLO23456'), b'b\xdd\xad\xf3\xbe') eq(base64.b32decode('MLO23456'), b'b\xdd\xad\xf3\xbe') map_tests = {(b'M1023456', b'L'): b'b\xdd\xad\xf3\xbe', (b'M1023456', b'I'): b'b\x1d\xad\xf3\xbe', } for (data, map01), res in map_tests.items(): data_str = data.decode('ascii') map01_str = map01.decode('ascii') eq(base64.b32decode(data, map01=map01), res) eq(base64.b32decode(data_str, map01=map01), res) eq(base64.b32decode(data, map01=map01_str), res) eq(base64.b32decode(data_str, map01=map01_str), res) self.assertRaises(binascii.Error, base64.b32decode, data) self.assertRaises(binascii.Error, base64.b32decode, data_str)
def test_b32decode_error(self): for data in [b'abc', b'ABCDEF==', b'==ABCDEF']: with self.assertRaises(binascii.Error): base64.b32decode(data) with self.assertRaises(binascii.Error): base64.b32decode(data.decode('ascii'))
def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode) for f in decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii \xcb')
def hash_from_magnet(m): res=Cache.magnet_re.search(m) if res: ih=res.group(1).upper() if len(ih)==40 and Cache.hexa_chars.match(ih): return res.group(1).upper() elif len(ih)==32: s=base64.b32decode(ih) return "".join("{:02X}".format(ord(c)) for c in s) else: raise ValueError('Not BT magnet link') else: raise ValueError('Not BT magnet link')
def decrypt(self, filename): plain_padded = aes256_hiv_decrypt(self.key, base64.b32decode(filename.upper()), self.mac_size) assert(len(plain_padded) == self.filename_plain_size ) plain = plain_padded.rstrip(b'\0') assert(plain.find(b'\0') == -1) return plain.decode("ascii")
def b32decode(data): if not b32Regex.match(data.decode('utf-8')): raise TypeError return base64.b32decode(data)
def _decode(buf): if isinstance(buf, unicode): buf = buf.encode('utf-8') return base64.b32decode(buf, casefold=True, map01='I')
def base32(TEXT, choice): from base64 import b32encode, b32decode return b32encode(TEXT.encode('utf-8')).decode('utf-8') if choice == "encode" else b32decode(TEXT).decode("utf-8")
def test_decode_nonascii_str(self): decode_funcs = (base64.b64decode, base64.standard_b64decode, base64.urlsafe_b64decode, base64.b32decode, base64.b16decode, base64.b85decode, base64.a85decode) for f in decode_funcs: self.assertRaises(ValueError, f, 'with non-ascii \xcb')