Python base64.decodestring() Examples

The following are 30 code examples for showing how to use base64.decodestring(). 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: 3vilTwinAttacker   Author: wi-fi-analyzer   File: NetCreds.py    License: MIT License 6 votes vote down vote up
def parse_basic_auth(src_ip_port, dst_ip_port, headers, authorization_header):
    '''
    Parse basic authentication over HTTP
    '''
    if authorization_header:
        # authorization_header sometimes is triggered by failed ftp
        try:
            header_val = headers[authorization_header.group()]
        except KeyError:
            return
        b64_auth_re = re.match('basic (.+)', header_val, re.IGNORECASE)
        if b64_auth_re != None:
            basic_auth_b64 = b64_auth_re.group(1)
            basic_auth_creds = base64.decodestring(basic_auth_b64)
            msg = 'Basic Authentication: %s' % basic_auth_creds
            printer(src_ip_port, dst_ip_port, msg) 
Example 2
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: NetCreds.py    License: MIT License 6 votes vote down vote up
def parse_netntlm_resp_msg(headers, resp_header, seq):
    '''
    Parse the client response to the challenge
    '''
    try:
        header_val3 = headers[resp_header]
    except KeyError:
        return
    header_val3 = header_val3.split(' ', 1)

    # The header value can either start with NTLM or Negotiate
    if header_val3[0] == 'NTLM' or header_val3[0] == 'Negotiate':
        try:
            msg3 = base64.decodestring(header_val3[1])
        except binascii.Error:
            return
        return parse_ntlm_resp(msg3, seq) 
Example 3
Project: net-creds   Author: DanMcInerney   File: net-creds.py    License: GNU General Public License v3.0 6 votes vote down vote up
def parse_basic_auth(src_ip_port, dst_ip_port, headers, authorization_header):
    '''
    Parse basic authentication over HTTP
    '''
    if authorization_header:
        # authorization_header sometimes is triggered by failed ftp
        try:
            header_val = headers[authorization_header.group()]
        except KeyError:
            return
        b64_auth_re = re.match('basic (.+)', header_val, re.IGNORECASE)
        if b64_auth_re != None:
            basic_auth_b64 = b64_auth_re.group(1)
            try:
                basic_auth_creds = base64.decodestring(basic_auth_b64)
            except Exception:
                return
            msg = 'Basic Authentication: %s' % basic_auth_creds
            printer(src_ip_port, dst_ip_port, msg) 
Example 4
Project: net-creds   Author: DanMcInerney   File: net-creds.py    License: GNU General Public License v3.0 6 votes vote down vote up
def parse_netntlm_chal(headers, chal_header, ack):
    '''
    Parse the netntlm server challenge
    https://code.google.com/p/python-ntlm/source/browse/trunk/python26/ntlm/ntlm.py
    '''
    try:
        header_val2 = headers[chal_header]
    except KeyError:
        return
    header_val2 = header_val2.split(' ', 1)
    # The header value can either start with NTLM or Negotiate
    if header_val2[0] == 'NTLM' or header_val2[0].lower() == 'negotiate':
        try:
            msg2 = header_val2[1]
        except IndexError:
            return
        msg2 = base64.decodestring(msg2)
        parse_ntlm_chal(msg2, ack) 
Example 5
Project: net-creds   Author: DanMcInerney   File: net-creds.py    License: GNU General Public License v3.0 6 votes vote down vote up
def parse_netntlm_resp_msg(headers, resp_header, seq):
    '''
    Parse the client response to the challenge
    '''
    try:
        header_val3 = headers[resp_header]
    except KeyError:
        return
    header_val3 = header_val3.split(' ', 1)

    # The header value can either start with NTLM or Negotiate
    if header_val3[0] == 'NTLM' or header_val3[0] == 'Negotiate':
        try:
            msg3 = base64.decodestring(header_val3[1])
        except binascii.Error:
            return
        return parse_ntlm_resp(msg3, seq) 
Example 6
Project: mishkal   Author: linuxscout   File: cookie.py    License: GNU General Public License v3.0 6 votes vote down vote up
def auth(self, cookie):
        """
        Authenticate the cooke using the signature, verify that it
        has not expired; and return the cookie's content
        """
        decode = base64.decodestring(
            cookie.replace("_", "/").replace("~", "="))
        signature = decode[:_signature_size]
        expires = decode[_signature_size:_header_size]
        content = decode[_header_size:]
        if signature == hmac.new(self.secret, content, sha1).digest():
            if int(expires) > int(make_time(time.time())):
                return content
            else:
                # This is the normal case of an expired cookie; just
                # don't bother doing anything here.
                pass
        else:
            # This case can happen if the server is restarted with a
            # different secret; or if the user's IP address changed
            # due to a proxy.  However, it could also be a break-in
            # attempt -- so should it be reported?
            pass 
