Python base64.encodestring() Examples

The following are 30 code examples of base64.encodestring(). 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: Kubernetes.py    From im with GNU General Public License v3.0 6 votes vote down vote up
def get_auth_header(self, auth_data):
        """
        Generate the auth header needed to contact with the Kubernetes API server.
        """
        url = urlparse(self.cloud.server)
        auths = auth_data.getAuthInfo(self.type, url[1])
        if not auths:
            self.log_error(
                "No correct auth data has been specified to Kubernetes.")
            return None
        else:
            auth = auths[0]

        auth_header = None

        if 'username' in auth and 'password' in auth:
            passwd = auth['password']
            user = auth['username']
            auth_header = {'Authorization': 'Basic ' +
                           (base64.encodestring((user + ':' + passwd).encode('utf-8'))).strip().decode('utf-8')}
        elif 'token' in auth:
            token = auth['token']
            auth_header = {'Authorization': 'Bearer ' + token}

        return auth_header 
Example #2
Source File: gifti.py    From me-ica with GNU Lesser General Public License v2.1 6 votes vote down vote up
def data_tag(dataarray, encoding, datatype, ordering):
    """ Creates the data tag depending on the required encoding """
    import base64
    import zlib
    ord = array_index_order_codes.npcode[ordering]
    enclabel = gifti_encoding_codes.label[encoding]
    if enclabel == 'ASCII':
        c = BytesIO()
        # np.savetxt(c, dataarray, format, delimiter for columns)
        np.savetxt(c, dataarray, datatype, ' ')
        c.seek(0)
        da = c.read()
    elif enclabel == 'B64BIN':
        da = base64.encodestring(dataarray.tostring(ord))
    elif enclabel == 'B64GZ':
        # first compress
        comp = zlib.compress(dataarray.tostring(ord))
        da = base64.encodestring(comp)
        da = da.decode()
    elif enclabel == 'External':
        raise NotImplementedError("In what format are the external files?")
    else:
        da = ''
    return "<Data>"+da+"</Data>\n" 
Example #3
Source File: metadata.py    From awesome-scala with Apache License 2.0 6 votes vote down vote up
def query(owner, name):
    if fake:
        print("    {0}/{1}: ok".format(owner, name))
        return (random.randint(1, 1000), random.randint(1, 300))
    else:
        try:
            req = urllib2.Request(
                "https://api.github.com/repos/{0}/{1}".format(owner, name)
            )
            if user is not None and token is not None:
                b64 = base64.encodestring("{0}:{1}".format(user, token)).replace(
                    "\n", ""
                )
                req.add_header("Authorization", "Basic {0}".format(b64))
            u = urllib2.urlopen(req)
            j = json.load(u)
            t = datetime.datetime.strptime(j["updated_at"], "%Y-%m-%dT%H:%M:%SZ")
            days = max(int((now - t).days), 0)
            print("    {0}/{1}: ok".format(owner, name))
            return (int(j["stargazers_count"]), days)
        except urllib2.HTTPError as e:
            print("    {0}/{1}: FAILED".format(owner, name))
            return (None, None) 
Example #4
Source File: urllib2.py    From jawfish with MIT License 6 votes vote down vote up
def proxy_open(self, req, proxy, type):
        orig_type = req.get_type()
        type, r_type = splittype(proxy)
        host, XXX = splithost(r_type)
        if '@' in host:
            user_pass, host = host.split('@', 1)
            user_pass = base64.encodestring(unquote(user_pass)).strip()
            req.add_header('Proxy-Authorization', 'Basic '+user_pass)
        host = unquote(host)
        req.set_proxy(host, type)
        if orig_type == type:
            # let other handlers take care of it
            # XXX this only makes sense if the proxy is before the
            # other handlers
            return None
        else:
            # need to start over, because the other handlers don't
            # grok the proxy's URL type
            return self.parent.open(req)

