Python源码示例:binascii.a2b_base64()

示例1
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
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
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
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 
示例5
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 
示例6
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) 
示例7
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) 
示例8
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'') 
示例9
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 
示例10
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) 
示例11
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 
示例12
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 
示例13
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 
示例14
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') 
示例15
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 
示例16
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) 
示例17
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) 
示例18
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) 
示例19
def b64decode(s, altchars=None, validate=False):
    """Decode the Base64 encoded bytes-like object or ASCII string s.

    Optional altchars must be a bytes-like object or ASCII string of length 2
    which specifies the alternative alphabet used instead of the '+' and '/'
    characters.

    The result is returned as a bytes object.  A binascii.Error is raised if
    s is incorrectly padded.

    If validate is False (the default), characters that are neither in the
    normal base-64 alphabet nor the alternative alphabet are discarded prior
    to the padding check.  If validate is True, these non-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) 
示例20
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 
示例21
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) 
示例22
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 
示例23
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) 
示例24
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 
示例25
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) 
示例26
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 
示例27
def send_email_task(
    subject, message, from_email, recipient_list, fail_silently=True, attachments=None, cc=None, bcc=None
):
    """
    Common Celery task to send e-mail message to given recipients.
    :param subject: subject of the e-mail
    :param message: e-mail message (in plain text)
    :param from_email: sender address
    :param recipient_list: list of recipient addresses
    :param fail_silently: if True, won't raise exceptions
    :param attachments: optional list of attachments to add to the message
    :param cc: list of cc e-mails
    :param bcc: list of bcc e-mails
    """
    if attachments:
        for attachment in attachments:
            attachment[1] = binascii.a2b_base64(attachment[1])  # decoding

    send_mail(subject, message, from_email, recipient_list, fail_silently, attachments, cc, bcc)
    logger.info(
        u"'events:tasks:send_email_task' finished sending e-mail to '{0}' with subject '{1}'."
        .format('; '.join(recipient_list), subject)
    ) 
示例28
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 
示例29
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) 
示例30
def _aes_decrypt(aes_key, aes_text) -> Text:
    """
    使用密钥解密文本信息,将会自动填充空白字符
    :param aes_key: 解密密钥
    :param aes_text: 需要解密的文本
    :return: 经过解密的数据
    """
    # 初始化解码器
    cipher = AES.new(_fill_16(aes_key), AES.MODE_ECB)
    # 优先逆向解密十六进制为bytes
    converted = a2b_base64(aes_text.replace('-', '/').replace("%3D", "=").encode())
    # 使用aes解密密文
    decrypt_text = str(cipher.decrypt(converted), encoding='utf-8').replace('\0', '')
    # 返回执行结果
    return decrypt_text.strip()