Example 7
Project: meddle   Author: glmcdona   File: base64_codec.py    License: MIT License 6 votes vote down vote up
def base64_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = base64.decodestring(input)
    return (output, len(input)) 
Example 8
Project: Computable   Author: ktraunmueller   File: base64_codec.py    License: MIT License 6 votes vote down vote up
def base64_decode(input,errors='strict'):

    """ Decodes the object input and returns a tuple (output
        object, length consumed).

        input must be an object which provides the bf_getreadbuf
        buffer slot. Python strings, buffer objects and memory
        mapped files are examples of objects providing this slot.

        errors defines the error handling to apply. It defaults to
        'strict' handling which is the only currently supported
        error handling for this codec.

    """
    assert errors == 'strict'
    output = base64.decodestring(input)
    return (output, len(input)) 
Example 9
Project: Computable   Author: ktraunmueller   File: rwbase.py    License: MIT License 6 votes vote down vote up
def base64_decode(nb):
    """Restore all bytes objects in the notebook from base64-encoded 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:
                        if isinstance(output.png, unicode):
                            output.png = output.png.encode('ascii')
                        output.png = decodestring(output.png)
                    if 'jpeg' in output:
                        if isinstance(output.jpeg, unicode):
                            output.jpeg = output.jpeg.encode('ascii')
                        output.jpeg = decodestring(output.jpeg)
    return nb 
Example 10
Project: Computable   Author: ktraunmueller   File: test_json.py    License: MIT License 6 votes vote down vote up
def test_read_jpeg(self):
        """JPEG output data is b64 unicode"""
        s = writes(nb0)
        nb1 = nbjson.reads(s)
        found_jpeg = False
        for cell in nb1.worksheets[0].cells:
            if not 'outputs' in cell:
                continue
            for output in cell.outputs:
                if 'jpeg' in output:
                    found_jpeg = True
                    jpegdata = output['jpeg']
                    self.assertEqual(type(jpegdata), unicode)
                    # test that it is valid b64 data
                    b64bytes = jpegdata.encode('ascii')
                    raw_bytes = decodestring(b64bytes)
        assert found_jpeg, "never found jpeg output" 
Example 11
Project: Computable   Author: ktraunmueller   File: rwbase.py    License: MIT License 6 votes vote down vote up
def base64_decode(nb):
    """Restore all bytes objects in the notebook from base64-encoded 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:
                        if isinstance(output.png, unicode):
                            output.png = output.png.encode('ascii')
                        output.png = decodestring(output.png)
                    if 'jpeg' in output:
                        if isinstance(output.jpeg, unicode):
                            output.jpeg = output.jpeg.encode('ascii')
                        output.jpeg = decodestring(output.jpeg)
    return nb 
Example 12
Project: Computable   Author: ktraunmueller   File: rich_ipython_widget.py    License: MIT License 6 votes vote down vote up
def _handle_pyout(self, msg):
        """ Overridden to handle rich data types, like SVG.
        """
        if not self._hidden and self._is_from_this_session(msg):
            content = msg['content']
            prompt_number = content.get('execution_count', 0)
            data = content['data']
            metadata = msg['content']['metadata']
            if 'image/svg+xml' in data:
                self._pre_image_append(msg, prompt_number)
                self._append_svg(data['image/svg+xml'], True)
                self._append_html(self.output_sep2, True)
            elif 'image/png' in data:
                self._pre_image_append(msg, prompt_number)
                png = decodestring(data['image/png'].encode('ascii'))
                self._append_png(png, True, metadata=metadata.get('image/png', None))
                self._append_html(self.output_sep2, True)
            elif 'image/jpeg' in data and self._jpg_supported:
                self._pre_image_append(msg, prompt_number)
                jpg = decodestring(data['image/jpeg'].encode('ascii'))
                self._append_jpg(jpg, True, metadata=metadata.get('image/jpeg', None))
                self._append_html(self.output_sep2, True)
            else:
                # Default back to the plain text representation.
                return super(RichIPythonWidget, self)._handle_pyout(msg) 
