當前位置: 首頁>>代碼示例>>Python>>正文


Python base64.standard_b64decode方法代碼示例

本文整理匯總了Python中base64.standard_b64decode方法的典型用法代碼示例。如果您正苦於以下問題:Python base64.standard_b64decode方法的具體用法?Python base64.standard_b64decode怎麽用?Python base64.standard_b64decode使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在base64的用法示例。


在下文中一共展示了base64.standard_b64decode方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: process_challenge

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def process_challenge(self, challenge_parameters):
        user_id_for_srp = challenge_parameters['USER_ID_FOR_SRP']
        salt_hex = challenge_parameters['SALT']
        srp_b_hex = challenge_parameters['SRP_B']
        secret_block_b64 = challenge_parameters['SECRET_BLOCK']
        # re strips leading zero from a day number (required by AWS Cognito)
        timestamp = re.sub(r" 0(\d) ", r" \1 ",
                           datetime.datetime.utcnow().strftime("%a %b %d %H:%M:%S UTC %Y"))
        hkdf = self.get_password_authentication_key(user_id_for_srp,
                                                    self.password, hex_to_long(srp_b_hex), salt_hex)
        secret_block_bytes = base64.standard_b64decode(secret_block_b64)
        msg = bytearray(self.pool_id.split('_')[1], 'utf-8') + bytearray(user_id_for_srp, 'utf-8') + \
              bytearray(secret_block_bytes) + bytearray(timestamp, 'utf-8')
        hmac_obj = hmac.new(hkdf, msg, digestmod=hashlib.sha256)
        signature_string = base64.standard_b64encode(hmac_obj.digest())
        response = {'TIMESTAMP': timestamp,
                    'USERNAME': user_id_for_srp,
                    'PASSWORD_CLAIM_SECRET_BLOCK': secret_block_b64,
                    'PASSWORD_CLAIM_SIGNATURE': signature_string.decode('utf-8')}
        if self.client_secret is not None:
            response.update({
                "SECRET_HASH":
                self.get_secret_hash(self.username, self.client_id, self.client_secret)})
        return response 
開發者ID:capless,項目名稱:warrant,代碼行數:26,代碼來源:aws_srp.py

示例2: run

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def run(self, params={}):
        try:
            data = params.get(Input.BASE64)
            errors = params.get(Input.ERRORS)
            result = base64.standard_b64decode(data)
            if errors in ["replace", "ignore"]:
                return {Output.DATA: result.decode('utf-8', errors=errors)}
            else:
                return {Output.DATA: result.decode('utf-8')}
        except Exception as e:
            self.logger.error("An error has occurred while decoding ", e)
            raise PluginException(
                cause="Failed to decode because valid base64 input was not provided.",
                assistance='If you would like continue to attempt to decode the input try setting the value of the error field to ignore errors or to replace the characters.',
                data=e
            ) 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:18,代碼來源:action.py

示例3: test_b64decode_invalid_chars

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def test_b64decode_invalid_chars(self):
        # issue 1466065: Test some invalid characters.
        tests = ((b'%3d==', b'\xdd'),
                 (b'$3d==', b'\xdd'),
                 (b'[==', b''),
                 (b'YW]3=', b'am'),
                 (b'3{d==', b'\xdd'),
                 (b'3d}==', b'\xdd'),
                 (b'@@', b''),
                 (b'!', b''),
                 (b'YWJj\nYWI=', b'abcab'))
        for bstr, res in tests:
            self.assertEqual(base64.b64decode(bstr), res)
            self.assertEqual(base64.standard_b64decode(bstr), res)
            self.assertEqual(base64.urlsafe_b64decode(bstr), res)

        # Normal alphabet characters not discarded when alternative given
        res = b'\xFB\xEF\xBE\xFF\xFF\xFF'
        self.assertEqual(base64.b64decode(b'++[[//]]', b'[]'), res)
        self.assertEqual(base64.urlsafe_b64decode(b'++--//__'), res) 
開發者ID:IronLanguages,項目名稱:ironpython2,代碼行數:22,代碼來源:test_base64.py

示例4: do_POST

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def do_POST(self):
        """Loads the licence for the requested resource"""
        try:
            url_parse = urlparse(self.path)
            common.debug('Handling HTTP POST IPC call to {}', url_parse.path)
            if '/license' not in url_parse:
                self.send_response(404)
                self.end_headers()
                return
            length = int(self.headers.get('content-length', 0))
            data = self.rfile.read(length).decode('utf-8').split('!')
            b64license = self.server.msl_handler.get_license(
                challenge=data[0], sid=base64.standard_b64decode(data[1]).decode('utf-8'))
            self.send_response(200)
            self.end_headers()
            self.wfile.write(base64.standard_b64decode(b64license))
        except Exception as exc:
            import traceback
            common.error(g.py2_decode(traceback.format_exc(), 'latin-1'))
            self.send_response(500 if isinstance(exc, MSLError) else 400)
            self.end_headers() 
