本文整理匯總了Python中base64.b32decode方法的典型用法代碼示例。如果您正苦於以下問題:Python base64.b32decode方法的具體用法?Python base64.b32decode怎麽用?Python base64.b32decode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類base64
的用法示例。
在下文中一共展示了base64.b32decode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: _from_safe_path_param_name
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
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)
示例2: _FromSafePathParamName
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def _FromSafePathParamName(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: String, safe regex group name.
Returns:
String; parameter matched from 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)
示例3: _filter_decode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def _filter_decode(self, data, encoding):
if its.py_v3 and isinstance(data, bytes):
data = data.decode('utf-8')
encoding = encoding.lower()
encoding = re.sub(r'^(base|rot)-(\d\d)$', r'\1\2', encoding)
if encoding == 'base16' or encoding == 'hex':
data = base64.b16decode(data)
elif encoding == 'base32':
data = base64.b32decode(data)
elif encoding == 'base64':
data = base64.b64decode(data)
elif encoding == 'rot13':
data = codecs.getdecoder('rot-13')(data)[0]
else:
raise ValueError('Unknown encoding type: ' + encoding)
if its.py_v3 and isinstance(data, bytes):
data = data.decode('utf-8')
return data
示例4: torrent
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def torrent(self):
""":class:`Torrent` instance"""
# Prevent circular import issues
from ._torrent import Torrent
torrent = Torrent()
torrent.name = self.dn
if self.tr:
torrent.trackers = self.tr
if self.ws:
torrent.webseeds = self.ws
if self.xl:
torrent._metainfo['info']['length'] = self.xl
if hasattr(self, '_info'):
torrent.metainfo['info'] = self._info
elif len(self.infohash) == 40:
torrent._infohash = self.infohash
else:
# Convert base 32 to base 16 (SHA1)
torrent._infohash = base64.b16encode(
base64.b32decode(self.infohash)).decode('utf-8').lower()
return torrent
示例5: test_b32decode_casefold
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
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')
示例6: generate_token
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
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
示例7: test_b32decode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
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)
示例8: reroot_tree
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def reroot_tree(self):
newick = request.forms.get('newick')
tree = Tree(newick, format=1)
left_most = tree.search_nodes(name=request.forms.get('left_most'))[0]
right_most = tree.search_nodes(name=request.forms.get('right_most'))[0]
new_root = tree.get_common_ancestor(left_most, right_most)
tree.set_outgroup(new_root)
# Ete3 tree.write function replaces some charachters that we support in the interface.
# As a workaround we are going to encode node names with base32, after serialization
# we are going to decode them back.
for node in tree.traverse('preorder'):
node.name = 'base32' + base64.b32encode(node.name.encode('utf-8')).decode('utf-8')
new_newick = tree.write(format=1)
# ete also converts base32 padding charachter "=" to "_" so we need to replace it.
new_newick = re.sub(r"base32(\w*)", lambda m: base64.b32decode(m.group(1).replace('_','=')).decode('utf-8'), new_newick)
return json.dumps({'newick': new_newick})
示例9: read_qa_comat
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def read_qa_comat(filename):
qa_comat_dict = {}
print 'read qa_comat ...'
with open(filename) as fin:
for l in tqdm(fin):
to = l.strip().split('\t')
#print 'test len(to): ', len(to)
m = np.loads(base64.b32decode(to[1]))
# print 'test m: ', m
# to[0] key which is qid_uid_rid; to[1] is the corresponding
# 3-row numpy array to denote the qa co-occur matrix
m0 = np.asarray(m[0], dtype=np.int16)
m1 = np.asarray(m[1], dtype=np.int16)
qa_comat_dict[to[0]] = [m0,m1,m[2]]
return qa_comat_dict
# Convert Embedding Dict 2 numpy array
示例10: generate_code
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def generate_code(secret, value = None):
if value is None:
value = int(time.time() / 30)
value = struct.pack('>q', value)
secretkey = base64.b32decode(secret.upper())
hash = hmac.new(secretkey, value, hashlib.sha1).digest()
offset = struct.unpack('>B', hash[-1:])[0] & 0xf
truncated_hash = hash[offset:offset + 4]
truncated_hash = struct.unpack('>L', truncated_hash)[0]
truncated_hash &= 0x7fffffff
truncated_hash %= 1000000
return '%06d' % truncated_hash
#----------------------------------------------------------------------
# counter based code varification
#----------------------------------------------------------------------
示例11: read_qrcode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def read_qrcode(self):
p = subprocess.Popen(['zbarimg', '-q', '--raw', 'PNG:-'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
temp_png = StringIO.StringIO()
self.inframe.save(temp_png, 'png')
std_out, std_err = p.communicate(input=temp_png.getvalue())
if len(std_out) == 0:
return False
if std_err:
raise Exception("zbarimg", std_err.strip())
#p = subprocess.Popen(['iconv', '-f', 'UTF-8', '-t', 'ISO-8859-1'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
#std_out, std_err = p.communicate(input=std_out)
#if std_err:
# raise Exception("iconv", std_err.strip())
try:
self.indata = {'body': b32decode(std_out.rstrip().replace('/', '='))}
self.write_tun()
except:
pass
示例12: decode_qr_code_data
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def decode_qr_code_data(encoded: bytes) -> str:
if not isinstance(encoded, (bytes,)):
raise InvalidSignatureRequest("Can only decode bytes")
if encoded == b'':
raise InvalidSignatureRequest("Cannot decode empty bytes")
try:
compressed_bytes = b32decode(encoded)
try:
decompressed_bytes = decompress(compressed_bytes)
try:
data = decompressed_bytes.decode('utf-8')
return data
except UnicodeError:
raise InvalidSignatureRequest("Not valid UTF-8")
except OSError:
raise InvalidSignatureRequest("Not gzipped")
except (TypeError, Base32DecodeError):
raise InvalidSignatureRequest("Not Base32")
示例13: decode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def decode(self, text):
if len(text) % 8:
text += "="*(8-(len(text)%8))
try:
return base64.b32decode(text.upper())
except:
return ""
示例14: partial_split_qr_decode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def partial_split_qr_decode(qr_code):
'Decode a partial key-set QR code.'
# calculate padding that would have been stripped
padding = (len(qr_code) * 5 - 9 * 8) % 32
binary = base64.b32decode(qr_code + ('=' * padding))
# check the header
if not binary.startswith('\x84\x7c\x20'):
raise ValueError('invalid header')
# the missing index for this set
missing = ord(binary[3])
required = ord(binary[4])
checksum = binary[5:9]
# extract each binary key and recompose the key
keys = set()
start = 9
index = 0
while start + 32 <= len(binary):
if index == missing: index += 1
key = '\x10\x01' + chr(index) + chr(required) + checksum + binary[start:start + 32]
keys.add(encode_check(key))
start += 32
index += 1
return keys
示例15: identity_key_from_address
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32decode [as 別名]
def identity_key_from_address(onion_address: str) -> bytes:
"""
Converts a hidden service address into its public identity key.
:param onion_address: hidden service address
:returns: **bytes** for the hidden service's public identity key
:raises: **ValueError** if address malformed or checksum is invalid
"""
if onion_address.endswith('.onion'):
onion_address = onion_address[:-6]
if not stem.util.tor_tools.is_valid_hidden_service_address(onion_address, version = 3):
raise ValueError("'%s.onion' isn't a valid hidden service v3 address" % onion_address)
# onion_address = base32(PUBKEY | CHECKSUM | VERSION) + '.onion'
# CHECKSUM = H('.onion checksum' | PUBKEY | VERSION)[:2]
decoded_address = base64.b32decode(onion_address.upper())
pubkey = decoded_address[:32]
expected_checksum = decoded_address[32:34]
version = decoded_address[34:35]
checksum = hashlib.sha3_256(CHECKSUM_CONSTANT + pubkey + version).digest()[:2]
if expected_checksum != checksum:
checksum_str = stem.util.str_tools._to_unicode(binascii.hexlify(checksum))
expected_checksum_str = stem.util.str_tools._to_unicode(binascii.hexlify(expected_checksum))
raise ValueError('Bad checksum (expected %s but was %s)' % (expected_checksum_str, checksum_str))
return pubkey