Example 13
Project: indras_net   Author: gcallah   File: markov.py    License: GNU General Public License v3.0 5 votes vote down vote up
def from_json(self, json_input):
        # get the encoded json dump
        enc = json_input["matrix"]
        
        # build the numpy data type
        dataType = np.dtype(enc[0])
        
        # decode the base64 encoded numpy array data and create a new numpy array with this data & type
        dataArray = np.frombuffer(base64.decodestring(enc[1].encode('utf-8')), dataType)
        
        # if the array had more than one data set it has to be reshaped
        if len(enc) > 2:
             dataArray = dataArray.reshape(enc[2]) # return the reshaped numpy array containing several data sets
             
        self.matrix = np.matrix(dataArray) 
Example 14
Project: indras_net   Author: gcallah   File: vector_space.py    License: GNU General Public License v3.0 5 votes vote down vote up
def from_json(cls, json_input):
        # get the encoded json dump
        enc = json_input["vector"]
        
        # build the numpy data type
        dataType = np.dtype(enc[0])

        # decode the base64 encoded numpy array data and create a new numpy array with this data & type
        return from_vector(np.frombuffer(base64.decodestring(enc[1].encode('utf-8')), dataType))

# Now we actually initialize the prehensions we declared above.
#  This can't be done earlier, since VectorSpace was just defined. 
Example 15
Project: endpoints-tools   Author: cloudendpoints   File: generate-google-id-jwt.py    License: Apache License 2.0 5 votes vote down vote up
def generate_jwt(args):
    """Generates a signed JSON Web Token using a service account. Based on https://cloud.google.com/endpoints/docs/service-to-service-auth"""
    # Make sure the service account has "Service Account Token Creator" permissions in Google IAM
    credentials = ServiceAccountCredentials.from_json_keyfile_name(
      args.service_account_file).create_scoped(['https://www.googleapis.com/auth/cloud-platform'])

    service = googleapiclient.discovery.build(
        serviceName='iam', version='v1', credentials=credentials)

    now = int(time.time())
    header_json = json.dumps({
        "typ": "JWT",
        "alg": "RS256"})

    payload_json = json.dumps({
        'iat': now,
        "exp": now + 3600,
        'iss': args.issuer if args.issuer else credentials.service_account_email,
        "target_audience": 'https://' + args.aud,
        "aud": "https://www.googleapis.com/oauth2/v4/token"
    })

    header_and_payload = '{}.{}'.format(
        base64.urlsafe_b64encode(header_json),
        base64.urlsafe_b64encode(payload_json))
    slist = service.projects().serviceAccounts().signBlob(
        name="projects/-/serviceAccounts/" + credentials.service_account_email,
        body={'bytesToSign': base64.b64encode(header_and_payload)})
    res = slist.execute()
    signature = base64.urlsafe_b64encode(
        base64.decodestring(res['signature']))
    signed_jwt = '{}.{}'.format(header_and_payload, signature)

    return signed_jwt 
Example 16
Project: me-ica   Author: ME-ICA   File: parse_gifti_fast.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def read_data_block(encoding, endian, ordering, datatype, shape, data):
    """ Tries to unzip, decode, parse the funny string data """
    ord = array_index_order_codes.npcode[ordering]
    enclabel = gifti_encoding_codes.label[encoding]
    if enclabel == 'ASCII':
        # GIFTI_ENCODING_ASCII
        c = StringIO(data)
        da = np.loadtxt(c)
        da = da.astype(data_type_codes.type[datatype])
        # independent of the endianness
        return da
    elif enclabel == 'B64BIN':
        # GIFTI_ENCODING_B64BIN
        dec = base64.decodestring(data.encode('ascii'))
        dt = data_type_codes.type[datatype]
        sh = tuple(shape)
        newarr = np.fromstring(dec, dtype = dt)
        if len(newarr.shape) != len(sh):
            newarr = newarr.reshape(sh, order = ord)
    elif enclabel == 'B64GZ':
        # GIFTI_ENCODING_B64GZ
        # convert to bytes array for python 3.2
        # http://diveintopython3.org/strings.html#byte-arrays
        dec = base64.decodestring(data.encode('ascii'))
        zdec = zlib.decompress(dec)
        dt = data_type_codes.type[datatype]
        sh = tuple(shape)
        newarr = np.fromstring(zdec, dtype = dt)
        if len(newarr.shape) != len(sh):
            newarr = newarr.reshape(sh, order = ord)
    elif enclabel == 'External':
        # GIFTI_ENCODING_EXTBIN
        raise NotImplementedError("In what format are the external files?")
    else:
        return 0
    # check if we need to byteswap
    required_byteorder = gifti_endian_codes.byteorder[endian]
    if (required_byteorder in ('big', 'little') and
        required_byteorder != sys.byteorder):
        newarr = newarr.byteswap()
    return newarr 