# feature suggested by Duncan Booth
# XXX custom is not a good name 
Example #5
Source File: tests.py    From gazetteer with MIT License 6 votes vote down vote up
def test_http_basic_auth(self):

        def get_auth_string(username, password):
            credentials = base64.encodestring('%s:%s' % (username, password)).strip()
            auth_string = 'Basic %s' % credentials
            return auth_string            

        correct_creds = get_auth_string(self.test_user.username, self.user_password)
        wrong_creds = get_auth_string("wronguser", "wrongpasswrod")
        post_json_data= '{"geometry":{},"type":"Feature", "properties":{"importance":null,"feature_code":"PPL","id":null,"population":null, \
        "is_composite":true,"name":"New Testing Place3","area":null,"admin":[],"is_primary":true,"alternate":null, \
        "timeframe":{},"uris":[]}}'
        response = self.c.post('/1.0/place.json', post_json_data, content_type='application/json', HTTP_AUTHORIZATION=wrong_creds)
        self.assertEqual(response.status_code, 403)
        response = self.c.post('/1.0/place.json', post_json_data, content_type='application/json', HTTP_AUTHORIZATION=correct_creds)
        self.assertEqual(response.status_code, 200) 
Example #6
Source File: metadata.py    From awesome-zio with Apache License 2.0 6 votes vote down vote up
def query(owner, name):
    if fake:
        print '    {0}/{1}: ok'.format(owner, name)
        return (random.randint(1, 1000), random.randint(1, 300))
    else:
        try:
            req = urllib2.Request('https://api.github.com/repos/{0}/{1}'.format(owner, name))
            if user is not None and token is not None:
                b64 = base64.encodestring('{0}:{1}'.format(user, token)).replace('\n', '')
                req.add_header("Authorization", "Basic {0}".format(b64))
            u = urllib2.urlopen(req)
            j = json.load(u)
            t = datetime.datetime.strptime(j['updated_at'], "%Y-%m-%dT%H:%M:%SZ")
            days = max(int((now - t).days), 0)
            print '    {0}/{1}: ok'.format(owner, name)
            return (int(j['stargazers_count']), days)
        except urllib2.HTTPError, e:
            print '    {0}/{1}: FAILED'.format(owner, name)
            return (None, None) 
Example #7
Source File: websocket.py    From plugin.video.emby with GNU General Public License v3.0 6 votes vote down vote up
def _validate_header(self, headers, key):
        for k, v in _HEADERS_TO_CHECK.iteritems():
            r = headers.get(k, None)
            if not r:
                return False
            r = r.lower()
            if v != r:
                return False

        result = headers.get("sec-websocket-accept", None)
        if not result:
            return False
        result = result.lower()

        value = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
        hashed = base64.encodestring(hashlib.sha1(value).digest()).strip().lower()
        return hashed == result 
Example #8
Source File: package_index.py    From jbox with MIT License 6 votes vote down vote up
def _encode_auth(auth):
    """
    A function compatible with Python 2.3-3.3 that will encode
    auth from a URL suitable for an HTTP header.
    >>> str(_encode_auth('username%3Apassword'))
    'dXNlcm5hbWU6cGFzc3dvcmQ='

    Long auth strings should not cause a newline to be inserted.
    >>> long_auth = 'username:' + 'password'*10
    >>> chr(10) in str(_encode_auth(long_auth))
    False
    """
    auth_s = urllib.parse.unquote(auth)
    # convert to bytes
    auth_bytes = auth_s.encode()
    # use the legacy interface for Python 2.3 support
    encoded_bytes = base64.encodestring(auth_bytes)
    # convert back to a string
    encoded = encoded_bytes.decode()
    # strip the trailing carriage return
    return encoded.replace('\n','') 
