Python base64.b64encode() Examples

The following are 30 code examples of base64.b64encode(). 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 also want to check out all available functions/classes of the module base64 , or try the search function .
Example #1
Source File: chart.py    From ipygee with MIT License 8 votes vote down vote up
def renderWidget(chart, width=None, height=None):
    """ Render a pygal chart into a Jupyter Notebook """
    from ipywidgets import HTML

    b64 = base64.b64encode(chart.render()).decode('utf-8')

    src = 'data:image/svg+xml;charset=utf-8;base64,'+b64

    if width and not height:
        html = '<embed src={} width={}></embed>'.format(src, width)
    elif height and not width:
        html = '<embed src={} height={}></embed>'.format(src, height)
    elif width and height:
        html = '<embed src={} height={} width={}></embed>'.format(src,
                                                                  height,
                                                                  width)
    else:
        html = '<embed src={}>'.format(src)

    return HTML(html) 
Example #2
Source File: utils.py    From wechatpy with MIT License 7 votes vote down vote up
def rsa_encrypt(data, pem, b64_encode=True):
    """
    rsa 加密
    :param data: 待加密字符串/binary
    :param pem: RSA public key 内容/binary
    :param b64_encode: 是否对输出进行 base64 encode
    :return: 如果 b64_encode=True 的话,返回加密并 base64 处理后的 string;否则返回加密后的 binary
    """
    from cryptography.hazmat.backends import default_backend
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives import hashes
    from cryptography.hazmat.primitives.asymmetric import padding

    encoded_data = to_binary(data)
    pem = to_binary(pem)
    public_key = serialization.load_pem_public_key(pem, backend=default_backend())
    encrypted_data = public_key.encrypt(
        encoded_data, padding=padding.OAEP(mgf=padding.MGF1(hashes.SHA1()), algorithm=hashes.SHA1(), label=None,),
    )
    if b64_encode:
        encrypted_data = base64.b64encode(encrypted_data).decode("utf-8")
    return encrypted_data 
Example #3
Source File: serving_utils.py    From fine-lm with MIT License 7 votes vote down vote up
def make_cloud_mlengine_request_fn(credentials, model_name, version):
  """Wraps function to make CloudML Engine requests with runtime args."""

  def _make_cloud_mlengine_request(examples):
    """Builds and sends requests to Cloud ML Engine."""
    api = discovery.build("ml", "v1", credentials=credentials)
    parent = "projects/%s/models/%s/versions/%s" % (cloud.default_project(),
                                                    model_name, version)
    input_data = {
        "instances": [{
            "input": {
                "b64": base64.b64encode(ex.SerializeToString())
            }
        } for ex in examples]
    }
    prediction = api.projects().predict(body=input_data, name=parent).execute()
    return prediction["predictions"]

  return _make_cloud_mlengine_request 
Example #4
Source File: downloader.py    From Paradrop with Apache License 2.0 7 votes vote down vote up
def _create_curl_conn(self, url):
        """
        Create a cURL connection object with useful default settings.
        """
        headers = []
        if self.user is not None and self.secret is not None:
            b64cred = base64.b64encode("{}:{}".format(self.user, self.secret))
            headers.append("Authorization: Basic {}".format(b64cred))

        conn = pycurl.Curl()

        if len(headers) > 0:
            conn.setopt(pycurl.HTTPHEADER, headers)

        conn.setopt(pycurl.URL, url)

        # github often redirects
        conn.setopt(pycurl.FOLLOWLOCATION, 1)

        return conn 
Example #5
Source File: device.py    From wechatpy with MIT License 6 votes vote down vote up
def get_qrcode_url(self, ticket, data=None):
        """
        通过 ticket 换取二维码地址
        详情请参考
        https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4

        :param ticket: 二维码 ticket
        :param data: 额外数据
        :return: 二维码地址
        """
        url = f"https://we.qq.com/d/{ticket}"
        if data:
            if isinstance(data, (dict, tuple, list)):
                data = urllib.urlencode(data)
            data = to_text(base64.b64encode(to_binary(data)))
            url = f"{url}#{data}"
        return url 