Example 17
Project: misp42splunk   Author: remg427   File: constructor.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def construct_yaml_binary(self, node):
        try:
            value = self.construct_scalar(node).encode('ascii')
        except UnicodeEncodeError as exc:
            raise ConstructorError(None, None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark)
        try:
            if hasattr(base64, 'decodebytes'):
                return base64.decodebytes(value)
            else:
                return base64.decodestring(value)
        except binascii.Error as exc:
            raise ConstructorError(None, None,
                    "failed to decode base64 data: %s" % exc, node.start_mark) 
Example 18
Project: misp42splunk   Author: remg427   File: constructor.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def construct_python_bytes(self, node):
        try:
            value = self.construct_scalar(node).encode('ascii')
        except UnicodeEncodeError as exc:
            raise ConstructorError(None, None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark)
        try:
            if hasattr(base64, 'decodebytes'):
                return base64.decodebytes(value)
            else:
                return base64.decodestring(value)
        except binascii.Error as exc:
            raise ConstructorError(None, None,
                    "failed to decode base64 data: %s" % exc, node.start_mark) 
Example 19
Project: misp42splunk   Author: remg427   File: constructor.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def construct_yaml_binary(self, node):
        try:
            value = self.construct_scalar(node).encode('ascii')
        except UnicodeEncodeError as exc:
            raise ConstructorError(None, None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark)
        try:
            if hasattr(base64, 'decodebytes'):
                return base64.decodebytes(value)
            else:
                return base64.decodestring(value)
        except binascii.Error as exc:
            raise ConstructorError(None, None,
                    "failed to decode base64 data: %s" % exc, node.start_mark) 
Example 20
Project: misp42splunk   Author: remg427   File: constructor.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def construct_python_bytes(self, node):
        try:
            value = self.construct_scalar(node).encode('ascii')
        except UnicodeEncodeError as exc:
            raise ConstructorError(None, None,
                    "failed to convert base64 data into ascii: %s" % exc,
                    node.start_mark)
        try:
            if hasattr(base64, 'decodebytes'):
                return base64.decodebytes(value)
            else:
                return base64.decodestring(value)
        except binascii.Error as exc:
            raise ConstructorError(None, None,
                    "failed to decode base64 data: %s" % exc, node.start_mark) 
Example 21
Project: bugbuzz-python   Author: fangpenlin   File: __init__.py    License: MIT License 5 votes vote down vote up
def decrypt(self, key, msg):
        from Crypto.Cipher import AES
        try:
            secret = self.getSecret(key)
            Initial16bytes = '0123456789012345'
            cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
            plain = self.depad(cipher.decrypt(decodestring(msg)))
        except:
            return msg
        try:
            return eval(plain)
        except SyntaxError:
            return plain 