開發者ID:CastagnaIT,項目名稱:plugin.video.netflix,代碼行數:23,代碼來源:http_server.py

示例5: as_file

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def as_file(self):
        """If obj[%data_key_name] exists, return name of a file with base64
        decoded obj[%data_key_name] content otherwise obj[%file_key_name]."""
        use_data_if_no_file = not self._file and self._data
        if use_data_if_no_file:
            if self._base64_file_content:
                if isinstance(self._data, str):
                    content = self._data.encode()
                else:
                    content = self._data
                self._file = _create_temp_file_with_content(
                    base64.standard_b64decode(content))
            else:
                self._file = _create_temp_file_with_content(self._data)
        if self._file and not os.path.isfile(self._file):
            raise ConfigException("File does not exists: %s" % self._file)
        return self._file 
開發者ID:tomplus,項目名稱:kubernetes_asyncio,代碼行數:19,代碼來源:kube_config.py

示例6: _urlsafe_b64decode

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def _urlsafe_b64decode(self, value):
        value = value.rstrip('\r\n')  # some encoders like to append a newline...
        try:
            # `base64.urlsafe_b64decode()` just ignores illegal
            # characters *but* we want to be *more strict*
            if not self._URLSAFE_B64_VALID_CHARACTERS.issuperset(value):
                raise ValueError
            # `base64.urlsafe_b64decode()` (contrary to `base64.standard_b64decode()`)
            # does *not* accept unicode strings (even not pure-ASCII ones) :-/
            value = string_as_bytes(value)
            value = base64.urlsafe_b64decode(value)
        except (ValueError, TypeError):  # (TypeError is raised on incorrect Base64 padding)
            raise FieldValueError(public_message=(
                '"{}" is not a valid URL-safe-Base64-encoded string '
                '[see: RFC 4648, section 5]'.format(ascii_str(value))))
        return value 
開發者ID:CERT-Polska,項目名稱:n6,代碼行數:18,代碼來源:fields.py

示例7: _update_marathon_json

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def _update_marathon_json(self, package_json):
        """Updates the marathon.json definition to contain the desired name and version strings.
        """
        # note: the file isn't valid JSON, so we edit the raw content instead
        marathon_encoded = package_json.get("marathon", {}).get("v2AppMustacheTemplate")
        orig_marathon_lines = base64.standard_b64decode(marathon_encoded).decode().split("\n")

        marathon_lines = []
        for line in orig_marathon_lines:
            name_match = re.match(r'^ *"PACKAGE_NAME": ?"(.*)",?$', line.rstrip("\n"))
            version_match = re.match(r'^ *"PACKAGE_VERSION": ?"(.*)",?$', line.rstrip("\n"))
            if name_match:
                line = line.replace(name_match.group(1), self._pkg_name)
            elif version_match:
                line = line.replace(version_match.group(1), self._pkg_version)
            marathon_lines.append(line)

        log.info("Updated marathon.json.mustache:")
        log.info("\n".join(difflib.unified_diff(orig_marathon_lines, marathon_lines, lineterm="")))

        # Update parent package object with changes:
        package_json["marathon"]["v2AppMustacheTemplate"] = base64.standard_b64encode(
            "\n".join(marathon_lines).encode("utf-8")
        ).decode() 
開發者ID:mesosphere,項目名稱:dcos-kafka-service,代碼行數:26,代碼來源:release_builder.py

示例8: _read_auth_response

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def _read_auth_response(self, response):
        """
        Read the authentication request's response sent by the database
        and validate the server signature which was returned.

        :param response: Response from the database
        :raises: ReqlDriverError | ReqlAuthError
        :return: None
        """

        json_response = self._decode_json_response(response, with_utf8=True)

        (
            first_client_message,
            authentication,
        ) = self._get_authentication_and_first_client_message(json_response)
        server_signature = base64.standard_b64decode(authentication[b"v"])

        if not self._compare_digest(server_signature, self._server_signature):
            raise ReqlAuthError("Invalid server signature", self._host, self._port)

        self._next_state() 
開發者ID:rethinkdb,項目名稱:rethinkdb-python,代碼行數:24,代碼來源:handshake.py

示例9: response_from_kitty

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def response_from_kitty(self, boss: Boss, window: Optional[Window], payload_get: PayloadGetType) -> ResponseType:
        windows = [boss.active_window]
        match = payload_get('match')
        if match:
            windows = list(boss.match_windows(match))
        mt = payload_get('match_tab')
        if mt:
            windows = []
            tabs = tuple(boss.match_tabs(mt))
            if not tabs:
                raise MatchError(payload_get('match_tab'), 'tabs')
            for tab in tabs:
                windows += tuple(tab)
        encoding, _, q = payload_get('data').partition(':')
        if encoding == 'text':
            data = q.encode('utf-8')
        elif encoding == 'base64':
            data = base64.standard_b64decode(q)
        else:
            raise TypeError(f'Invalid encoding for send-text data: {encoding}')
        for window in windows:
            if window is not None:
                window.write_to_child(data) 