Example #6
Source File: efs.py    From aegea with Apache License 2.0 6 votes vote down vote up
def create(args):
    vpc = ensure_vpc()
    if args.security_groups is None:
        args.security_groups = [__name__]
        ensure_security_group(__name__, vpc, tcp_ingress=[dict(port=socket.getservbyname("nfs"),
                                                               source_security_group_name=__name__)])
    creation_token = base64.b64encode(bytearray(os.urandom(24))).decode()
    args.tags.append("Name=" + args.name)
    create_file_system_args = dict(CreationToken=creation_token,
                                   PerformanceMode=args.performance_mode,
                                   ThroughputMode=args.throughput_mode,
                                   Tags=encode_tags(args.tags))
    if args.throughput_mode == "provisioned":
        create_file_system_args.update(ProvisionedThroughputInMibps=args.provisioned_throughput_in_mibps)
    fs = clients.efs.create_file_system(**create_file_system_args)
    waiter = make_waiter(clients.efs.describe_file_systems, "FileSystems[].LifeCycleState", "available", "pathAny")
    waiter.wait(FileSystemId=fs["FileSystemId"])
    security_groups = [resolve_security_group(g, vpc).id for g in args.security_groups]
    for subnet in vpc.subnets.all():
        clients.efs.create_mount_target(FileSystemId=fs["FileSystemId"],
                                        SubnetId=subnet.id,
                                        SecurityGroups=security_groups)
    return fs 
Example #7
Source File: bwh_ctr.py    From BandwagongVPS_controller with 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 #8
Source File: build_docker_image.py    From aegea with Apache License 2.0 6 votes vote down vote up
def get_dockerfile(args):
    if args.dockerfile:
        return io.open(args.dockerfile, "rb").read()
    else:
        cmd = bash_cmd_preamble + [
            "apt-get update -qq",
            "apt-get install -qqy cloud-init net-tools",
            "echo $CLOUD_CONFIG_B64 | base64 --decode > /etc/cloud/cloud.cfg.d/99_aegea.cfg",
            "cloud-init init",
            "cloud-init modules --mode=config",
            "cloud-init modules --mode=final"
        ]
        return dockerfile.format(base_image=args.base_image,
                                 maintainer=ARN.get_iam_username(),
                                 label=" ".join(args.tags),
                                 cloud_config_b64=base64.b64encode(get_cloud_config(args)).decode(),
                                 run=json.dumps(cmd)).encode() 
Example #9
Source File: bwh_ctr.py    From BandwagongVPS_controller with GNU General Public License v3.0 6 votes vote down vote up
def dual_host_select_event(self):
        num = 0
        with open(".\data.ini",'rb') as f:
            self.tmp_data = f.readlines()
        with open(".\data.ini",'wb') as f:
            for x in self.tmp_data:
                if not len(x.strip()):
                    pass
                if num == 0:
                    f.write(base64.b64encode(str(self.dual_host_view.currentRow()+1).encode()))
                    f.write('\n'.encode())
                else:
                    f.write(x)
                num += 1

        a = QMessageBox()
        #写入成功提示
        a.information(a,self.tr("Success"),self.tr("host will be changed after resrart the application")) 
Example #10
Source File: camera.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def get_image(self):
        """
        Get an image from the camera.

        Returns image data as a BytesIO object.
        """
        url = "http://{}/image.jpg".format(self.host)

        encoded = base64.b64encode('admin:'.encode('utf-8')).decode('ascii')

        headers = {
            'Authorization': 'Basic ' + encoded
        }

        result = requests.get(url, headers=headers)
        if result.ok:
            return BytesIO(result.content)

        else:
            return None 
Example #11
Source File: test_app.py    From controller with MIT License 6 votes vote down vote up
def test_get_private_registry_config(self, mock_requests):
        registry = {'username': 'test', 'password': 'test'}
        auth = bytes('{}:{}'.format("test", "test"), 'UTF-8')
        encAuth = base64.b64encode(auth).decode(encoding='UTF-8')
        image = 'test/test'

        docker_config, name, create = App()._get_private_registry_config(image, registry)
        dockerConfig = json.loads(docker_config)
        expected = {"https://index.docker.io/v1/": {"auth": encAuth}}
        self.assertEqual(dockerConfig.get('auths'), expected)
        self.assertEqual(name, "private-registry")
        self.assertEqual(create, True)

        image = "quay.io/test/test"
        docker_config, name, create = App()._get_private_registry_config(image, registry)
        dockerConfig = json.loads(docker_config)
        expected = {"quay.io": {"auth": encAuth}}
        self.assertEqual(dockerConfig.get('auths'), expected)
        self.assertEqual(name, "private-registry")
        self.assertEqual(create, True) 