Example 22
Project: bugbuzz-python   Author: fangpenlin   File: __init__.py    License: MIT License 5 votes vote down vote up
def decrypt(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 (cipher.decrypt(
            decodestring(msg.encode('utf-8')))).decode('utf-8') 
Example 23
Project: bugbuzz-python   Author: fangpenlin   File: __init__.py    License: MIT License 5 votes vote down vote up
def decrypt(self, key, msg):
        from Crypto.Cipher import AES
        try:
            secret = self.getSecret(key)
            Initial16bytes = '0123456789012345'
            cipher = AES.new(secret[0:32], AES.MODE_CBC, Initial16bytes)
            plain = self.depad(cipher.decrypt(decodestring(msg)))
        except:
            return msg
        try:
            return eval(plain)
        except SyntaxError:
            return plain 
Example 24
Project: bugbuzz-python   Author: fangpenlin   File: __init__.py    License: MIT License 5 votes vote down vote up
def decrypt(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 (cipher.decrypt(
            decodestring(msg.encode('utf-8')))).decode('utf-8') 
Example 25
Project: 3vilTwinAttacker   Author: wi-fi-analyzer   File: NetCreds.py    License: MIT License 5 votes vote down vote up
def parse_netntlm_chal(headers, chal_header, ack):
    '''
    Parse the netntlm server challenge
    https://code.google.com/p/python-ntlm/source/browse/trunk/python26/ntlm/ntlm.py
    '''
    try:
        header_val2 = headers[chal_header]
    except KeyError:
        return
    header_val2 = header_val2.split(' ', 1)
    # The header value can either start with NTLM or Negotiate
    if header_val2[0] == 'NTLM' or header_val2[0] == 'Negotiate':
        msg2 = header_val2[1]
        msg2 = base64.decodestring(msg2)
        parse_ntlm_chal(ack, msg2) 
Example 26
Project: bilibiliupload   Author: ForgQi   File: live.py    License: MIT License 5 votes vote down vote up
def prepare(self):
        info = VideoInfo(self.name, True)
        html = get_content(self.url)
        t_a = match1(html, '"keywords" content="([^"]+)')
        info.title = t_a.split(',')[0]
        info.artist = t_a.split(',')[1]

        replay_url = match1(html, '"m3u8":"([^"]+)')
        if replay_url:
            replay_url = replay_url.replace('\/','/')
            info.live = False
            info.stream_types.append('current')
            info.streams['current'] = {'container': 'm3u8', 'video_profile': 'current', 'src' : [replay_url], 'size': float('inf')}
            return info

        self.vid = match1(html, '"sn":"([^"]+)')
        channel = match1(html, '"channel":"([^"]+)')
        api_url = 'http://g2.live.360.cn/liveplay?stype=flv&channel={}&bid=huajiao&sn={}&sid={}&_rate=xd&ts={}&r={}&_ostype=flash&_delay=0&_sign=null&_ver=13'.format(channel, self.vid, SID, time.time(),random.random())
        encoded_json = get_content(api_url)
        decoded_json = base64.decodestring(compact_bytes(encoded_json[0:3]+ encoded_json[6:], 'utf-8')).decode('utf-8')
        video_data = json.loads(decoded_json)
        live_url = video_data['main']
        info.live = True
        info.stream_types.append('current')
        info.streams['current'] = {'container': 'flv', 'video_profile': 'current', 'src' : [live_url], 'size': float('inf')}
        return info 
Example 27
Project: vulscan   Author: vulscanteam   File: tooler_views.py    License: MIT License 5 votes vote down vote up
def index(request):
    if request.method == 'GET':
        old = u"hello world!"
        new = u"hello%20world%21"
        return render(request,'tooler.html',{'old':old,'new':new,})
    elif request.method == 'POST':
        try:
            #判断处理方式
            #return HttpResponse(requests)
            #获取表单值并设置编码
            old  = request.POST['old'] .encode('utf-8')
            action = request.POST['action'] 

            if action == 'urlencode':
                new = urllib.quote(old)
            elif action == 'urldecode':
                new = urllib.unquote(old)   
            elif action == 'asciicode':
                ascii_code = ''
                for i in range(len(old)):
                    ascii_code = ascii_code + u'chr(' + str(ord(old[i])).strip() + u')' 
                #中文部分会存在问题
                new = ascii_code
            elif action == 'enbase64':
                new = base64.encodestring(old)
            elif action == 'debase64':
                new = base64.decodestring(old)
            elif action == 'enmd5':
                passwd = hashlib.md5()
                passwd.update(old)
                new = passwd.hexdigest()
            else:
                return HttpResponse('error!')
            return render(request,'tooler.html',{'old':old,'new':new,})
            #以上可能会出现异常操作,未做异常处理/
        except:
            return HttpResponse('error!') 
Example 28
Project: pagure   Author: Pagure   File: comment_email_milter.py    License: GNU General Public License v2.0 5 votes vote down vote up
def get_email_body(emailobj):
    """ Return the body of the email, preferably in text.
    """

    def _get_body(emailobj):
        """ Return the first text/plain body found if the email is multipart
        or just the regular payload otherwise.
        """
        if emailobj.is_multipart():
            for payload in emailobj.get_payload():
                # If the message comes with a signature it can be that this
                # payload itself has multiple parts, so just return the
                # first one
                if payload.is_multipart():
                    return _get_body(payload)

                body = payload.get_payload()
                if payload.get_content_type() == "text/plain":
                    return body
        else:
            return emailobj.get_payload()

    body = _get_body(emailobj)

    enc = emailobj["Content-Transfer-Encoding"]
    if enc == "base64":
        body = base64.decodestring(body)

    return body 
Example 29
Project: assaytools   Author: choderalab   File: ipnbdoctest.py    License: GNU Lesser General Public License v2.1 5 votes vote down vote up
def compare_png(a64, b64):
        """compare two b64 PNGs (incomplete)"""
        try:
            import Image
        except ImportError:
            pass
        adata = base64.decodestring(a64)
        bdata = base64.decodestring(b64)
        return True 
Example 30
Project: floyd-cli   Author: floydhub   File: access_token.py    License: Apache License 2.0 5 votes vote down vote up
def assert_token_not_expired(token):
    payload_base64 = token.split('.')[1] + '==='
    payload = json.loads(base64.decodestring(payload_base64.encode('ascii')).decode('ascii'))
    if payload['exp'] <= time.time():
        sys.exit('ERROR: Auth token expired, please use "floyd login" command to login with a new token.')