Example #9
Source File: package_index.py    From python-netsurv with MIT License 6 votes vote down vote up
def _encode_auth(auth):
    """
    A function compatible with Python 2.3-3.3 that will encode
    auth from a URL suitable for an HTTP header.
    >>> str(_encode_auth('username%3Apassword'))
    'dXNlcm5hbWU6cGFzc3dvcmQ='

    Long auth strings should not cause a newline to be inserted.
    >>> long_auth = 'username:' + 'password'*10
    >>> chr(10) in str(_encode_auth(long_auth))
    False
    """
    auth_s = urllib.parse.unquote(auth)
    # convert to bytes
    auth_bytes = auth_s.encode()
    # use the legacy interface for Python 2.3 support
    encoded_bytes = base64.encodestring(auth_bytes)
    # convert back to a string
    encoded = encoded_bytes.decode()
    # strip the trailing carriage return
    return encoded.replace('\n', '') 
Example #10
Source File: package_index.py    From python-netsurv with MIT License 6 votes vote down vote up
def _encode_auth(auth):
    """
    A function compatible with Python 2.3-3.3 that will encode
    auth from a URL suitable for an HTTP header.
    >>> str(_encode_auth('username%3Apassword'))
    'dXNlcm5hbWU6cGFzc3dvcmQ='

    Long auth strings should not cause a newline to be inserted.
    >>> long_auth = 'username:' + 'password'*10
    >>> chr(10) in str(_encode_auth(long_auth))
    False
    """
    auth_s = urllib.parse.unquote(auth)
    # convert to bytes
    auth_bytes = auth_s.encode()
    # use the legacy interface for Python 2.3 support
    encoded_bytes = base64.encodestring(auth_bytes)
    # convert back to a string
    encoded = encoded_bytes.decode()
    # strip the trailing carriage return
    return encoded.replace('\n', '') 
Example #11
Source File: package_index.py    From pledgeservice with Apache License 2.0 6 votes vote down vote up
def _encode_auth(auth):
    """
    A function compatible with Python 2.3-3.3 that will encode
    auth from a URL suitable for an HTTP header.
    >>> str(_encode_auth('username%3Apassword'))
    'dXNlcm5hbWU6cGFzc3dvcmQ='

    Long auth strings should not cause a newline to be inserted.
    >>> long_auth = 'username:' + 'password'*10
    >>> chr(10) in str(_encode_auth(long_auth))
    False
    """
    auth_s = unquote(auth)
    # convert to bytes
    auth_bytes = auth_s.encode()
    # use the legacy interface for Python 2.3 support
    encoded_bytes = base64.encodestring(auth_bytes)
    # convert back to a string
    encoded = encoded_bytes.decode()
    # strip the trailing carriage return
    return encoded.replace('\n','') 
Example #12
Source File: package_index.py    From lambda-chef-node-cleanup with Apache License 2.0 6 votes vote down vote up
def _encode_auth(auth):
    """
    A function compatible with Python 2.3-3.3 that will encode
    auth from a URL suitable for an HTTP header.
    >>> str(_encode_auth('username%3Apassword'))
    'dXNlcm5hbWU6cGFzc3dvcmQ='

    Long auth strings should not cause a newline to be inserted.
    >>> long_auth = 'username:' + 'password'*10
    >>> chr(10) in str(_encode_auth(long_auth))
    False
    """
    auth_s = urllib.parse.unquote(auth)
    # convert to bytes
    auth_bytes = auth_s.encode()
    # use the legacy interface for Python 2.3 support
    encoded_bytes = base64.encodestring(auth_bytes)
    # convert back to a string
    encoded = encoded_bytes.decode()
    # strip the trailing carriage return
    return encoded.replace('\n','') 