Example #12
Source File: ssh.py    From aegea with Apache License 2.0 6 votes vote down vote up
def get_kms_auth_token(session, bless_config, lambda_regional_config):
    logger.info("Requesting new KMS auth token in %s", lambda_regional_config["aws_region"])
    token_not_before = datetime.datetime.utcnow() - datetime.timedelta(minutes=1)
    token_not_after = token_not_before + datetime.timedelta(hours=1)
    token = dict(not_before=token_not_before.strftime("%Y%m%dT%H%M%SZ"),
                 not_after=token_not_after.strftime("%Y%m%dT%H%M%SZ"))
    encryption_context = {
        "from": session.resource("iam").CurrentUser().user_name,
        "to": bless_config["lambda_config"]["function_name"],
        "user_type": "user"
    }
    kms = session.client('kms', region_name=lambda_regional_config["aws_region"])
    res = kms.encrypt(KeyId=lambda_regional_config["kms_auth_key_id"],
                      Plaintext=json.dumps(token),
                      EncryptionContext=encryption_context)
    return base64.b64encode(res["CiphertextBlob"]).decode() 
Example #13
Source File: device.py    From wechatpy with MIT License 6 votes vote down vote up
def send_message(self, device_type, device_id, user_id, content):
        """
        主动发送消息给设备
        详情请参考
        https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-3

        :param device_type: 设备类型,目前为“公众账号原始ID”
        :param device_id: 设备ID
        :param user_id: 微信用户账号的openid
        :param content: 消息内容,BASE64编码
        :return: 返回的 JSON 数据包
        """
        content = to_text(base64.b64encode(to_binary(content)))
        return self._post(
            "transmsg",
            data={"device_type": device_type, "device_id": device_id, "open_id": user_id, "content": content,},
        ) 
Example #14
Source File: json_serializers.py    From dustmaps with GNU General Public License v2.0 6 votes vote down vote up
def serialize_ndarray_b64(o):
    """
    Serializes a :obj:`numpy.ndarray` in a format where the datatype and shape are
    human-readable, but the array data itself is binary64 encoded.

    Args:
        o (:obj:`numpy.ndarray`): :obj:`ndarray` to be serialized.

    Returns:
        A dictionary that can be passed to :obj:`json.dumps`.
    """
    if o.flags['C_CONTIGUOUS']:
        o_data = o.data
    else:
        o_data = np.ascontiguousarray(o).data
    data_b64 = base64.b64encode(o_data)
    return dict(
        _type='np.ndarray',
        data=data_b64.decode('utf-8'),
        dtype=o.dtype,
        shape=o.shape) 
Example #15
Source File: downloader.py    From Paradrop with Apache License 2.0 6 votes vote down vote up
def _create_curl_conn(self, url):
        """
        Create a cURL connection object with useful default settings.
        """
        headers = []
        if self.user is not None and self.secret is not None:
            b64cred = base64.b64encode("{}:{}".format(self.user, self.secret))
            headers.append("Authorization: Basic {}".format(b64cred))

        conn = pycurl.Curl()

        if len(headers) > 0:
            conn.setopt(pycurl.HTTPHEADER, headers)

        conn.setopt(pycurl.URL, url)

        # github often redirects
        conn.setopt(pycurl.FOLLOWLOCATION, 1)

        return conn 
