Python base64.b64encode() Examples

The following are code examples for showing how to use base64.b64encode(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: paws   Author: funkybob   File: response.py    BSD 3-Clause "New" or "Revised" License 7 votes vote down vote up
def response(body='', status=200, headers=None, binary=False):
    '''
    Generate a response dict for Lambda Proxy
    '''
    if headers is None:
        headers = {}
    if binary:
        body = b64encode(body)
    elif not isinstance(body, (str, bytes)):
        body = json.dumps(body, default=str)
        headers.setdefault('Content-Type', 'application/json')
    return {
        'statusCode': status,
        'headers': headers,
        'body': body,
        'isBase64Encoded': binary,
    } 
Example 2
Project: WebTeam   Author: shashankrnr32   File: Encryption.py    MIT License 6 votes vote down vote up
def writeConfig(username,password):
    colorama.init(autoreset=True)
    Ukey = random.randint(10,50)
    Pkey = random.randint(10,50)
    username = username.encode()
    password = password.encode()
    Ukey,Pkey,username,password = encrypt(Ukey,Pkey,username,password)
    storage = open('config.txt','w')
    storage.write(str(base64.b64encode(str(Ukey).encode()),'UTF-8'))
    storage.write('\n')
    storage.write(str(base64.b64encode(str(Pkey).encode()),'UTF-8'))
    storage.write('\n')
    storage.write(str(username,'UTF-8'))
    storage.write('\n')
    storage.write(str(password,'UTF-8'))
    storage.close()
    print(colorama.Fore.GREEN+'[SUCCESS] Credentials Saved') 
Example 3
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_id(self, username, role='', sites='', displayName='', email='', altid='', data={}):
        if Options['debug']:
            print >> sys.stderr, 'sdserver.UserIdMixin.set_id', username, role, sites, displayName, email, altid, data

        if ':' in username or ':' in role or ':' in sites or ':' in displayName:
            raise Exception('Colon character not allowed in username/role/name')

        cookie_data = {'version': COOKIE_VERSION}
        cookie_data['name'] = displayName or username
        if email:
            cookie_data['email'] = email
        if altid:
            cookie_data['altid'] = altid

        cookie_data.update(data or {})

        token = gen_proxy_auth_token(username, role, sites, root=True)
        cookieStr = ':'.join( sliauth.safe_quote(x) for x in [username, role, sites, token, base64.b64encode(json.dumps(cookie_data,sort_keys=True))] )

        self.set_user_cookie(cookieStr, batch=cookie_data.get('batch')) 
Example 4
Project: slidoc   Author: mitotic   File: slidoc.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def render(self, text, index_id='', qindex_id=''):
        self.renderer.index_id = index_id
        self.renderer.qindex_id = qindex_id
        html = super(MarkdownWithSlidoc, self).render(text)
        self.renderer.close_zip(text)

        if not self.renderer.global_plugin_refs.issubset(self.renderer.plugin_embeds):
            abort("    ****PLUGIN-ERROR: %s: Missing global plugins %s ." % (self.options["filename"], list(self.renderer.global_plugin_refs.difference(self.renderer.plugin_embeds))))

        first_slide_pre = '<span id="%s-attrs" class="slidoc-attrs" style="display: none;">%s</span>\n' % (self.renderer.first_id, base64.b64encode(json.dumps(self.renderer.questions)))

        if self.renderer.options['config'].pace:
            first_slide_pre += SlidocRenderer.remarks_template

        if self.renderer.qconcepts[0] or self.renderer.qconcepts[1]:
            # Include sorted list of concepts related to questions
            q_list = [sort_caseless(list(self.renderer.qconcepts[j])) for j in (0, 1)]
            first_slide_pre += '<span id="%s-qconcepts" class="slidoc-qconcepts" style="display: none;">%s</span>\n' % (self.renderer.first_id, base64.b64encode(json.dumps(q_list)))

        classes =  ['slidoc-first-slide', 'slidoc-single-column' if 'two_column' in self.renderer.options['config'].features else '']
        prefix = SlidocRenderer.image_drop_template+self.renderer.slide_prefix(self.renderer.first_id, ' '.join(classes))+first_slide_pre+concept_chain(self.renderer.first_id, self.renderer.options['config'].server_url)
        suffix = self.renderer.end_slide(last_slide=True)
        return md2md.unicodify(prefix) + html + md2md.unicodify(suffix) 
Example 5
Project: REMAKE   Author: PHIEZUKE   File: models.py    GNU General Public License v3.0 6 votes vote down vote up
def genOBSParams(self, newList, returnAs='json'):
        oldList = {'name': self.genTempFile('file'),'ver': '1.0'}
        if returnAs not in ['json','b64','default']:
            raise Exception('Invalid parameter returnAs')
        oldList.update(newList)
        if 'range' in oldList:
            new_range='bytes 0-%s\/%s' % ( str(oldList['range']-1), str(oldList['range']) )
            oldList.update({'range': new_range})
        if returnAs == 'json':
            oldList=json.dumps(oldList)
            return oldList
        elif returnAs == 'b64':
            oldList=json.dumps(oldList)
            return base64.b64encode(oldList.encode('utf-8'))
        elif returnAs == 'default':
            return oldList 
Example 6
Project: laracrypt   Author: serverops   File: __init__.py    MIT License 6 votes vote down vote up
def encrypt(self, text):
        iv = ''.join(chr(random.randint(0, 0xFF)) for i in range(16))
        base64_iv = base64.b64encode(iv)
        mode = AES.MODE_CBC
        encrypter = AES.new(self.key, mode, IV=iv)

        value = base64.b64encode(encrypter.encrypt(self._pad(dumps(text))))
        mac = self._hash(base64_iv, value)

        json_encoded = json.dumps({
            'iv': base64_iv,
            'value': value,
            'mac': mac
        })

        return base64.b64encode(json_encoded) 
Example 7
Project: MusicDownloader   Author: wwwpf   File: netease.py    GNU General Public License v3.0 6 votes vote down vote up
def AES_encrypt(plain_text, key):
    '''本函数为以下js代码的python版本
    function b(a, b) {
        var c = CryptoJS.enc.Utf8.parse(b)
          , d = CryptoJS.enc.Utf8.parse("0102030405060708")
          , e = CryptoJS.enc.Utf8.parse(a)
          , f = CryptoJS.AES.encrypt(e, c, {
            iv: d,
            mode: CryptoJS.mode.CBC
        });
        return f.toString()
    }
    js中返回的密文是实际AES加密后再经过base64编码的数据。
    '''

    key_data = key.encode("utf-8")
    IV = "0102030405060708".encode("utf-8")
    cryptor = AES.new(key_data, AES.MODE_CBC, IV)

    padding_len = 16 - (len(plain_text) & 0xf)
    plain_data = (plain_text + chr(padding_len) * padding_len).encode("utf-8")
    cipher_data = cryptor.encrypt(plain_data)
    return base64.b64encode(cipher_data).decode("utf-8") 
Example 8
Project: BandwagongVPS_controller   Author: Pryriat   File: bwh_ctr.py    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    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: bitmm   Author: thmp   File: hitbtc.py    MIT License 6 votes vote down vote up
def sendSignedMessage(self, payload):
        message = {
            "apikey": self.api_key,
            "signature": "",
            "message": {
                "nonce": self.nonce,
                "payload": payload
            }
        }

        message["signature"] = base64.b64encode(hmac.new(self.secret, msg=json.dumps(message["message"], separators=(',', ':')), digestmod=hashlib.sha512).digest())

        #print json.dumps(message, separators=(',', ':'))
        self.sendMessage(json.dumps(message, separators=(',', ':')))

        self.nonce += 1 
Example 11
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: _netscaler.py    MIT License 6 votes vote down vote up
def http_request(self, api_endpoint, data_json=None):
        data_josn = {} if data_json is None else data_json

        request_url = self._nsc_protocol + '://' + self._nsc_host + self._nitro_base_url + api_endpoint

        data_json = urlencode(data_json)
        if not len(data_json):
            data_json = None

        auth = base64.b64encode(to_bytes('%s:%s' % (self._nsc_user, self._nsc_pass)).replace('\n', '').strip())
        headers = {
            'Authorization': 'Basic %s' % auth,
            'Content-Type': 'application/x-www-form-urlencoded',
        }

        response, info = fetch_url(self.module, request_url, data=data_json, headers=headers)

        return json.load(response) 
Example 12
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: slurp.py    MIT License 6 votes vote down vote up
def main():
    module = AnsibleModule(
        argument_spec=dict(
            src=dict(type='path', required=True, aliases=['path']),
        ),
        supports_check_mode=True,
    )
    source = module.params['src']

    if not os.path.exists(source):
        module.fail_json(msg="file not found: %s" % source)
    if not os.access(source, os.R_OK):
        module.fail_json(msg="file is not readable: %s" % source)

    data = base64.b64encode(open(source, 'rb').read())

    module.exit_json(content=data, source=source, encoding='base64') 
Example 13
Project: securionpay-python   Author: securionpay   File: checkout_request.py    MIT License 6 votes vote down vote up
def sign(checkout_request):
    try:
        basestring
    except NameError:
        basestring = str

    if not isinstance(checkout_request, basestring):
        checkout_request = json.dumps(
            checkout_request, sort_keys=True, separators=(",", ":")
        )

    digest = hmac.new(
        api.private_key.encode(),
        msg=checkout_request.encode(),
        digestmod=hashlib.sha256,
    ).hexdigest()
    return base64.b64encode((digest + "|" + checkout_request).encode()).decode() 
Example 14
Project: esp-sdk-python   Author: EvidentSecurity   File: api_authentication.py    MIT License 6 votes vote down vote up
def sign_request(self):
        """
        :return: Sign request takes pieces of information about the request and
        generates a hmac hash digest for authentication. This will return a
        base64 string of the digest
        :rtype: str
        """
        url = urlparse(self.url)
        uri = url.path
        if url.query != '':
            uri += '?{}'.format(url.query)
        canonical = '{method},{content_type},{md5},{uri},{date}'.format(
            method=self.method.upper(),
            content_type=CONTENT_TYPE,
            md5=self.body_md5(),
            uri=uri,
            date=self.date)
        digest = hmac.new(self.config.secret_access_key.encode('utf-8'),
                          canonical.encode('utf-8'),
                          digestmod=hashlib.sha1).digest()
        return 'APIAuth {access_key}:{signature}'.format(
            access_key=self.config.access_key_id,
            signature=base64.b64encode(digest).decode()) 
Example 15
Project: spqrel_tools   Author: LCAS   File: google_client.py    MIT License 6 votes vote down vote up
def recognize_data(self, data):
        try:
            print "[" + self.__class__.__name__ + "] [GOOGLE] Recognizing data.."
            transcriptions = []
            base64_data = base64.b64encode(data)
            audio_json = {"content": base64_data}
            config_json = {"languageCode": self.language}
            json_data = {"config": config_json, "audio": audio_json}
            response = requests.post(self.url, json=json_data, headers=self.headers, timeout=self.timeout)
            json_res = json.loads(response.text)
            print json_res
            if "results" in json_res.keys() and "alternatives" in json_res["results"][0].keys():
                for alternative in json_res["results"][0]["alternatives"]:
                    transcriptions.append(alternative["transcript"].lower())
            return transcriptions
        except ValueError as ve:
            print ve.message
            print "[" + self.__class__.__name__ + "] [RECOGNIZE]ERROR! Google APIs are temporary unavailable. Returning empty list.."
            return []
        except requests.exceptions.RequestException as e:
            print e.message
            print "[" + self.__class__.__name__ + "] [RECOGNIZE]ERROR! Unable to reach Google. Returning empty list.."
            return [] 
Example 16
Project: pnp   Author: HazardDede   File: utils.py    MIT License 6 votes vote down vote up
def load_file(fp: str, mode: str = 'auto', base64: bool = False) -> Dict[str, Any]:
    """
    Loads a file by the given file path into memory.
    The read mode can either be binary, text or auto. Auto will try to guess the read mode
    based on the files content.

    Args:
        fp (str): file path.
        mode (str): One of binary, text, auto
        base64 (bool): If True the content will be base64 encoded; otherwise not.
    """
    if not isinstance(base64, bool):
        raise TypeError("Argument 'base64' is expected to be a bool, but is {}".format(
            type(base64)
        ))
    mode = 'binary' if base64 else mode
    if mode not in FILE_MODES:
        raise ValueError("Argument 'mode' is expected to be one of: {}".format(FILE_MODES))

    read_mode = get_file_mode(fp, mode=mode)
    with open(fp, read_mode) as fstream:
        contents = b64encode(fstream.read()) if base64 else fstream.read()

    return dict(file_name=os.path.basename(fp), content=contents, mode=read_mode, base64=base64) 
Example 17
Project: saasy_boi   Author: netskopeoss   File: apis.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def imgur_upload_image(image_path, creds):
    url = "https://api.imgur.com/3/image"
    headers = {
        'user-agent': user_agent,
        'authorization': 'Client-ID {}'.format(creds)
    }

    try:
        r = requests.post(
            url,
            headers=headers,
            data={
                'image': base64.b64encode(open(image_path, 'rb').read()),
                'title': image_path
            }
        )

        data = r.json()
        return data['data']['link']

    except Exception:
        return "Upload failed" 
Example 18
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def get_tgz64(filenames):
    stream = io.BytesIO()
    tar = tarfile.open(fileobj=stream, mode='w:gz')
    for filename in filenames:
        if os.path.isfile(filename):
            tar.add(filename)
    tar.close()

    return base64.b64encode(stream.getvalue())


# Check services from the ntp packages for migration 
Example 19
Project: weibo-login   Author: littlepinecone   File: login.py    GNU General Public License v3.0 5 votes vote down vote up
def recombinePattern(img_data):
    # 返回的图片base64由两部分组成, 前面是打乱的图片,后面是打乱图片正确组合的次序
    img_data0 = img_data.split(',')[1].split('|')[0]
    img_data1 = img_data.split(',')[1].split('|')[1]

    file = open('original.png', 'wb')
    file.write(base64.b64decode(img_data0))
    file.close()
    # 分割打乱的图片
    img = Image.open("original.png")
    for y in range(0, 5):
        for x in range(1, 6):
            combine = img.crop((32 * (x - 1), 32 * y, 32 * x, 32 * (y + 1)))
            combine.save(str(x + 5 * y) + ".png")
    # 重新组合图片
    outImage = Image.new('RGBA', (160, 160))
    noo = 0
    for i in base64decode(img_data1):
        no = int(i)

        # print no
        fromImge = Image.open(str(no + 1) + ".png")
        # loc = ((i % 2) * 200, (int(i/2) * 200))
        loc = (((noo % 5) * 32), (int(noo / 5)) * 32)
        # print noo
        noo += 1
        # print(loc)
        outImage.paste(fromImge, loc)

    outImage = outImage.convert('L')
    # outImage = outImage.resize((64, 64), Image.ANTIALIAS)
    outImage.save('merged.png')
    # print type(outImage)
    buffer = cStringIO.StringIO()
    outImage.save(buffer, format="png")
    img_base64 = base64.b64encode(buffer.getvalue())
    return img_base64


# 通过截取特定的小区域与预先处理的24种情形对比来识别验证码 
Example 20
Project: jumpserver-python-sdk   Author: jumpserver   File: utils.py    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 21
Project: hydrus   Author: HTTP-APIs   File: user.py    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 22
Project: phrydy   Author: Josef-Friedrich   File: mediafile.py    MIT License 5 votes vote down vote up
def serialize(self, image):
        """Turn a Image into a base64 encoded FLAC picture block.
        """
        pic = mutagen.flac.Picture()
        pic.data = image.data
        pic.type = image.type_index
        pic.mime = image.mime_type
        pic.desc = image.desc or u''

        # Encoding with base64 returns bytes on both Python 2 and 3.
        # Mutagen requires the data to be a Unicode string, so we decode
        # it before passing it along.
        return base64.b64encode(pic.write()).decode('ascii') 
Example 23
Project: pepper-robot-programming   Author: maverickjoy   File: asthama_search.py    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 24
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def proxy_open(self, req, proxy, type):
        orig_type = req.get_type()
        proxy_type, user, password, hostport = _parse_proxy(proxy)

        if proxy_type is None:
            proxy_type = orig_type

        if req.host and proxy_bypass(req.host):
            return None

        if user and password:
            user_pass = '%s:%s' % (unquote(user), unquote(password))
            creds = base64.b64encode(user_pass).strip()
            req.add_header('Proxy-authorization', 'Basic ' + creds)
        hostport = unquote(hostport)
        req.set_proxy(hostport, proxy_type)

        if orig_type == proxy_type or orig_type == 'https':
            # let other handlers take care of it
            return None
        else:
            # need to start over, because the other handlers don't
            # grok the proxy's URL type
            # e.g. if we have a constructor arg proxies like so:
            # {'http': 'ftp://proxy.example.com'}, we may end up turning
            # a request for http://acme.example.com/a into one for
            # ftp://proxy.example.com/a
            return self.parent.open(req, timeout=req.timeout) 
Example 25
Project: pyblish-win   Author: pyblish   File: urllib2.py    GNU Lesser General Public License v3.0 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 is not None:
            raw = "%s:%s" % (user, pw)
            auth = 'Basic %s' % base64.b64encode(raw).strip()
            if req.get_header(self.auth_header, None) == auth:
                return None
            req.add_unredirected_header(self.auth_header, auth)
            return self.parent.open(req, timeout=req.timeout)
        else:
            return None 
Example 26
Project: pyblish-win   Author: pyblish   File: test_base64.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_b64encode(self):
        eq = self.assertEqual
        # Test default alphabet
        eq(base64.b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
        eq(base64.b64encode('\x00'), 'AA==')
        eq(base64.b64encode("a"), "YQ==")
        eq(base64.b64encode("ab"), "YWI=")
        eq(base64.b64encode("abc"), "YWJj")
        eq(base64.b64encode(""), "")
        eq(base64.b64encode("abcdefghijklmnopqrstuvwxyz"
                            "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                            "[email protected]#0^&*();:<>,. []{}"),
           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
        # Test with arbitrary alternative characters
        eq(base64.b64encode('\xd3V\xbeo\xf7\x1d', altchars='*$'), '01a*b$cd')
        # Non-bytes
        eq(base64.b64encode(bytearray('abcd')), 'YWJjZA==')
        self.assertRaises(TypeError, base64.b64encode,
                          '\xd3V\xbeo\xf7\x1d', altchars=bytearray('*$'))
        # Test standard alphabet
        eq(base64.standard_b64encode("www.python.org"), "d3d3LnB5dGhvbi5vcmc=")
        eq(base64.standard_b64encode("a"), "YQ==")
        eq(base64.standard_b64encode("ab"), "YWI=")
        eq(base64.standard_b64encode("abc"), "YWJj")
        eq(base64.standard_b64encode(""), "")
        eq(base64.standard_b64encode("abcdefghijklmnopqrstuvwxyz"
                                     "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
                                     "[email protected]#0^&*();:<>,. []{}"),
           "YWJjZGVmZ2hpamtsbW5vcHFyc3R1dnd4eXpBQkNE"
           "RUZHSElKS0xNTk9QUVJTVFVWV1hZWjAxMjM0NT"
           "Y3ODkhQCMwXiYqKCk7Ojw+LC4gW117fQ==")
        # Non-bytes
        eq(base64.standard_b64encode(bytearray('abcd')), 'YWJjZA==')
        # Test with 'URL safe' alternative characters
        eq(base64.urlsafe_b64encode('\xd3V\xbeo\xf7\x1d'), '01a-b_cd')
        # Non-bytes
        eq(base64.urlsafe_b64encode(bytearray('\xd3V\xbeo\xf7\x1d')), '01a-b_cd') 
Example 27
Project: pyblish-win   Author: pyblish   File: test_httpservers.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_authorization(self):
        headers = {'Authorization' : 'Basic %s' %
                   base64.b64encode('username:pass')}
        res = self.request('/cgi-bin/file1.py', 'GET', headers=headers)
        self.assertEqual(('Hello World\n', 'text/html', 200),
                (res.read(), res.getheader('Content-type'), res.status)) 
Example 28
Project: WebTeam   Author: shashankrnr32   File: Encryption.py    MIT License 5 votes vote down vote up
def encrypt(Ukey,Pkey,username,password):
    for i in range(1,Ukey):
        username = base64.b64encode(username)
    for i in range(1,Pkey):
        password = base64.b64encode(password)
    return Ukey,Pkey,username,password 
Example 29
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 5 votes vote down vote up
def calculateSignature(string, private_key):
    hash_var = hmac.new(private_key, string, hashlib.sha1).digest()
    sig = urllib.parse.quote_plus(base64.b64encode(hash_var))
    return sig 
Example 30
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 5 votes vote down vote up
def calculateSignature(string, private_key):
    hash_var = hmac.new(private_key, string, hashlib.sha1).digest()
    sig = urllib.parse.quote_plus(base64.b64encode(hash_var))
    return sig 
Example 31
Project: WebTeam   Author: shashankrnr32   File: GenerateAPI.py    MIT License 5 votes vote down vote up
def calculateSignature(string, private_key):
    hash_var = hmac.new(private_key, string, hashlib.sha1).digest()
    sig = urllib.parse.quote_plus(base64.b64encode(hash_var))
    return sig 
Example 32
Project: drydock   Author: airshipit   File: bootaction.py    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 33
Project: drydock   Author: airshipit   File: machine.py    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 34
Project: drydock   Author: airshipit   File: test_bootaction_pipeline.py    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 35
Project: drydock   Author: airshipit   File: test_reference_resolver.py    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:[email protected]/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 36
Project: robust-atd   Author: shadowbq   File: __init__.py    MIT License 5 votes vote down vote up
def b64(self, user, password):
        '''
        Description: Internal procedure to get the base64 values used for authentication
        Input:       user and password
        Output:      base64('user:pass'): The dic includes all the json report
        '''
        import base64
        auth_string = user + ':' + password
        return base64.b64encode(auth_string) 
Example 37
Project: ihtml   Author: thedataincubator   File: ihtmlmagic.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def ihtml(self, line, cell):
        height = int(line or 400)
        url = "data:text/html;base64," + base64.b64encode(self.var_re.sub(self.var_replace, cell).encode('utf-8')).decode('utf-8')
        display_html(IFrame(url, "100%", height)) 
Example 38
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: securecookie.py    Apache License 2.0 5 votes vote down vote up
def quote(cls, value):
        """Quote the value for the cookie.  This can be any object supported
        by :attr:`serialization_method`.

        :param value: the value to quote.
        """
        if cls.serialization_method is not None:
            value = cls.serialization_method.dumps(value)
        if cls.quote_base64:
            value = b''.join(base64.b64encode(value).splitlines()).strip()
        return value 
Example 39
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: securecookie.py    Apache License 2.0 5 votes vote down vote up
def serialize(self, expires=None):
        """Serialize the secure cookie into a string.

        If expires is provided, the session will be automatically invalidated
        after expiration when you unseralize it. This provides better
        protection against session cookie theft.

        :param expires: an optional expiration date for the cookie (a
                        :class:`datetime.datetime` object)
        """
        if self.secret_key is None:
            raise RuntimeError('no secret key defined')
        if expires:
            self['_expires'] = _date_to_unix(expires)
        result = []
        mac = hmac(self.secret_key, None, self.hash_method)
        for key, value in sorted(self.items()):
            result.append(('%s=%s' % (
                url_quote_plus(key),
                self.quote(value).decode('ascii')
            )).encode('ascii'))
            mac.update(b'|' + result[-1])
        return b'?'.join([
            base64.b64encode(mac.digest()).strip(),
            b'&'.join(result)
        ]) 
Example 40
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: securecookie.py    Apache License 2.0 5 votes vote down vote up
def quote(cls, value):
        """Quote the value for the cookie.  This can be any object supported
        by :attr:`serialization_method`.

        :param value: the value to quote.
        """
        if cls.serialization_method is not None:
            value = cls.serialization_method.dumps(value)
        if cls.quote_base64:
            value = b''.join(base64.b64encode(value).splitlines()).strip()
        return value 
Example 41
Project: Flask-Python-GAE-Login-Registration   Author: orymeyer   File: securecookie.py    Apache License 2.0 5 votes vote down vote up
def serialize(self, expires=None):
        """Serialize the secure cookie into a string.

        If expires is provided, the session will be automatically invalidated
        after expiration when you unseralize it. This provides better
        protection against session cookie theft.

        :param expires: an optional expiration date for the cookie (a
                        :class:`datetime.datetime` object)
        """
        if self.secret_key is None:
            raise RuntimeError('no secret key defined')
        if expires:
            self['_expires'] = _date_to_unix(expires)
        result = []
        mac = hmac(self.secret_key, None, self.hash_method)
        for key, value in sorted(self.items()):
            result.append(('%s=%s' % (
                url_quote_plus(key),
                self.quote(value).decode('ascii')
            )).encode('ascii'))
            mac.update(b'|' + result[-1])
        return b'?'.join([
            base64.b64encode(mac.digest()).strip(),
            b'&'.join(result)
        ]) 
Example 42
Project: shelter   Author: seznam   File: processes.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def loop(self):
        self.context.value = base64.b64encode(os.urandom(6)) 
Example 43
Project: pywarp   Author: pyauth   File: __init__.py    Apache License 2.0 5 votes vote down vote up
def b64_encode(b):
    return base64.b64encode(b).decode() 
Example 44
Project: pyserverchan   Author: GanjinZero   File: pyserver.py    MIT License 5 votes vote down vote up
def output_to_weixin_picture(self, picture, title='Picture'):
        # picture: A network address or a local address
        # local picture max size 7kb
        if check_is_web(picture):
            content = '![' + title + '](' + picture + ')'
        else:
            with open(picture, 'rb') as pic:
                picture_type = picture.split(".")[-1]
                base64pic = base64.b64encode(pic.read())
                base64str = str(base64pic)[2:-1]
                content = '![' + title + '][link1]' + os.linesep + os.linesep
                content += '[link1]:data:image/' + picture_type + ';base64,' + base64str
        requests.get(self.url, params={'text':title, 'desp':content}) 
Example 45
Project: azure-iot-rest   Author: jongio   File: module-twin.py    MIT License 5 votes vote down vote up
def get_iot_hub_sas_token(uri, key, policy_name, expiry=3600):
    ttl = time() + expiry
    sign_key = "%s\n%d" % ((quote(uri)), int(ttl))
    signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())

    rawtoken = {
        'sr' :  uri,
        'sig': signature,
        'se' : str(int(ttl))
    }

    if policy_name is not None:
        rawtoken['skn'] = policy_name

    return 'SharedAccessSignature ' + urlencode(rawtoken) 
Example 46
Project: azure-iot-rest   Author: jongio   File: modules.py    MIT License 5 votes vote down vote up
def get_iot_hub_sas_token(uri, key, policy_name, expiry=3600):
    ttl = time() + expiry
    sign_key = "%s\n%d" % ((quote(uri)), int(ttl))
    signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())

    rawtoken = {
        'sr' :  uri,
        'sig': signature,
        'se' : str(int(ttl))
    }

    if policy_name is not None:
        rawtoken['skn'] = policy_name

    return 'SharedAccessSignature ' + urlencode(rawtoken) 
Example 47
Project: azure-iot-rest   Author: jongio   File: device-conf.py    MIT License 5 votes vote down vote up
def get_iot_hub_sas_token(uri, key, policy_name, expiry=3600):
    ttl = time() + expiry
    sign_key = "%s\n%d" % ((quote(uri)), int(ttl))
    signature = b64encode(HMAC(b64decode(key), sign_key.encode('utf-8'), sha256).digest())

    rawtoken = {
        'sr' :  uri,
        'sig': signature,
        'se' : str(int(ttl))
    }

    if policy_name is not None:
        rawtoken['skn'] = policy_name

    return 'SharedAccessSignature ' + urlencode(rawtoken) 
Example 48
Project: azure-iot-rest   Author: jongio   File: file-upload.py    MIT License 5 votes vote down vote up
def get_iot_hub_sas_token(uri, key, policy_name, expiry=3600):
    ttl = time() + expiry
    sign_key = "%s\n%d" % ((quote_plus(uri)), int(ttl))
    signature = b64encode(HMAC(b64decode(key), sign_key, sha256).digest())

    rawtoken = {
        'sr' :  uri,
        'sig': signature,
        'se' : str(int(ttl))
    }

    if policy_name is not None:
        rawtoken['skn'] = policy_name

    return 'SharedAccessSignature ' + urlencode(rawtoken) 
Example 49
Project: slidoc   Author: mitotic   File: sdserver.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def site_cookie_data(self):
        siteName = Options['site_name'] or ''
        cookie_data = {'version': COOKIE_VERSION, 'site': siteName, 'pluginDataPath': '/'+PLUGINDATA_PATH}
        if Options['source_dir']:
            cookie_data['editable'] = 'edit'

        siteMenu = SiteProps.get_site_menu()
        if 'gradebook' in siteMenu:
            cookie_data['gradebook'] = 1
        if 'files' in siteMenu:
            cookie_data['files'] = 1

        return sliauth.safe_quote( base64.b64encode(json.dumps(cookie_data,sort_keys=True)) ) 
Example 50
Project: slidoc   Author: mitotic   File: md2nb.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def external_link(self, line, text, link, title):
        nb_output_append = title.startswith('nb_output') and self.cells_buffer and self.cells_buffer[-1]['cell_type'] == 'code'
        if line.lstrip().startswith('!') and (self.cmd_args.embed_images or nb_output_append):
            fpath = link
            if self.filedir:
                fpath = self.filedir + '/' + fpath
            _, extn = os.path.splitext(os.path.basename(fpath))
            extn = extn.lower()
            if extn in ('.gif', '.jpg', '.jpeg', '.png', '.svg'):
                content_type = 'image/jpeg' if extn == '.jpg' else 'image/'+extn[1:]
                if self.cmd_args.image_dir:
                    fpath =  os.path.join(self.cmd_args.image_dir, os.path.basename(fpath))
                with open(fpath) as f:
                    content = f.read()
                attachment_name =  os.path.basename(fpath)
                img_md = '![%s](attachment:%s)\n' % (text, attachment_name)
                img_content = self.image_output(text, content_type, base64.b64encode(content), attachment=not nb_output_append)
                if nb_output_append:
                    self.cells_buffer[-1]['outputs'].append(img_content)
                elif self.cells_buffer and self.cells_buffer[-1]['cell_type'] == 'markdown':
                    self.cells_buffer[-1]['source'].append(img_md)
                    self.cells_buffer[-1]['attachments'][attachment_name] = img_content
                else:
                    self.cells_buffer += {"cell_type" : "markdown",
                                          "metadata" : {},
                                          "source" : [img_md],
                                          "attachments" : {attachment_name: img_content} }
            else:
                self.buffered_lines.append(line)
        else:
            self.buffered_lines.append(line)