Example #13
Source File: package_index.py    From kobo-predict with BSD 2-Clause "Simplified" License 6 votes vote down vote up
def _encode_auth(auth):
    """
    A function compatible with Python 2.3-3.3 that will encode
    auth from a URL suitable for an HTTP header.
    >>> str(_encode_auth('username%3Apassword'))
    'dXNlcm5hbWU6cGFzc3dvcmQ='

    Long auth strings should not cause a newline to be inserted.
    >>> long_auth = 'username:' + 'password'*10
    >>> chr(10) in str(_encode_auth(long_auth))
    False
    """
    auth_s = urllib.parse.unquote(auth)
    # convert to bytes
    auth_bytes = auth_s.encode()
    # use the legacy interface for Python 2.3 support
    encoded_bytes = base64.encodestring(auth_bytes)
    # convert back to a string
    encoded = encoded_bytes.decode()
    # strip the trailing carriage return
    return encoded.replace('\n', '') 
Example #14
Source File: _http.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _tunnel(sock, host, port, auth):
    debug("Connecting proxy...")
    connect_header = "CONNECT %s:%d HTTP/1.0\r\n" % (host, port)
    # TODO: support digest auth.
    if auth and auth[0]:
        auth_str = auth[0]
        if auth[1]:
            auth_str += ":" + auth[1]
        encoded_str = base64encode(auth_str.encode()).strip().decode()
        connect_header += "Proxy-Authorization: Basic %s\r\n" % encoded_str
    connect_header += "\r\n"
    dump("request header", connect_header)

    send(sock, connect_header)

    try:
        status, resp_headers, status_message = read_headers(sock)
    except Exception as e:
        raise WebSocketProxyException(str(e))

    if status != 200:
        raise WebSocketProxyException(
            "failed CONNECT via proxy status: %r" % status)

    return sock 
Example #15
Source File: metadata.py    From awesome-iot with MIT License 6 votes vote down vote up
def query(owner, name):
    if fake:
        print '    {0}/{1}: ok'.format(owner, name)
        return (random.randint(1, 1000), random.randint(1, 300))
    else:
        try:
            req = urllib2.Request('https://api.github.com/repos/{0}/{1}'.format(owner, name))
            if user is not None and token is not None:
                b64 = base64.encodestring('{0}:{1}'.format(user, token)).replace('\n', '')
                req.add_header("Authorization", "Basic {0}".format(b64))
            u = urllib2.urlopen(req)
            j = json.load(u)
            t = datetime.datetime.strptime(j['updated_at'], "%Y-%m-%dT%H:%M:%SZ")
            days = max(int((now - t).days), 0)
            print '    {0}/{1}: ok'.format(owner, name)
            return (int(j['stargazers_count']), days)
        except urllib2.HTTPError, e:
            print '    {0}/{1}: FAILED'.format(owner, name)
            return (None, None) 
Example #16
Source File: rwbase.py    From Computable with MIT License 6 votes vote down vote up
def base64_encode(nb):
    """Base64 encode all bytes objects in the notebook.
    
    These will be b64-encoded unicode strings
    
    Note: This is never used
    """
    for ws in nb.worksheets:
        for cell in ws.cells:
            if cell.cell_type == 'code':
                for output in cell.outputs:
                    if 'png' in output:
                        output.png = encodestring(output.png).decode('ascii')
                    if 'jpeg' in output:
                        output.jpeg = encodestring(output.jpeg).decode('ascii')
    return nb 
Example #17
Source File: encoders.py    From Computable with MIT License 5 votes vote down vote up
def _qencode(s):
    enc = _encodestring(s, quotetabs=True)
    # Must encode spaces, which quopri.encodestring() doesn't do
    return enc.replace(' ', '=20') 
Example #18
Source File: _handshake.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _create_sec_websocket_key():
    randomness = os.urandom(16)
    return base64encode(randomness).decode('utf-8').strip() 
