本文整理汇总了Python中binascii.a2b_base64方法的典型用法代码示例。如果您正苦于以下问题:Python binascii.a2b_base64方法的具体用法?Python binascii.a2b_base64怎么用?Python binascii.a2b_base64使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类binascii
的用法示例。
在下文中一共展示了binascii.a2b_base64方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: b64decode
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def b64decode(s, altchars=None, validate=False):
"""Decode a Base64 encoded byte string.
s is the byte string to decode. Optional altchars must be a
string of length 2 which specifies the alternative alphabet used
instead of the '+' and '/' characters.
The decoded string is returned. A binascii.Error is raised if s is
incorrectly padded.
If validate is False (the default), non-base64-alphabet characters are
discarded prior to the padding check. If validate is True,
non-base64-alphabet characters in the input result in a binascii.Error.
"""
s = _bytes_from_decode_data(s)
if altchars is not None:
altchars = _bytes_from_decode_data(altchars)
assert len(altchars) == 2, repr(altchars)
s = s.translate(bytes.maketrans(altchars, b'+/'))
if validate and not re.match(b'^[A-Za-z0-9+/]*={0,2}$', s):
raise binascii.Error('Non-base64 digit found')
return binascii.a2b_base64(s)
示例2: CheckBasicAuth
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def CheckBasicAuth(self, username, password) :
if not isinstance(username, str) :
raise ValueError('"username" must be a string.')
if not isinstance(password, str) :
raise ValueError('"password" must be a string.')
auth = self.Authorization
if auth :
try :
auth = auth.split()
if len(auth) == 2 and auth[0].lower() == 'basic' :
auth = a2b_base64(auth[1].encode()).decode()
auth = auth.split(':')
return ( auth[0].lower() == username.lower() and \
auth[1] == password )
except :
pass
return False
# ------------------------------------------------------------------------
示例3: decode
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def decode(string):
"""Decode a raw base64 string, returning a bytes object.
This function does not parse a full MIME header value encoded with
base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
level email.header class for that functionality.
"""
if not string:
return bytes()
elif isinstance(string, str):
return a2b_base64(string.encode('raw-unicode-escape'))
else:
return a2b_base64(string)
# For convenience and backwards compatibility w/ standard base64 module
示例4: create
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def create(vek, keySizeBytes, certificatePath):
#print("VEK: " + str(binascii.hexlify(vek)))
publicKeyPem = open(certificatePath).read()
publicKey = RSA.importKey(publicKeyPem)
# Convert from PEM to DER
lines = publicKeyPem.replace(" ", '').split()
publicKeyDer = binascii.a2b_base64(''.join(lines[1:-1]))
cert = x509.load_pem_x509_certificate(SmartStr(publicKeyPem), default_backend())
subjectName = cert.subject.rfc4514_string()
serial = cert.serial_number
cipher = PKCS1_OAEP.new(key=publicKey, hashAlgo=SHA256, mgfunc=lambda x, y: pss.MGF1(x, y, SHA1))
wrapped_key = cipher.encrypt(vek)
#print("WrappedKey: " + str(binascii.hexlify(wrapped_key)))
return CertEncryptedKeyBag(subjectName, serial, keySizeBytes, wrapped_key)
示例5: parse
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def parse(self, data):
# TODO: refactor with ramfiles
if data is None:
return None, None
# probably base64-encoded PSBT
if data[:4] == b"cHNi":
try:
psbt = a2b_base64(data)
if psbt[:5] != b"psbt\xff":
raise HostError("Not a PSBT")
return self.SIGN_PSBT, BytesIO(psbt)
except:
pass
# probably wallet descriptor
if b"&" in data and "?" not in data:
return self.ADD_WALLET, BytesIO(data)
# probably verifying address
if data.startswith(b"bitcoin:") or b"index=" in data:
return self.VERIFY_ADDRESS, BytesIO(data)
return self.UNKNOWN, BytesIO(data)
示例6: sign_psbt
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def sign_psbt(self, stream):
# decode to file
with open(self.path+"/psbt", "wb") as f:
chunk = bytearray(4)
l = stream.readinto(chunk)
while l > 0:
f.write(a2b_base64(chunk[:l]))
l = stream.readinto(chunk)
# reopen to read
with open(self.path+"/psbt", "rb") as f:
# ask the manager to sign transaction
# if tx is not ok - it will raise an error
psbt = await self.manager.sign_psbt(f, remote=True)
if psbt is None:
self.respond(b'error: User cancelled')
# serialize, convert to base64, send back
raw_tx_stream = BytesIO(psbt.serialize())
# convert to base64 in chunks
chunk = bytearray(3)
l = raw_tx_stream.readinto(chunk)
while l > 0:
self.usb.write(b2a_base64(chunk[:l]).strip())
l = raw_tx_stream.readinto(chunk)
# add EOL
self.respond(b'')
示例7: decode
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def decode(s, convert_eols=None):
"""Decode a raw base64 string.
If convert_eols is set to a string value, all canonical email linefeeds,
e.g. "\\r\\n", in the decoded text will be converted to the value of
convert_eols. os.linesep is a good choice for convert_eols if you are
decoding a text attachment.
This function does not parse a full MIME header value encoded with
base64 (like =?iso-8895-1?b?bmloISBuaWgh?=) -- please use the high
level email.header class for that functionality.
"""
if not s:
return s
dec = a2b_base64(s)
if convert_eols:
return dec.replace(CRLF, convert_eols)
return dec
# For convenience and backwards compatibility w/ standard base64 module
示例8: b64decode
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def b64decode(s, altchars=None):
"""Decode a Base64 encoded string.
s is the string to decode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies the
alternative alphabet used instead of the '+' and '/' characters.
The decoded string is returned. A TypeError is raised if s were
incorrectly padded or if there are non-alphabet characters present in the
string.
"""
if altchars is not None:
s = _translate(s, {altchars[0]: '+', altchars[1]: '/'})
try:
return binascii.a2b_base64(s)
except binascii.Error, msg:
# Transform this exception for consistency
raise TypeError(msg)
示例9: _build_login_schematic
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def _build_login_schematic(self) -> Login:
login = None
login_data = self.request.json.get('login')
if login_data is not None:
email = login_data.get('email')
if email is not None:
email = a2b_base64(email).decode()
password = login_data.get('password')
if password is not None:
password = a2b_base64(password).decode()
login = Login(dict(
federated_platform=login_data.get('federatedPlatform'),
federated_token=login_data.get('federatedToken'),
email=email,
password=password
))
return login
示例10: _authenticate_credentials
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def _authenticate_credentials(self):
"""Compare credentials in request to credentials in database.
:raises AuthenticationError when no match found on database
"""
basic_credentials = self.request.headers['authorization']
binary_credentials = a2b_base64(basic_credentials[6:])
email_address, password = binary_credentials.decode().split(':||:')
acct_repository = AccountRepository(self.db)
self.account = acct_repository.get_account_from_credentials(
email_address,
password
)
if self.account is None:
raise AuthenticationError('provided credentials not found')
self.access_token.account_id = self.account.id
self.refresh_token.account_id = self.account.id
示例11: _get_email_address
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def _get_email_address(self):
if self.request.args['platform'] == 'Google':
email_address = get_google_account_email(
self.request.args['token']
)
elif self.request.args['platform'] == 'Facebook':
email_address = get_facebook_account_email(
self.request.args['token']
)
elif self.request.args['platform'] == 'GitHub':
email_address = get_github_account_email(
self.request.args['token']
)
else:
coded_email = self.request.args['token']
email_address = a2b_base64(coded_email).decode()
return email_address
示例12: test_dictionary_verification
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def test_dictionary_verification(self):
test_data = {}
for _ in range(5):
test_data['_' + utilities.random_string(10)] = utilities.random_string(10)
self.sk = security_keys.SigningKey.generate(curve=ecdsa.NIST521p)
test_data = self.sk.sign_dict(test_data, signature_encoding='base64')
self.assertIsInstance(test_data, dict)
# make sure the 'signature' key was added
self.assertIn('signature', test_data)
self.assertEqual(len(test_data), 6)
try:
binascii.a2b_base64(test_data['signature'])
except ValueError:
self.fail('signature could not be decoded as base64')
vk = self.sk.get_verifying_key()
vk.verify_dict(test_data, signature_encoding='base64')
test_data['_' + utilities.random_string(10)] = utilities.random_string(10)
with self.assertRaises(ecdsa.keys.BadSignatureError):
vk.verify_dict(test_data, signature_encoding='base64')
示例13: decode
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def decode(s, convert_eols=None):
"""Decode a raw base64 string.
If convert_eols is set to a string value, all canonical email linefeeds,
e.g. "\\r\\n", in the decoded text will be converted to the value of
convert_eols. os.linesep is a good choice for convert_eols if you are
decoding a text attachment.
This function does not parse a full MIME header value encoded with
base64 (like =?iso-8859-1?b?bmloISBuaWgh?=) -- please use the high
level email.header class for that functionality.
"""
if not s:
return s
dec = a2b_base64(s)
if convert_eols:
return dec.replace(CRLF, convert_eols)
return dec
# For convenience and backwards compatibility w/ standard base64 module
示例14: b64decode
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def b64decode(s, altchars=None):
"""Decode a Base64 encoded string.
s is the string to decode. Optional altchars must be a string of at least
length 2 (additional characters are ignored) which specifies the
alternative alphabet used instead of the '+' and '/' characters.
The decoded string is returned. A TypeError is raised if s is
incorrectly padded. Characters that are neither in the normal base-64
alphabet nor the alternative alphabet are discarded prior to the padding
check.
"""
if altchars is not None:
s = s.translate(string.maketrans(altchars[:2], '+/'))
try:
return binascii.a2b_base64(s)
except binascii.Error, msg:
# Transform this exception for consistency
raise TypeError(msg)
示例15: YARACompile
# 需要导入模块: import binascii [as 别名]
# 或者: from binascii import a2b_base64 [as 别名]
def YARACompile(ruledata):
if ruledata.startswith('#'):
if ruledata.startswith('#h#'):
rule = binascii.a2b_hex(ruledata[3:])
elif ruledata.startswith('#b#'):
rule = binascii.a2b_base64(ruledata[3:])
elif ruledata.startswith('#s#'):
rule = 'rule string {strings: $a = "%s" ascii wide nocase condition: $a}' % ruledata[3:]
elif ruledata.startswith('#q#'):
rule = ruledata[3:].replace("'", '"')
else:
rule = ruledata[1:]
return yara.compile(source=rule)
else:
dFilepaths = {}
if os.path.isdir(ruledata):
for root, dirs, files in os.walk(ruledata):
for file in files:
filename = os.path.join(root, file)
dFilepaths[filename] = filename
else:
for filename in ProcessAt(ruledata):
dFilepaths[filename] = filename
return yara.compile(filepaths=dFilepaths)