本文整理匯總了Python中base64.b32encode方法的典型用法代碼示例。如果您正苦於以下問題:Python base64.b32encode方法的具體用法?Python base64.b32encode怎麽用?Python base64.b32encode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在類base64
的用法示例。
在下文中一共展示了base64.b32encode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。
示例1: get_id
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def get_id(source_uuid):
"""Derive a short (12 character) id from a random UUID.
The supplied UUID must be a version 4 UUID object.
"""
if isinstance(source_uuid, str):
source_uuid = uuid.UUID(source_uuid)
if source_uuid.version != 4:
raise ValueError(_('Invalid UUID version (%d)') % source_uuid.version)
# The "time" field of a v4 UUID contains 60 random bits
# (see RFC4122, Section 4.4)
random_bytes = _to_byte_string(source_uuid.time, 60)
# The first 12 bytes (= 60 bits) of base32-encoded output is our data
encoded = base64.b32encode(random_bytes.encode("latin-1"))[:12]
return encoded.lower().decode('utf-8')
示例2: from_torrent_url
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def from_torrent_url(url):
import base64
import bencode
import hashlib
import urllib
from kmediatorrent.utils import url_get
torrent_data = url_get(url)
metadata = bencode.bdecode(torrent_data)
hashcontents = bencode.bencode(metadata['info'])
digest = hashlib.sha1(hashcontents).digest()
b32hash = base64.b32encode(digest)
params = {
'dn': metadata['info']['name'],
'tr': metadata['announce'],
}
plugin.log.info(params)
paramstr = urllib.urlencode(params)
return 'magnet:?%s&%s' % ('xt=urn:btih:%s' % b32hash, paramstr)
示例3: totpauth_url
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def totpauth_url(totp_dev):
# https://github.com/google/google-authenticator/wiki/Key-Uri-Format
label = totp_dev.user.username.encode('utf8')
# We need two separate issuers, otherwise deploying in prod will override our authenticator token from
# dev
if settings.DEPLOY_MODE == 'production':
issuer = b'CourSys'
else:
issuer = b'CourSys-DEV'
query = [
('secret', base64.b32encode(totp_dev.bin_key)),
('digits', totp_dev.digits),
('issuer', issuer)
]
return b'otpauth://totp/%s?%s' % (label, urlencode(query).encode('ascii'))
# based on http://stackoverflow.com/a/4631504/1236542
示例4: _to_safe_path_param_name
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def _to_safe_path_param_name(matched_parameter):
"""Creates a safe string to be used as a regex group name.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
We cast the matched_parameter to base32 (since the alphabet is safe),
strip the padding (= not safe) and prepend with _, since we know a token
can begin with underscore.
Args:
matched_parameter: A string containing the parameter matched from the URL
template.
Returns:
A string that's safe to be used as a regex group name.
"""
return '_' + base64.b32encode(matched_parameter).rstrip('=')
示例5: _ToSafePathParamName
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def _ToSafePathParamName(matched_parameter):
"""Creates a safe string to be used as a regex group name.
Only alphanumeric characters and underscore are allowed in variable name
tokens, and numeric are not allowed as the first character.
We cast the matched_parameter to base32 (since the alphabet is safe),
strip the padding (= not safe) and prepend with _, since we know a token
can begin with underscore.
Args:
matched_parameter: String; parameter matched from URL template.
Returns:
String, safe to be used as a regex group name.
"""
return '_' + base64.b32encode(matched_parameter).rstrip('=')
示例6: address_from_identity_key
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def address_from_identity_key(key: Union[bytes, 'cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PublicKey', 'cryptography.hazmat.primitives.asymmetric.ed25519.Ed25519PrivateKey'], suffix: bool = True) -> str: # type: ignore
"""
Converts a hidden service identity key into its address. This accepts all
key formats (private, public, or public bytes).
:param key: hidden service identity key
:param suffix: includes the '.onion' suffix if true, excluded otherwise
:returns: **str** hidden service address
:raises: **ImportError** if key is a cryptographic type and ed25519 support
is unavailable
"""
key = stem.util._pubkey_bytes(key) # normalize key into bytes
version = stem.client.datatype.Size.CHAR.pack(3)
checksum = hashlib.sha3_256(CHECKSUM_CONSTANT + key + version).digest()[:2]
onion_address = base64.b32encode(key + checksum + version)
return stem.util.str_tools._to_unicode(onion_address + b'.onion' if suffix else onion_address).lower()
示例7: _filter_encode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def _filter_encode(self, data, encoding):
if its.py_v3 and isinstance(data, str):
data = data.encode('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.b16encode(data)
elif encoding == 'base32':
data = base64.b32encode(data)
elif encoding == 'base64':
data = base64.b64encode(data)
elif encoding == 'rot13':
data = codecs.getencoder('rot-13')(data.decode('utf-8'))[0]
else:
raise ValueError('Unknown encoding type: ' + encoding)
if its.py_v3 and isinstance(data, bytes):
data = data.decode('utf-8')
return data
示例8: connect
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def connect(self):
if not self.trade_pub_socket and self.trade_pub:
self.trade_pub_socket = self.zmq_context.socket(zmq.SUB)
self.trade_pub_socket.connect(self.trade_pub)
self.trade_pub_socket_stream = ZMQStream(self.trade_pub_socket)
self.trade_pub_socket_stream.on_recv(self._on_trade_publish)
self.trade_in_socket.send( "OPN," + base64.b32encode(os.urandom(10)))
response_message = self.trade_in_socket.recv()
opt_code = response_message[:3]
raw_message = response_message[4:]
if opt_code != 'OPN':
if opt_code == 'ERR':
raise TradeClientException( error_message = raw_message )
raise TradeClientException( error_message = 'Protocol Error: Unknown message opt_code received' )
self.connection_id = raw_message
示例9: crypter
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def crypter(ack='',iv='2769514380123456',base='b64'):
ahk = hmac.new(b'vilame',ack.encode(),'md5').hexdigest()
c = CrypterAES(ahk, iv)
if base == 'b16': _encode,_decode = base64.b16encode,base64.b16decode
if base == 'b32': _encode,_decode = base64.b32encode,base64.b32decode
if base == 'b64': _encode,_decode = base64.b64encode,base64.b64decode
if base == 'b85': _encode,_decode = base64.b85encode,base64.b85decode
if base == 'urlsafe_b64': _encode,_decode = base64.urlsafe_b64encode,base64.urlsafe_b64decode
def zbase_enc(data):
return _encode(zlib.compress(data.encode())[2:-4]).decode()
def zbase_dec(basedata):
return zlib.decompress(_decode(basedata),-15).decode()
def zencrypt(data): return c.encrypt_base(zlib.compress(data.encode())[2:-4],_encode)
def zdecrypt(data): return zlib.decompress(c.decrypt_base(data,_decode),-15).decode()
c.zencrypt = zencrypt
c.zdecrypt = zdecrypt
c.zbase_enc = zbase_enc
c.zbase_dec = zbase_dec
c.encrypt = lambda data:c.encrypt_base(data,_encode)
c.decrypt = lambda data:c.decrypt_base(data,_decode).decode()
return c
示例10: _generate_uri
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def _generate_uri(hotp, type_name, account_name, issuer, extra_parameters):
parameters = [
("digits", hotp._length),
("secret", base64.b32encode(hotp._key)),
("algorithm", hotp._algorithm.name.upper()),
]
if issuer is not None:
parameters.append(("issuer", issuer))
parameters.extend(extra_parameters)
uriparts = {
"type": type_name,
"label": ("%s:%s" % (quote(issuer), quote(account_name)) if issuer
else quote(account_name)),
"parameters": urlencode(parameters),
}
return "otpauth://{type}/{label}?{parameters}".format(**uriparts)
示例11: writeServerPassword
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def writeServerPassword( password ):
"""
Dump our ScrambleSuit server descriptor to file.
The file should make it easy for bridge operators to obtain copy &
pasteable server descriptors.
"""
assert len(password) == const.SHARED_SECRET_LENGTH
assert const.STATE_LOCATION != ""
passwordFile = os.path.join(const.STATE_LOCATION, const.PASSWORD_FILE)
log.info("Writing server password to file `%s'." % passwordFile)
password_str = "# You are supposed to give this password to your clients to append it to their Bridge line"
password_str = "# For example: Bridge scramblesuit 192.0.2.1:5555 EXAMPLEFINGERPRINTNOTREAL password=EXAMPLEPASSWORDNOTREAL"
password_str = "# Here is your password:"
password_str = "password=%s\n" % base64.b32encode(password)
try:
with open(passwordFile, 'w') as fd:
fd.write(password_str)
except IOError as err:
log.error("Error writing password file to `%s': %s" %
(passwordFile, err))
示例12: get_public_server_options
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def get_public_server_options( cls, transportOptions ):
"""
Return ScrambleSuit's BridgeDB parameters, i.e., the shared secret.
As a fallback mechanism, we return an automatically generated password
if the bridge operator did not use `ServerTransportOptions'.
"""
log.debug("Tor's transport options: %s" % str(transportOptions))
if not "password" in transportOptions:
log.warning("No password found in transport options (use Tor's " \
"`ServerTransportOptions' to set your own password)." \
" Using automatically generated password instead.")
srv = state.load()
transportOptions = {"password":
base64.b32encode(srv.fallbackPassword)}
cls.uniformDHSecret = srv.fallbackPassword
return transportOptions
示例13: __init__
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def __init__(self):
self.nodes = []
self.metadata = self.config.get('metadata', {})
try:
creator = self.metadata['creator']
except KeyError:
raise UsageError("Must specify creator metadata.")
if not creator.isalnum():
raise UsageError(
"Creator must be alphanumeric. Found {!r}".format(creator)
)
self.creator = creator
self.metadata.update(self.identity.metadata)
self.metadata['distribution'] = self.distribution
# Try to make names unique even if the same creator is starting
# multiple clusters at the same time. This lets other code use the
# name as a way to identify nodes. This is only necessary in one
# place, the node creation code, to perform cleanup when the create
# operation fails in a way such that it isn't clear if the instance has
# been created or not.
self.random_tag = b32encode(os.urandom(8)).lower().strip("\n=")
示例14: base32_encode
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [as 別名]
def base32_encode(self):
"""Encode as Base32
Base32 is a notation for encoding arbitrary byte data using a
restricted set of symbols that can be conveniently used by humans
and processed by computers. It uses a smaller set of characters than
Base64, usually the uppercase alphabet and the numbers 2 to 7.
Returns:
Chepy: The Chepy object.
Examples:
>>> Chepy("some data").base32_encode().output.decode()
"ONXW2ZJAMRQXIYI="
"""
self.state = base64.b32encode(self._convert_to_bytes())
return self
示例15: reroot_tree
# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import b32encode [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})