Example #19
Source File: _handshake.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def _validate(headers, key, subprotocols):
    subproto = None
    for k, v in _HEADERS_TO_CHECK.items():
        r = headers.get(k, None)
        if not r:
            return False, None
        r = r.lower()
        if v != r:
            return False, None

    if subprotocols:
        subproto = headers.get("sec-websocket-protocol", None).lower()
        if not subproto or subproto not in [s.lower() for s in subprotocols]:
            error("Invalid subprotocol: " + str(subprotocols))
            return False, None

    result = headers.get("sec-websocket-accept", None)
    if not result:
        return False, None
    result = result.lower()

    if isinstance(result, six.text_type):
        result = result.encode('utf-8')

    value = (key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11").encode('utf-8')
    hashed = base64encode(hashlib.sha1(value).digest()).strip().lower()
    success = compare_digest(hashed, result)

    if success:
        return True, subproto
    else:
        return False, None 
Example #20
Source File: helper.py    From FuzzFlow with MIT License 5 votes vote down vote up
def update_job_output(self, job_id, content):
        output = base64.encodestring(content)
        return Rest.update_job(job_id, {
            'output': output
        }) 
Example #21
Source File: util.py    From lighter with MIT License 5 votes vote down vote up
def buildRequest(url, data=None, headers={}, method='GET', contentType='application/json'):
    parsed_url = urlparse.urlparse(url)
    parts = list(parsed_url[0:6])
    parts[1] = ('@' in parts[1]) and parts[1].split('@')[1] or parts[1]

    body = None
    headers = copy(headers)

    if data is not None:
        if contentType == 'application/json':
            body = toJson(data)
            headers['Content-Type'] = 'application/json'
        elif contentType == 'application/x-www-form-urlencoded':
            body = urllib.urlencode(data)
            headers['Content-Type'] = 'application/x-www-form-urlencoded'

    request = urllib2.Request(urlunparse(parts), body, headers)
    request.get_method = lambda: method

    if parsed_url.username is not None and parsed_url.password is not None:
        # You need the replace to handle encodestring adding a trailing newline
        # (https://docs.python.org/2/library/base64.html#base64.encodestring)
        base64string = base64.encodestring('%s:%s' % (parsed_url.username, parsed_url.password)).replace('\n', '')
        request.add_header("Authorization", "Basic %s" % base64string)

    return request 
Example #22
Source File: urllib2.py    From jawfish with MIT License 5 votes vote down vote up
def retry_http_basic_auth(self, host, req, realm):
        user,pw = self.passwd.find_user_password(realm, host)
        if pw:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.encodestring(raw).strip()
            if req.headers.get(self.auth_header, None) == auth:
                return None
            req.add_header(self.auth_header, auth)
            return self.parent.open(req)
        else:
            return None 
Example #23
Source File: px.py    From px with MIT License 5 votes vote down vote up
def b64encode(val):
    try:
        return base64.encodebytes(val.encode("utf-8"))
    except AttributeError:
        return base64.encodestring(val) 
Example #24
Source File: userencode.py    From SinaMicroblog_Creeper-Spider_VerificationCode with GNU General Public License v2.0 5 votes vote down vote up
def GetUserName(userName):
    "Used to encode user name"
    userNameTemp = urllib2.quote(userName)
    userNameEncoded = base64.encodestring(userNameTemp)[:-1]
    return userNameEncoded 
Example #25
Source File: weibo_util.py    From hexo_weibo_image with MIT License 5 votes vote down vote up
def generate_form_data(nonce, pubkey, servertime, rsakv, username, password):
    rsa_public_key = int(pubkey, 16)
    key = rsa.PublicKey(rsa_public_key, 65537)
    message = str(servertime) + '\t' + str(nonce) + '\n' + str(password)
    passwd = rsa.encrypt(message, key)
    passwd = binascii.b2a_hex(passwd)
    username = urllib2.quote(username)
    username = base64.encodestring(username)
    form_data = {
        'entry': 'weibo',
        'gateway': '1',
        'from': '',
        'savestate': '7',
        'useticket': '1',
        'pagerefer': 'http://weibo.com/p/1005052679342531/home?from=page_100505&mod=TAB&pids=plc_main',
        'vsnf': '1',
        'su': username,
        'service': 'miniblog',
        'servertime': servertime,
        'nonce': nonce,
        'pwencode': 'rsa2',
        'rsakv': rsakv,
        'sp': passwd,
        'sr': '1366*768',
        'encoding': 'UTF-8',
        'prelt': '115',
        'url': 'http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack',
        'returntype': 'META'
    }
    form_data = urllib.urlencode(form_data)
    return form_data 
Example #26
Source File: thttpclient.py    From galaxy-sdk-python with Apache License 2.0 5 votes vote down vote up
def __auth_headers(self, headers):
    string_to_assign = str()
    string_to_assign += '%s\n' % 'POST'
    string_to_assign += '%s\n' % headers[CONTENT_MD5]
    string_to_assign += '%s\n' % headers[CONTENT_TYPE]
    string_to_assign += '\n'
    string_to_assign += '%s' % self.__canonicalize_xiaomi_headers(headers)
    string_to_assign += '%s' % self.__canonicalize_resource(self.path)
    signature = \
      base64.encodestring(hmac.new(self.credential.secretKey, string_to_assign, digestmod=sha1).digest()).strip()
    auth_string = "Galaxy-V2 %s:%s" % (self.credential.secretKeyId, signature)
    headers[AUTHORIZATION] = auth_string

    return headers 
Example #27
Source File: utils.py    From galaxy-sdk-python with Apache License 2.0 5 votes vote down vote up
def auth_headers(method, uri, headers, credential):
  string_to_assign = str()
  string_to_assign += '%s\n' % method
  string_to_assign += '%s\n' % headers[CONTENT_MD5]
  string_to_assign += '%s\n' % headers[CONTENT_TYPE]
  string_to_assign += '%s\n' % headers[DATE]
  string_to_assign += '%s' % __canonicalize_xiaomi_headers(headers)
  string_to_assign += '%s' % __canonicalize_resource(uri)
  signature = base64.encodestring(hmac.new(credential.galaxy_key_secret, string_to_assign, digestmod=sha1).digest()).strip()
  auth_string = "Galaxy-V2 %s:%s" % (credential.galaxy_access_key, signature)
  new_header = dict.copy(headers)
  new_header[AUTHORIZATION] = auth_string
  return new_header 
Example #28
Source File: sdsthttpclient.py    From galaxy-sdk-python with Apache License 2.0 5 votes vote down vote up
def __auth_headers(self, headers):
    string_to_assign = str()
    string_to_assign += '%s\n' % 'POST'
    string_to_assign += '%s\n' % self.__get_header(headers, "content-md5")
    string_to_assign += '%s\n' % self.__get_header(headers, "content-type")
    string_to_assign += '\n'
    string_to_assign += '%s' % self.__canonicalize_xiaomi_headers(headers)
    string_to_assign += '%s' % self.__canonicalize_resource(self.path)
    signature = \
      base64.encodestring(hmac.new(self.credential.secretKey, string_to_assign, digestmod=sha1).digest()).strip()
    auth_string = "Galaxy-V3 %s:%s" % (self.credential.secretKeyId, signature)
    headers[HK_AUTHORIZATION] = auth_string

    return headers 
Example #29
Source File: __init__.py    From bugbuzz-python with MIT License 5 votes vote down vote up
def encrypt(self, key, msg):
        from Crypto.Cipher import AES
        secret = self.getSecret(key)
        Initial16bytes = '0123456789012345'
        cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
        return encodestring(
            cipher.encrypt(self.pad(msg.encode('utf-8')))).decode('utf-8') 
Example #30
Source File: base64_enc_dec.py    From Some-Examples-of-Simple-Python-Script with GNU Affero General Public License v3.0 5 votes vote down vote up
def _base64_encode_string(self, encode_string):
        encoder = base64.encodestring(encode_string)
        return encoder