Python base64.b64decode() Examples

The following are 40 code examples for showing how to use base64.b64decode(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may want to check out the right sidebar which shows the related API usage.

You may also want to check out all available functions/classes of the module base64 , or try the search function .

Example 1
Project: aegea   Author: kislyuk   File: git.py    License: Apache License 2.0 7 votes vote down vote up
def __init__(self, blob):
        super(Blob, self).__init__(blob)
        self._api = blob.get('url', '')

        #: Raw content of the blob.
        self.content = blob.get('content').encode()

        #: Encoding of the raw content.
        self.encoding = blob.get('encoding')

        #: Decoded content of the blob.
        self.decoded = self.content
        if self.encoding == 'base64':
            self.decoded = b64decode(self.content)

        #: Size of the blob in bytes
        self.size = blob.get('size')
        #: SHA1 of the blob
        self.sha = blob.get('sha') 
Example 2
Project: dustmaps   Author: gregreen   File: json_serializers.py    License: GNU General Public License v2.0 6 votes vote down vote up
def deserialize_ndarray(d):
    """
    Deserializes a JSONified :obj:`numpy.ndarray`. Can handle arrays serialized
    using any of the methods in this module: :obj:`"npy"`, :obj:`"b64"`,
    :obj:`"readable"`.

    Args:
        d (`dict`): A dictionary representation of an :obj:`ndarray` object.

    Returns:
        An :obj:`ndarray` object.
    """
    if 'data' in d:
        x = np.fromstring(
            base64.b64decode(d['data']),
            dtype=d['dtype'])
        x.shape = d['shape']
        return x
    elif 'value' in d:
        return np.array(d['value'], dtype=d['dtype'])
    elif 'npy' in d:
        return deserialize_ndarray_npy(d)
    else:
        raise ValueError('Malformed np.ndarray encoding.') 
Example 3
Project: BandwagongVPS_controller   Author: Pryriat   File: bwh_ctr.py    License: GNU General Public License v3.0 6 votes vote down vote up
def lan_event(self):
        '''变更语言的方法'''
        #读取本地配置文件
        num = 0
        with open(".\data.ini",'rb') as f:
            self.lan_data = f.readlines()
        with open(".\data.ini",'wb') as f:
            for line in self.lan_data:
                if num == self.dual_host_view.currentRow() + 1:
                    data = base64.b64decode(line)
                    data = json.loads(data.decode())
                    data['lan'] = self.lan_input.currentIndex()
                    f.write(base64.b64encode(json.dumps(data).encode()))
                    f.write('\n'.encode())
                else:
                    f.write(line)
                num += 1

        a = QMessageBox()
        #写入成功提示
        a.information(a,self.tr("Success"),self.tr("Language will be changed after resrart the application")) 
Example 4
Project: BandwagongVPS_controller   Author: Pryriat   File: bwh_ctr.py    License: GNU General Public License v3.0 6 votes vote down vote up
def dual_host_view_update(self):
        self.dual_host_view.clear()
        self.file = open(".\data.ini",'rb')
        fr = True
        tmp_i = 0
        for lines in self.file:
            if not len(lines.strip()):
                continue
            if fr:
                self.dual_host_currentindex = int(base64.b64decode(lines).decode())
                fr = False
            else:
                tmp_data = json.loads(base64.b64decode(lines).decode())
                self.dual_host_view.addItem(tmp_data['name'])
                if tmp_i == self.dual_host_currentindex:
                    self.current_host.setText(tmp_data['name'])
            tmp_i += 1
        self.dual_host_view.setCurrentRow(self.dual_host_currentindex-1)
        self.dual_host_view.update() 
Example 5
Project: iris   Author: doitintl   File: main.py    License: MIT License 6 votes vote down vote up
def tag_one():
    data = json.loads(base64.b64decode(request.json['message']['data']))
    logging.info(data)
    try:
        method_name = data['protoPayload']['methodName']
        for plugin in Plugin.plugins:
            if plugin.is_on_demand():
                for method in plugin.methodsNames():
                    if method.lower() in method_name.lower():
                        gcp_object = plugin.get_gcp_object(data)
                        if gcp_object is not None:
                            project_id = data['resource']['labels'][
                                'project_id']
                            logging.info("Calling tag one for %s", plugin.__class__.__name__)
                            plugin.tag_one(gcp_object, project_id)
                            plugin.do_batch()
    except Exception as e:
        logging.error(e)
    return 'ok', 200 
Example 6
Project: bioservices   Author: cokelaer   File: wikipathway.py    License: GNU General Public License v3.0 6 votes vote down vote up
def getColoredPathway(self, pathwayId, filetype="svg", revision=0,
            color=None, graphId=None):
        """Get a colored image version of the pathway.

        :param str pwId: The pathway identifier.
        :param int revision: The revision number of the pathway (use '0' for most recent version).
        :param str fileType:  The image type (One of 'svg', 'pdf' or 'png'). Not
            yet implemented. svg is returned for now.
        :returns: Binary form of the image.

        .. todo:: graphId, color parameters
        """

        url = self.url + "getColoredPathway?pwId={}".format(pathwayId)
        if revision:
            url += "&revision={}".format(revision)
        url += "&format=json"
        request = self.http_get(url)
        try:
            data = request['data']  
            return base64.b64decode(data)
        except:
            return request 
Example 7
Project: bioservices   Author: cokelaer   File: chemspider.py    License: GNU General Public License v3.0 6 votes vote down vote up
def image(self, Id):
        """ Return string containing PNG binary image data of 2D structure image

        ::

            >>> from bioservices import *
            >>> s = ChemSpider()
            >>> ret = s.image(1020)
            >>> with open("test.png", "w") as f:
            ...     f.write(ret)
            >>> s.on_web("test.png")
        """
        url = "Search.asmx/GetCompoundThumbnail?id=%s&token=%s" % (Id, self._token)
        res = self.http_get(url, frmt="xml")
        res = self.easyXML(res)
        #TODO python3 compatible !
        import base64
        image = base64.b64decode(res.root.text)
        return image 
Example 8
Project: Paradrop   Author: ParadropLabs   File: auth.py    License: Apache License 2.0 6 votes vote down vote up
def get_username_password(userpass):
    """
    Please note: username and password can either be presented in plain text
    such as "admin:password" or base64 encoded such as "YWRtaW46cGFzc3dvcmQ=".
    Both forms should be returned from this function.
    """
    plaintext = base64.b64decode(userpass)

    segments = plaintext.split(':')
    count = len(segments)
    if count == 1:
        return segments[0], ''
    elif count == 2:
        return segments
    else:
        raise Exception('There should be at most two segments!') 
Example 9
Project: ANGRYsearch   Author: DoTheEvo   File: angrysearch.py    License: GNU General Public License v2.0 6 votes vote down vote up
def get_tray_icon(self):
        base64_data = '''iVBORw0KGgoAAAANSUhEUgAAABYAAAAWCAYAAADEtGw7AAAABHN
                         CSVQICAgIfAhkiAAAAQNJREFUOI3t1M9KAlEcxfHPmP0xU6Ogo
                         G0teoCiHjAIfIOIepvKRUE9R0G0KNApfy0c8hqKKUMrD9zVGc4
                         9nPtlsgp5n6qSVSk7cBG8CJ6sEX63UEcXz4jE20YNPbygPy25Q
                         o6oE+fEPXFF7A5yA9Eg2sQDcU3sJd6k89O4iiMcYKVol3rH2Mc
                         a1meZ4hMdNPCIj+SjHHfFZU94/0Nwlv4rWoY7vhrdeLNoO86bG
                         lym/ge3lsHDdI2fojbBG6sUtzOiQ1wQOwk6GwWKHeJyHtxOcFi
                         0TpFaxmnhNcyIW45bQ6RS3Hq4MeB7Ltyahki9Gd2xidWiwG9va
                         nCZqi7xlZGVHfwN6+5nU/ccBUYAAAAASUVORK5CYII='''

        pm = Qg.QPixmap()
        pm.loadFromData(base64.b64decode(base64_data))
        i = Qg.QIcon()
        i.addPixmap(pm)
        return i

    # OFF BY DEFAULT
    # 0.2 SEC DELAY TO LET USER FINISH TYPING BEFORE INPUT BECOMES A DB QUERY 
Example 10
Project: mindustry-modding   Author: SimonWoodburyForget   File: msch.py    License: GNU General Public License v3.0 6 votes vote down vote up
def load(data, encoding="utf8"):
    """ Loads a base64 encoded schematic `str` object, 
    or a non-base65 encoded `bytes` object; returns a 
    Schematics object containing a Schematic, and it's 
    metadata, like width, height and tags."""
    if isinstance(data, str):
        base64header = "bXNjaAB"
        if not data.startswith(base64header):
            raise ValueError(f"String should start with: {base64header}")
        data = bytes(data, encoding)
        data = b64decode(data)

    if isinstance(data, bytes):
        data = msch.parse(data)
        return data
    else:
        raise ValueError(f"Unknown or unsupported type: {type(data)}")

########################################
## Writer
######################################## 
Example 11
Project: joeecc   Author: johndoe31415   File: Tools.py    License: GNU General Public License v3.0 6 votes vote down vote up
def load_pem_data(filename, specifier):
	"""Loads the PEM payload, designated with a BEGIN and END specifier, from a
	file given by its filename."""
	data = None
	with open(filename, "r") as f:
		spec_begin = "-----BEGIN " + specifier + "-----"
		spec_end = "-----END " + specifier + "-----"
		for line in f:
			line = line.rstrip()
			if (data is None) and (line == spec_begin):
				data = [ ]
			elif (data is not None) and (line == spec_end):
				break
			elif data is not None:
				data.append(line)
	if data is None:
		raise Exception("Trying to parse PEM file with specifier '%s', but no such block in file found." % (specifier))
	data = base64.b64decode("".join(data).encode("utf-8"))
	return data 
Example 12
Project: pysm4   Author: yang3yen   File: sm4.py    License: MIT License 6 votes vote down vote up
def decrypt_ecb(cipher_text, key):
    """
    SM4(ECB)解密
    :param cipher_text: 密文
    :param key: 密钥, 小于等于16字节
    """
    cipher_text = b64decode(cipher_text)
    cipher_hex = _hex(cipher_text)

    # 密码检验
    key = _key_iv_check(key_iv=key)
    plain_hex_list = []
    for i in _range(len(cipher_text) // BLOCK_BYTE):
        sub_hex = cipher_hex[i * BLOCK_HEX:(i + 1) * BLOCK_HEX]
        plain = decrypt(cipher_num=int(sub_hex, 16),
                        mk=int(_hex(key), 16))
        plain_hex_list.append(num2hex(num=plain, width=BLOCK_HEX))

    plain_text = _padding(_unhex(''.join(plain_hex_list)),
                          mode=SM4_DECRYPT)
    return plain_text if PY2 else plain_text.decode(E_FMT)


# 密码块链接(CBC) 
Example 13
Project: django-oauth-toolkit-jwt   Author: Humanitec   File: utils.py    License: MIT License 6 votes vote down vote up
def decode_jwt(jwt_value):
    """
    :type jwt_value: str
    """
    try:
        headers_enc, payload_enc, verify_signature = jwt_value.split(".")
    except ValueError:
        raise jwt.InvalidTokenError()

    payload_enc += '=' * (-len(payload_enc) % 4)  # add padding
    payload = json.loads(base64.b64decode(payload_enc).decode("utf-8"))

    algorithms = getattr(settings, 'JWT_JWS_ALGORITHMS', ['HS256', 'RS256'])
    public_key_name = 'JWT_PUBLIC_KEY_{}'.format(payload['iss'].upper())
    public_key = getattr(settings, public_key_name, None)
    if not public_key:
        raise ImproperlyConfigured('Missing setting {}'.format(
                                   public_key_name))

    decoded = jwt.decode(jwt_value, public_key, algorithms=algorithms)
    return decoded 
Example 14
Project: sfdclib   Author: rbauction   File: metadata.py    License: MIT License 6 votes vote down vote up
def retrieve_zip(self, async_process_id):
        """ Retrieves ZIP file """
        result = self._retrieve_retrieve_result(async_process_id, 'true')
        state = result.find('mt:status', self._XML_NAMESPACES).text
        error_message = result.find('mt:errorMessage', self._XML_NAMESPACES)
        if error_message is not None:
            error_message = error_message.text

        # Check if there are any messages
        messages = []
        message_list = result.findall('mt:details/mt:messages', self._XML_NAMESPACES)
        for message in message_list:
            messages.append({
                'file': message.find('mt:fileName', self._XML_NAMESPACES).text,
                'message': message.find('mt:problem', self._XML_NAMESPACES).text
            })

        # Retrieve base64 encoded ZIP file
        zipfile_base64 = result.find('mt:zipFile', self._XML_NAMESPACES).text
        zipfile = b64decode(zipfile_base64)

        return state, error_message, messages, zipfile 
Example 15
Project: firefox_decrypt   Author: unode   File: firefox_decrypt.py    License: GNU General Public License v3.0 6 votes vote down vote up
def decode(self, data64):
        data = b64decode(data64)
        inp = self.SECItem(0, data, len(data))
        out = self.SECItem(0, None, 0)

        e = self._PK11SDR_Decrypt(inp, out, None)
        LOG.debug("Decryption of data returned %s", e)
        try:
            if e == -1:
                LOG.error("Password decryption failed. Passwords protected by a Master Password!")
                self.handle_error()
                raise Exit(Exit.NEED_MASTER_PASSWORD)

            res = ct.string_at(out.data, out.len).decode(LIB_ENCODING)
        finally:
            # Avoid leaking SECItem
            self._SECITEM_ZfreeItem(out, 0)

        return res 
Example 16
Project: cyberdisc-bot   Author: CyberDiscovery   File: constants.py    License: MIT License 5 votes vote down vote up
def getenv(name: str, fallback: str = "") -> str:
    """Return an (optionally base64-encoded) env var."""
    variable = environ.get(name)
    if DEPLOY and variable is not None:
        variable = base64.b64decode(variable).decode()
    return variable or fallback 
Example 17
Project: drydock   Author: airshipit   File: bootaction.py    License: Apache License 2.0 5 votes vote down vote up
def eval_base64_decode(self, data, ctx=None):
        """Decode data from base64.

        Light weight wrapper around base64 library to shed the ctx kwarg

        :param data: data to be decoded
        :param ctx: throwaway, just allows a generic interface for pipeline segments
        """
        return base64.b64decode(data) 
Example 18
Project: drydock   Author: airshipit   File: node_results.py    License: Apache License 2.0 5 votes vote down vote up
def get_decoded_data(self):
        """Decode the result data from base64."""
        try:
            return base64.b64decode(self.data)
        except binascii.Error:
            return None 
Example 19
Project: aegea   Author: kislyuk   File: lambda.py    License: Apache License 2.0 5 votes vote down vote up
def update_code(args):
    with open(args.zip_file, "rb") as fh:
        payload = fh.read()
    payload_sha = hashlib.sha256(payload).digest()
    res = getattr(clients, "lambda").update_function_code(FunctionName=args.function_name, ZipFile=payload)
    assert base64.b64decode(res["CodeSha256"]) == payload_sha
    return res 
Example 20
Project: wechatpy   Author: wechatpy   File: fields.py    License: MIT License 5 votes vote down vote up
def __base64_decode(self, text):
        return to_text(base64.b64decode(to_binary(text))) 
Example 21
Project: wechatpy   Author: wechatpy   File: __init__.py    License: MIT License 5 votes vote down vote up
def __init__(self, token, encoding_aes_key, _id):
        encoding_aes_key = to_binary(encoding_aes_key + "=")
        self.key = base64.b64decode(encoding_aes_key)
        assert len(self.key) == 32
        self.token = token
        self._id = _id 
Example 22
Project: wechatpy   Author: wechatpy   File: __init__.py    License: MIT License 5 votes vote down vote up
def __init__(self, key, iv, app_id):
        self.cipher = WeChatCipher(base64.b64decode(key), base64.b64decode(iv))
        self.app_id = app_id 
Example 23
Project: wechatpy   Author: wechatpy   File: __init__.py    License: MIT License 5 votes vote down vote up
def decrypt_message(self, msg):
        raw_data = base64.b64decode(msg)
        decrypted = self.cipher.decrypt(raw_data)
        plaintext = PKCS7Encoder.decode(decrypted)
        decrypted_msg = json.loads(to_text(plaintext))
        if decrypted_msg["watermark"]["appid"] != self.app_id:
            raise InvalidAppIdException()
        return decrypted_msg 
Example 24
Project: wechatpy   Author: wechatpy   File: base.py    License: MIT License 5 votes vote down vote up
def _decrypt(self, text, _id, exception=None):
        text = to_binary(text)
        plain_text = self.cipher.decrypt(base64.b64decode(text))
        padding = plain_text[-1]
        content = plain_text[16:-padding]
        xml_length = socket.ntohl(struct.unpack(b"I", content[:4])[0])
        xml_content = to_text(content[4 : xml_length + 4])
        from_id = to_text(content[xml_length + 4 :])
        if from_id != _id:
            exception = exception or Exception
            raise exception()
        return xml_content 
Example 25
Project: pywarp   Author: pyauth   File: metadata.py    License: Apache License 2.0 5 votes vote down vote up
def metadata_for_key_id(self, key_id):
        for e in self.metadata_toc["entries"]:
            if key_id in e.get("attestationCertificateKeyIdentifiers", []):
                break
        else:
            raise KeyError("No metadata found for key ID {}".format(key_id))
        res = requests.get(e["url"])
        res.raise_for_status()
        return json.loads(base64.b64decode(res.content).decode()) 
Example 26
Project: pywarp   Author: pyauth   File: __init__.py    License: Apache License 2.0 5 votes vote down vote up
def b64_decode(s):
    return base64.b64decode(s) 
Example 27
Project: pywarp   Author: pyauth   File: app.py    License: Apache License 2.0 5 votes vote down vote up
def register_credential():
    rp.rp_id = app.current_request.context["domainName"]
    req = {xform_name(f): base64.b64decode(app.current_request.json_body[f]) for f in app.current_request.json_body}
    print("registerCredential inputs:", req)
    return rp.register(**req) 
Example 28
Project: pywarp   Author: pyauth   File: app.py    License: Apache License 2.0 5 votes vote down vote up
def verify_assertion():
    rp.rp_id = app.current_request.context["domainName"]
    req = {xform_name(f): base64.b64decode(app.current_request.json_body[f]) for f in app.current_request.json_body}
    print("verifyAssertion inputs:", req)
    return rp.verify(**req) 
Example 29
Project: sawtooth-cookiejar   Author: danintel   File: cookiejar_client.py    License: Apache License 2.0 5 votes vote down vote up
def count(self):
        '''Count the number of cookies in the cookie jar.'''
        result = self._send_to_rest_api("state/{}".format(self._address))
        try:
            return base64.b64decode(yaml.safe_load(result)["data"])
        except BaseException:
            return None 
Example 30
Project: fishroom   Author: tuna   File: dumpload.py    License: GNU General Public License v3.0 5 votes vote down vote up
def load_meta(r, fromfile):
    with open(fromfile, 'r') as f:
        backup = json.load(f)

    for rk, b in backup.items():
        if rk == APIClientManager.clients_key:
            for token_id, b64token in b.items():
                r.hset(rk, token_id, base64.b64decode(b64token))
        elif isinstance(b, int):
            r.set(rk, b)
        elif isinstance(b, dict):
            for k, v in b.items():
                r.hset(rk, k, v) 
Example 31
Project: python-rest-api   Author: messagebird   File: signed_request.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def verify(self, signing_key):
        payload = self._build_payload()
        expected_signature = base64.b64decode(self._requestSignature)
        calculated_signature = hmac.new(signing_key.encode('latin-1'), payload.encode('latin-1'),
                                        hashlib.sha256).digest()
        return expected_signature == calculated_signature 
Example 32
Project: XFLTReaT   Author: earthquake   File: encoding.py    License: MIT License 5 votes vote down vote up
def decode(self, text):
		if len(text) % 4:
			text += "="*(4-(len(text)%4))
		return base64.b64decode(text.replace("-", "/").replace("_", "+")) 
Example 33
Project: XFLTReaT   Author: earthquake   File: encoding.py    License: MIT License 5 votes vote down vote up
def decode(self, text):
		if len(text) % 4:
			text += "="*(4-(len(text)%4))
		try:
			return base64.b64decode(text)
		except:
			return "" 
Example 34
Project: KDD2019-HandsOn-Tutorial   Author: graph-knowledgegraph   File: TutorialClasses.py    License: MIT License 5 votes vote down vote up
def Base64ToFloatArray(s, withMagnitudeColumn=True):
  arr = array.array('f', base64.b64decode(s))
  if withMagnitudeColumn:
    return (arr[0], arr[1:])
  else:
    return arr 
Example 35
Project: TradzQAI   Author: kkuette   File: cbpro_auth.py    License: Apache License 2.0 5 votes vote down vote up
def get_auth_headers(timestamp, message, api_key, secret_key, passphrase):
    message = message.encode('ascii')
    hmac_key = base64.b64decode(secret_key)
    signature = hmac.new(hmac_key, message, hashlib.sha256)
    signature_b64 = base64.b64encode(signature.digest()).decode('utf-8')
    return {
        'Content-Type': 'Application/JSON',
        'CB-ACCESS-SIGN': signature_b64,
        'CB-ACCESS-TIMESTAMP': timestamp,
        'CB-ACCESS-KEY': api_key,
        'CB-ACCESS-PASSPHRASE': passphrase
    } 
Example 36
Project: InsightAgent   Author: insightfinder   File: ifobfuscate.py    License: Apache License 2.0 5 votes vote down vote up
def decode(obfuscated):
    """ decode an obfuscated string """
    return base64.b64decode(obfuscated).decode('utf-8') 
Example 37
Project: InsightAgent   Author: insightfinder   File: ifobfuscate.py    License: Apache License 2.0 5 votes vote down vote up
def decode(obfuscated):
    """ decode an obfuscated string """
    return base64.b64decode(obfuscated).decode('utf-8') 
Example 38
Project: InsightAgent   Author: insightfinder   File: ifobfuscate.py    License: Apache License 2.0 5 votes vote down vote up
def decode(obfuscated):
    """ decode an obfuscated string """
    return base64.b64decode(obfuscated).decode('utf-8') 
Example 39
Project: InsightAgent   Author: insightfinder   File: ifobfuscate.py    License: Apache License 2.0 5 votes vote down vote up
def decode(obfuscated):
    """ decode an obfuscated string """
    return base64.b64decode(obfuscated).decode('utf-8') 
Example 40
Project: controller   Author: deis   File: utils.py    License: MIT License 5 votes vote down vote up
def fingerprint(key):
    """
    Return the fingerprint for an SSH Public Key
    """
    key = base64.b64decode(key.strip().split()[1].encode('ascii'))
    fp_plain = hashlib.md5(key).hexdigest()
    return ':'.join(a + b for a, b in zip(fp_plain[::2], fp_plain[1::2]))