開發者ID:kovidgoyal,項目名稱:kitty,代碼行數:25,代碼來源:send_text.py

示例10: _login

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def _login(sess, cookies_file=None, cookies_base64=None):
        if cookies_file is None:
            if cookies_base64 is None:
                cookies_base64 = os.environ.get('DL_COURSERA_COOKIES_BASE64')
                assert cookies_base64

            cookies = base64.standard_b64decode(cookies_base64)

            with TmpFile() as tmpfile:
                with open(tmpfile, 'wb') as ofs:
                    ofs.write(cookies)

                cj = MozillaCookieJar()
                cj.load(tmpfile)
        else:
            cj = MozillaCookieJar()
            cj.load(cookies_file)

        sess.cookies.update(cj) 
開發者ID:feng-lei,項目名稱:dl_coursera,代碼行數:21,代碼來源:Crawler.py

示例11: sign_extract

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def sign_extract(signature):
	if not signature:
		return None, None, None
	try:
		text = base64.standard_b64decode(signature)
	except:
		return None, None, None
	part = text.split(':')
	if len(part) != 3:
		return None, None, None
	user = part[0].strip('\r\n\t ')
	try:
		ts = long(part[1])
	except:
		return None, None, None
	verify = part[2].strip('\r\n\t ').lower()
	return user, ts, verify

# 檢查文件名 
開發者ID:skywind3000,項目名稱:collection,代碼行數:21,代碼來源:cfs.py

示例12: save_crawled_screeshot

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def save_crawled_screeshot(b64_screenshot, max_size, f_save=False):
    screenshot_size = (len(b64_screenshot)*3) /4
    if screenshot_size < max_size or f_save:
        image_content = base64.standard_b64decode(b64_screenshot.encode())
        sha256_string = sha256(image_content).hexdigest()
        filepath = get_screenshot_filepath(sha256_string)
        if os.path.isfile(filepath):
            #print('File already exist')
            return sha256_string
        # create dir
        dirname = os.path.dirname(filepath)
        if not os.path.exists(dirname):
            os.makedirs(dirname)
        with open(filepath, 'wb') as f:
            f.write(image_content)
        return sha256_string
    return False 
開發者ID:CIRCL,項目名稱:AIL-framework,代碼行數:19,代碼來源:Screenshot.py

示例13: IsValidBase64String

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def IsValidBase64String(string_to_validate):
    """Verifies if a string is a valid Base64 encoded string, after replacing '-' with '/'

    :param string string_to_validate:
        String to validate.

    :return:
        Whether given string is a valid base64 string or not.
    :rtype: str
    """
    # '-' is not supported char for decoding in Python(same as C# and Java) which has similar logic while parsing ResourceID generated by backend
    try:
        buffer = base64.standard_b64decode(string_to_validate.replace('-', '/'))
        if len(buffer) != 4:
            return False
    except Exception as e:
        if six.PY2:
            e = e.message
        if type(e) == binascii.Error:
            return False
        else:
            raise e
    return True 
開發者ID:Azure,項目名稱:azure-cosmos-python,代碼行數:25,代碼來源:base.py

示例14: check_originating_identity

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def check_originating_identity():
    """
    Check and decode the "X-Broker-API-Originating-Identity" header
    https://github.com/openservicebrokerapi/servicebroker/blob/v2.13/spec.md#originating-identity
    """
    from flask import request, json
    if "X-Broker-API-Originating-Identity" in request.headers:
        try:
            platform, value = request.headers["X-Broker-API-Originating-Identity"].split(None, 1)
            request.originating_identity = {
                'platform': platform,
                'value': json.loads(base64.standard_b64decode(value))
            }
        except ValueError as e:
            return to_json_response(ErrorResponse(
                description='Improper "X-Broker-API-Originating-Identity" header. ' + str(e))
            ), HTTPStatus.BAD_REQUEST
    else:
        request.originating_identity = None 
開發者ID:eruvanos,項目名稱:openbrokerapi,代碼行數:21,代碼來源:request_filter.py

示例15: run

# 需要導入模塊: import base64 [as 別名]
# 或者: from base64 import standard_b64decode [as 別名]
def run(self, params={}):
        raw = base64.standard_b64decode(params[Input.BYTES])
        md5 = hashlib.md5(raw).hexdigest()  # nosec
        sha1 = hashlib.sha1(raw).hexdigest()  # nosec
        sha256 = hashlib.sha256(raw).hexdigest()
        sha512 = hashlib.sha512(raw).hexdigest()

        hashes = {
            Output.MD5: md5,
            Output.SHA1: sha1,
            Output.SHA256: sha256,
            Output.SHA512: sha512,
        }
        return hashes 
開發者ID:rapid7,項目名稱:insightconnect-plugins,代碼行數:16,代碼來源:action.py


注:本文中的base64.standard_b64decode方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。