Python base64.b64encode() Examples

The following are 30 code examples for showing how to use base64.b64encode(). 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 check out the related API usage on the sidebar.

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

Example 1
Project: wechatpy   Author: wechatpy   File: utils.py    License: 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 2
Project: aegea   Author: kislyuk   File: ssh.py    License: 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 3
Project: aegea   Author: kislyuk   File: build_docker_image.py    License: 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 4
Project: aegea   Author: kislyuk   File: efs.py    License: 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 5
Project: wechatpy   Author: wechatpy   File: device.py    License: 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 6
Project: wechatpy   Author: wechatpy   File: device.py    License: 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 7
Project: dustmaps   Author: gregreen   File: json_serializers.py    License: 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 8
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 9
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_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
Project: controller   Author: deis   File: test_app.py    License: 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 11
Project: Paradrop   Author: ParadropLabs   File: downloader.py    License: 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 12
Project: Paradrop   Author: ParadropLabs   File: downloader.py    License: 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 13
Project: Paradrop   Author: ParadropLabs   File: camera.py    License: 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 14
Project: fine-lm   Author: akzaidi   File: serving_utils.py    License: MIT License 6 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 15
Project: ipygee   Author: fitoprincipe   File: chart.py    License: MIT License 6 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 16
Project: pysm4   Author: yang3yen   File: sm4.py    License: 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
Project: glazier   Author: google   File: beyondcorp.py    License: 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
Project: TaskBot   Author: EvilPsyCHo   File: WXBizMsgCrypt_py3.py    License: GNU General Public License v3.0 6 votes vote down vote up
def encrypt(self, text, appid):
        """对明文进行加密
        @param text: 需要加密的明文
        @return: 加密得到的字符串
        """
        # 16位随机字符串添加到明文开头
        len_str = struct.pack("I", socket.htonl(len(text.encode())))
        # text = self.get_random_str() + binascii.b2a_hex(len_str).decode() + text + appid
        text = self.get_random_str() + len_str + text.encode() + appid
        # 使用自定义的填充方式对明文进行补位填充
        pkcs7 = PKCS7Encoder()
        text = pkcs7.encode(text)
        # 加密
        cryptor = AES.new(self.key, self.mode, self.key[:16])
        try:
            ciphertext = cryptor.encrypt(text)
            # 使用BASE64对加密后的字符串进行编码
            return ierror.WXBizMsgCrypt_OK, base64.b64encode(ciphertext).decode('utf8')
        except Exception as e:
            return ierror.WXBizMsgCrypt_EncryptAES_Error, None 
Example 19
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def to_json(self):
        safe_fields = {}
        safe_fields["matrix"] = [str(self.matrix.dtype), base64.b64encode(self.matrix.A).decode('utf-8'), self.matrix.shape]
        
        return safe_fields 
Example 20
Project: indras_net   Author: gcallah   File: vector_space.py    License: GNU General Public License v3.0 5 votes vote down vote up
def to_json(self):
        safe_fields = {}
        safe_fields["vector"] = [str(self.vector.dtype), base64.b64encode(self.vector).decode('utf-8')]
        
        return safe_fields 
Example 21
Project: indras_net   Author: gcallah   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def run(request):
    """
        This runs the model that was picked.
    """
    env = None
    try:
        action = request.POST[ACTION]
    except KeyError:
        action = None

    session_id = int(request.session['session_id'])

    # Load entry_point
    model_name = request.POST[MODEL]
    model = ABMModel.objects.get(name=model_name)
    entry_point = model.module
    plot_type = model.plot_type
    importlib.import_module(entry_point[0:-4])

    questions = model.params.all()

    # Take actions on a running model
    if action:
        env = running_model(request, action, entry_point,
                            questions, session_id)
    # Run a model for the first time
    else:
        env = model_first_run(request, action, entry_point, questions,
                              session_id, plot_type)

    site_hdr = get_hdr()

    text_box, image_bytes = env.user.text_output, env.plot()
    image = base64.b64encode(image_bytes.getvalue()).decode()

    template_data = {HEADER: site_hdr, 'text0': text_box[0], 'image': image,
                     'text1': text_box[1], 'model': model}

    return render(request, 'run.html', template_data) 