Example #16
Source File: sm4.py    From pysm4 with MIT License 6 votes vote down vote up
def encrypt_ecb(plain_text, key):
    """
    SM4(ECB)加密
    :param plain_text: 明文
    :param key: 密钥, 小于等于16字节
    """
    plain_text = _padding(plain_text, mode=SM4_ENCRYPT)
    if plain_text is None:
        return

    # 密钥检验
    key = _key_iv_check(key_iv=key)

    plain_hex = _hex(plain_text)
    cipher_hex_list = []
    for i in _range(len(plain_text) // BLOCK_BYTE):
        sub_hex = plain_hex[i * BLOCK_HEX:(i + 1) * BLOCK_HEX]
        cipher = encrypt(clear_num=int(sub_hex, 16),
                         mk=int(_hex(key), 16))
        cipher_hex_list.append(num2hex(num=cipher, width=BLOCK_HEX))

    cipher_text = b64encode(_unhex(''.join(cipher_hex_list)))
    return cipher_text if PY2 else cipher_text.decode(E_FMT) 
Example #17
Source File: beyondcorp.py    From glazier with Apache License 2.0 6 votes vote down vote up
def _GetHash(self, file_path: Text) -> bytes:
    """Calculates the hash of the boot wim.

    Args:
      file_path: path to the file to be hashed

    Returns:
      hash of boot wim in hex
    """
    block_size = 33554432  # define bytes to read at a time when hashing (32mb)
    hasher = hashlib.sha256()

    with open(file_path, 'rb') as f:
      fb = f.read(block_size)
      while fb:
        hasher.update(fb)
        fb = f.read(block_size)
    return base64.b64encode(hasher.digest()) 
Example #18
Source File: push.py    From operator-courier with Apache License 2.0 5 votes vote down vote up
def _create_base64_bundle(self, bundle_dir, repository):
        with TemporaryDirectory() as temp_dir:
            tarfile_name = os.path.join(temp_dir, "%s.tar.gz" % repository)
            with tarfile.open(tarfile_name, "w:gz") as tar:
                tar.add(bundle_dir, os.path.basename(bundle_dir))
            with open(tarfile_name, "rb") as tarball:
                result = tarball.read()
            result64 = base64.b64encode(result).decode("utf-8")
            return result64 
Example #19
Source File: secret.py    From controller with MIT License 5 votes vote down vote up
def manifest(self, namespace, name, data, secret_type='Opaque', labels={}):
        secret_types = ['Opaque', 'kubernetes.io/dockerconfigjson']
        if secret_type not in secret_types:
            raise KubeException('{} is not a supported secret type. Use one of the following: '.format(secret_type, ', '.join(secret_types)))  # noqa

        manifest = {
            'kind': 'Secret',
            'apiVersion': 'v1',
            'metadata': {
                'name': name,
                'namespace': namespace,
                'labels': {
                    'app': namespace,
                    'heritage': 'deis'
                }
            },
            'type': secret_type,
            'data': {}
        }

        # add in any additional label info
        manifest['metadata']['labels'].update(labels)

        for key, value in data.items():
            if value is None:
                manifest['data'].update({key: ''})
                continue

            value = value if isinstance(value, bytes) else bytes(str(value), 'UTF-8')
            item = base64.b64encode(value).decode(encoding='UTF-8')
            manifest['data'].update({key: item})

        return manifest 
Example #20
Source File: bot_framework_adapter.py    From botbuilder-python with MIT License 5 votes vote down vote up
def get_oauth_sign_in_link(
        self,
        context: TurnContext,
        connection_name: str,
        final_redirect: str = None,  # pylint: disable=unused-argument
        oauth_app_credentials: AppCredentials = None,
    ) -> str:
        """
        Gets the raw sign-in link to be sent to the user for sign-in for a connection name.

        :param context: Context for the current turn of conversation with the user
        :type context: :class:`botbuilder.core.TurnContext`
        :param connection_name: Name of the auth connection to use
        :type connection_name: str
        :param final_redirect: The final URL that the OAuth flow will redirect to.
        :param oauth_app_credentials: (Optional) AppCredentials for OAuth.
        :type oauth_app_credentials: :class:`botframework.connector.auth.AppCredential`

        :return: If the task completes successfully, the result contains the raw sign-in link
        """

        client = await self._create_token_api_client(context, oauth_app_credentials)

        conversation = TurnContext.get_conversation_reference(context.activity)
        state = TokenExchangeState(
            connection_name=connection_name,
            conversation=conversation,
            ms_app_id=client.config.credentials.microsoft_app_id,
            relates_to=context.activity.relates_to,
        )

        final_state = base64.b64encode(
            json.dumps(state.serialize()).encode(encoding="UTF-8", errors="strict")
        ).decode()

        return client.bot_sign_in.get_sign_in_url(final_state) 
Example #21
Source File: twt_img.py    From twitter-image-downloader with MIT License 5 votes vote down vote up
def bearer(self, key, secret):
        """Download the bearer token and return it.

        Args:
            key: API key.
            secret: API string.
        """

        # setup
        credential = base64.b64encode(
            bytes(f"{key}:{secret}", "utf-8")
        ).decode()
        url = "https://api.twitter.com/oauth2/token"
        headers = {
            "Authorization": f"Basic {credential}",
            "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
        }
        payload = {"grant_type": "client_credentials"}

        # post the request
        r = requests.post(url, headers=headers, params=payload)

        # check the response
        if r.status_code == 200:
            return r.json()["access_token"]
        else:
            raise e.BearerTokenNotFetchedError() 
Example #22
Source File: test_app.py    From controller with MIT License 5 votes vote down vote up
def test_get_private_registry_config_off_cluster(self, mock_requests):
        registry = {}
        auth = bytes('{}:{}'.format("test", "test"), 'UTF-8')
        encAuth = base64.b64encode(auth).decode(encoding='UTF-8')
        image = "test.com/test/test"
        docker_config, name, create = App()._get_private_registry_config(image, registry)
        dockerConfig = json.loads(docker_config)
        expected = {"https://index.docker.io/v1/": {
            "auth": encAuth
        }}
        self.assertEqual(dockerConfig.get('auths'), expected)
        self.assertEqual(name, "private-registry-off-cluster")
        self.assertEqual(create, True) 
Example #23
Source File: app.py    From controller with MIT License 5 votes vote down vote up
def _get_private_registry_config(self, image, registry=None):
        name = settings.REGISTRY_SECRET_PREFIX
        if registry:
            # try to get the hostname information
            hostname = registry.get('hostname', None)
            if not hostname:
                hostname, _ = docker_auth.split_repo_name(image)

            if hostname == docker_auth.INDEX_NAME:
                hostname = 'https://index.docker.io/v1/'

            username = registry.get('username')
            password = registry.get('password')
        elif settings.REGISTRY_LOCATION == 'off-cluster':
            secret = self._scheduler.secret.get(
                settings.WORKFLOW_NAMESPACE, 'registry-secret').json()
            username = secret['data']['username']
            password = secret['data']['password']
            hostname = secret['data']['hostname']
            if hostname == '':
                hostname = 'https://index.docker.io/v1/'
            name = name + '-' + settings.REGISTRY_LOCATION
        elif settings.REGISTRY_LOCATION in ['ecr', 'gcr']:
            return None, name + '-' + settings.REGISTRY_LOCATION, False
        else:
            return None, None, None

        # create / update private registry secret
        auth = bytes('{}:{}'.format(username, password), 'UTF-8')
        # value has to be a base64 encoded JSON
        docker_config = json.dumps({
            'auths': {
                hostname: {
                    'auth': base64.b64encode(auth).decode(encoding='UTF-8')
                }
            }
        })
        return docker_config, name, True 
Example #24
Source File: ifobfuscate.py    From InsightAgent with Apache License 2.0 5 votes vote down vote up
def obfuscate(to_obfuscate):
    """ obfuscate a string """
    try:
        return base64.b64encode(to_obfuscate).decode('utf-8')
    except Exception:
        return base64.b64encode(to_obfuscate.encode('utf-8')).decode('utf-8') 
Example #25
Source File: ifobfuscate.py    From InsightAgent with Apache License 2.0 5 votes vote down vote up
def obfuscate(to_obfuscate):
    """ obfuscate a string """
    try:
        return base64.b64encode(to_obfuscate).decode('utf-8')
    except Exception:
        return base64.b64encode(to_obfuscate.encode('utf-8')).decode('utf-8') 
Example #26
Source File: ifobfuscate.py    From InsightAgent with Apache License 2.0 5 votes vote down vote up
def obfuscate(to_obfuscate):
    """ obfuscate a string """
    try:
        return base64.b64encode(to_obfuscate).decode('utf-8')
    except Exception:
        return base64.b64encode(to_obfuscate.encode('utf-8')).decode('utf-8') 
Example #27
Source File: ifobfuscate.py    From InsightAgent with Apache License 2.0 5 votes vote down vote up
def obfuscate(to_obfuscate):
    """ obfuscate a string """
    try:
        return base64.b64encode(to_obfuscate).decode('utf-8')
    except Exception:
        return base64.b64encode(to_obfuscate.encode('utf-8')).decode('utf-8') 
Example #28
Source File: arya.py    From Arya with GNU General Public License v3.0 5 votes vote down vote up
def b64sub(s, key):
    """
    "Encryption" method that base64 encodes a given string, 
    then does a randomized alphabetic letter substitution.
    """
    enc_tbl = string.maketrans(string.ascii_letters, key)
    return string.translate(base64.b64encode(s), enc_tbl) 
Example #29
Source File: cbpro_auth.py    From TradzQAI with 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 #30
Source File: encoding.py    From XFLTReaT with MIT License 5 votes vote down vote up
def encode(self, text):
		return base64.b64encode(text).replace("=","")