Example 22
Project: jumpserver-python-sdk   Author: jumpserver   File: utils.py    License: GNU General Public License v2.0 5 votes vote down vote up
def content_md5(data):
    """计算data的MD5值,经过Base64编码并返回str类型。

    返回值可以直接作为HTTP Content-Type头部的值
    """
    if isinstance(data, str):
        data = hashlib.md5(data.encode('utf-8'))
    value = base64.b64encode(data.hexdigest().encode('utf-8'))
    return value.decode('utf-8') 
Example 23
Project: hydrus   Author: HTTP-APIs   File: user.py    License: MIT License 5 votes vote down vote up
def generate_basic_digest(id_: int, paraphrase: str) -> str:
    """Create the digest to be added to the HTTP Authorization header."""
    paraphrase_digest = sha224(paraphrase.encode('utf-8')).hexdigest()
    credentials = '{}:{}'.format(id_, paraphrase_digest)
    digest = base64.b64encode(credentials.encode('utf-8')).decode('utf-8')
    return digest 
Example 24
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    License: MIT License 5 votes vote down vote up
def _isAsthamaPump(self, imageWidth, imageHeight, imageString):
        result = {}
        coordinates = {}
        metadata = {}
        isPresent = False

        try :
            self._printLogs("Sending Image To DL Server...", "NORMAL")

            url = DL_SERVER_URL
            payload = {
                        "imageWidth"   : imageWidth,
                        "imageHeight"  : imageHeight,
                        "image_string" : base64.b64encode(imageString),
                        "imageID"      : self.imageNo2d
                        }
            headers = {'content-type': 'application/json'}

            res = requests.post(url, data=json.dumps(payload), headers=headers)
            result = res.json()
            self._printLogs("[*] Sent to  : " + str(url), "OKBLUE")
            self._printLogs("[*] Response : " + str(result), "OKBLUE")

        except Exception, err:
            self._printLogs("Error Found on connecting to server : " + str(err), "FAIL")
            self._printLogs("+", "LINE") 
Example 25
Project: drydock   Author: airshipit   File: bootaction.py    License: Apache License 2.0 5 votes vote down vote up
def eval_base64_encode(self, data, ctx=None):
        """Encode data as base64.

        Light weight wrapper around base64 library to shed the ctx kwarg

        :param data: data to be encoded
        :param ctx: throwaway, just allows a generic interface for pipeline segments
        """
        return base64.b64encode(data) 
Example 26
Project: drydock   Author: airshipit   File: machine.py    License: Apache License 2.0 5 votes vote down vote up
def deploy(self, user_data=None, platform=None, kernel=None):
        """Start the MaaS deployment process.

        :param user_data: ``str`` of cloud-init user data
        :param platform: Which image to install
        :param kernel: Which kernel to enable
        """
        deploy_options = {}

        if user_data is not None:
            deploy_options['user_data'] = base64.b64encode(
                user_data.encode('utf-8')).decode('utf-8')

        if platform is not None:
            deploy_options['distro_series'] = platform

        if kernel is not None:
            deploy_options['hwe_kernel'] = kernel

        url = self.interpolate_url()
        resp = self.api_client.post(
            url,
            op='deploy',
            files=deploy_options if len(deploy_options) > 0 else None)

        if not resp.ok:
            self.logger.error(
                "Error deploying node, received HTTP %s from MaaS" %
                resp.status_code)
            self.logger.debug("MaaS response: %s" % resp.text)
            raise errors.DriverError(
                "Error deploying node, received HTTP %s from MaaS" %
                resp.status_code) 
Example 27
Project: drydock   Author: airshipit   File: test_bootaction_pipeline.py    License: Apache License 2.0 5 votes vote down vote up
def test_bootaction_pipeline_base64(self):
        objects.register_all()

        ba = objects.BootActionAsset()

        orig = 'Test 1 2 3!'.encode('utf-8')
        expected_value = base64.b64encode(orig)

        test_value = ba.execute_pipeline(orig, ['base64_encode'])

        assert expected_value == test_value 
Example 28
Project: drydock   Author: airshipit   File: test_reference_resolver.py    License: Apache License 2.0 5 votes vote down vote up
def test_resolve_http_basicauth_url(self):
        """Test the resolver will resolve http URLs w/ basic auth."""
        url = 'http://user:pass@foo.com/test.yaml'
        auth_header = "Basic %s" % base64.b64encode(
            "user:pass".encode('utf-8')).decode('utf-8')
        responses.add(responses.GET, url)

        ReferenceResolver.resolve_reference(url)

        assert len(responses.calls) == 1
        assert 'Authorization' in responses.calls[0].request.headers
        assert responses.calls[0].request.headers.get(
            'Authorization') == auth_header 
Example 29
Project: aegea   Author: kislyuk   File: repo.py    License: Apache License 2.0 5 votes vote down vote up
def create_file(self, path, message, content, branch=None,
                    committer=None, author=None):
        """Create a file in this repository.

        See also: http://developer.github.com/v3/repos/contents/#create-a-file

        :param str path: (required), path of the file in the repository
        :param str message: (required), commit message
        :param bytes content: (required), the actual data in the file
        :param str branch: (optional), branch to create the commit on.
            Defaults to the default branch of the repository
        :param dict committer: (optional), if no information is given the
            authenticated user's information will be used. You must specify
            both a name and email.
        :param dict author: (optional), if omitted this will be filled in with
            committer information. If passed, you must specify both a name and
            email.
        :returns: {
            'content': :class:`Contents <github3.repos.contents.Contents>`:,
            'commit': :class:`Commit <github3.git.Commit>`}

        """
        if content and not isinstance(content, bytes):
            raise ValueError(  # (No coverage)
                'content must be a bytes object')  # (No coverage)

        json = None
        if path and message and content:
            url = self._build_url('contents', path, base_url=self._api)
            content = b64encode(content).decode('utf-8')
            data = {'message': message, 'content': content, 'branch': branch,
                    'committer': validate_commmitter(committer),
                    'author': validate_commmitter(author)}
            self._remove_none(data)
            json = self._json(self._put(url, data=dumps(data)), 201)
            if 'content' in json and 'commit' in json:
                json['content'] = Contents(json['content'], self)
                json['commit'] = Commit(json['commit'], self)
        return json 
Example 30
Project: aegea   Author: kislyuk   File: repo.py    License: Apache License 2.0 5 votes vote down vote up
def update_file(self, path, message, content, sha, branch=None,
                    author=None, committer=None):
        """Update the file ``path`` with ``content``.

        This is part of the Contents CrUD (Create Update Delete) API. See
        http://developer.github.com/v3/repos/contents/#update-a-file for more
        information.

        :param str path: (required), path to the file being updated
        :param str message: (required), commit message
        :param str content: (required), updated contents of the file
        :param str sha: (required), blob sha of the file being updated
        :param str branch: (optional), uses the default branch on the
            repository if not provided.
        :param dict author: (optional), if omitted this will be filled in with
            committer information. If passed, you must specify both a name and
            email.
        :returns: {'commit': :class:`Commit <github3.git.Commit>`,
            'content': :class:`Contents <github3.repos.contents.Contents>`}

        """
        if content and not isinstance(content, bytes):
            raise ValueError(  # (No coverage)
                'content must be a bytes object')  # (No coverage)

        json = None
        if path and message and content and sha:
            url = self._build_url('contents', path, base_url=self._api)
            content = b64encode(content).decode('utf-8')
            data = {'message': message, 'content': content, 'sha': sha,
                    'committer': validate_commmitter(committer),
                    'author': validate_commmitter(author),
                    'branch': branch}
            self._remove_none(data)
            json = self._json(self._put(url, data=dumps(data)), 200)
            if 'content' in json and 'commit' in json:
                json['content'] = Contents(json['content'], self)
                json['commit'] = Commit(json['commit'], self)
        return json