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: securionpay-python   Author: securionpay   File: checkout_request.py    MIT License 7 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 3
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 4
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 5
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 6
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 7
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 8
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 9
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 10
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 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: 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 14
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 15
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 16
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 17
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 18
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 19
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 20
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 21
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 22
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 23
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 24
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 25
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"
                            "0123456789!@#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"
                                     "0123456789!@#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 26
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 27
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 28
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 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: 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 32
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 33
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 34
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: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 35
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 36
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 37
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 38
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 39
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 40
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 41
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 42
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 43
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 44
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 45
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 46
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 47
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 48
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 49
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) 
Example 50
Project: slidoc   Author: mitotic   File: sdviewer.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def gen_hmac_token(message):
    token = base64.b64encode(hmac.new(HMAC_KEY, message, hashlib.md5).digest())
    return token[:TRUNCATE_DIGEST] 
Example 51
Project: annots   Author: Infernion   File: travis_pypi_setup.py    MIT License 5 votes vote down vote up
def encrypt(pubkey, password):
    """Encrypt password using given RSA public key and encode it with base64.

    The encrypted password can only be decrypted by someone with the
    private key (in this case, only Travis).
    """
    key = load_key(pubkey)
    encrypted_password = key.encrypt(password, PKCS1v15())
    return base64.b64encode(encrypted_password) 
Example 52
Project: pytuber   Author: tefra   File: models.py    MIT License 5 votes vote down vote up
def mime(self):
        return base64.b64encode(
            json.dumps(
                {
                    field: getattr(self, field)
                    for field in ["arguments", "provider", "type", "title"]
                }
            ).encode()
        ).decode("utf-8") 
Example 53
Project: BandwagongVPS_controller   Author: Pryriat   File: bwh_lg.py    GNU General Public License v3.0 5 votes vote down vote up
def login_event(self):
        '''将登陆窗体的信息写入本地配置文件'''
        self.file = open(".\data.ini",'wb')
        #使用base64编码防止明文存储
        self.data = base64.b64encode(json.dumps({'name':'新建主机','veid':self.veid_input.text(),'api':self.api_input.text(),'lan':self.lan_input.currentIndex()}).encode())
        global web_payload
        web_payload = {'veid':self.veid_input.text(),'api_key':self.api_input.text()}
        self.file.write(base64.b64encode('1'.encode()))
        self.file.write('\n'.encode())
        self.file.write(self.data)
        self.file.close()
        self.accept() 
Example 54
Project: BandwagongVPS_controller   Author: Pryriat   File: bwh_add_host.py    GNU General Public License v3.0 5 votes vote down vote up
def bwh_add_event(self):
        self.ns = True
        if self.api_input.text() == '' or self.veid_input.text() == '':
            a = QMessageBox()
            a.critical(a,self.tr("Error","api or veid empty!"))
            self.close()
        elif self.name_input.text() == '':
            self.name_input.setText(self.tr("new host"))
        with open('data.ini','ab') as f:
            self.data = base64.b64encode(json.dumps({'name':self.name_input.text(),'veid':self.veid_input.text(),'api':self.api_input.text(),'lan':self.lan}).encode())
            f.write('\n'.encode())
            f.write(self.data)
        self.accept() 
Example 55
Project: bitmm   Author: thmp   File: hitbtc.py    MIT License 5 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 56
Project: camect-py   Author: camect   File: __init__.py    MIT License 5 votes vote down vote up
def _authorization(self) -> str:
        return base64.b64encode(f"{self._user}:{self._password}".encode()).decode() 
Example 57
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: encoding.py    MIT License 5 votes vote down vote up
def encode(data):
        return base64.b64encode(data) 
Example 58
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: low_level.py    MIT License 5 votes vote down vote up
def _temporary_keychain():
    """
    This function creates a temporary Mac keychain that we can use to work with
    credentials. This keychain uses a one-time password and a temporary file to
    store the data. We expect to have one keychain per socket. The returned
    SecKeychainRef must be freed by the caller, including calling
    SecKeychainDelete.

    Returns a tuple of the SecKeychainRef and the path to the temporary
    directory that contains it.
    """
    # Unfortunately, SecKeychainCreate requires a path to a keychain. This
    # means we cannot use mkstemp to use a generic temporary file. Instead,
    # we're going to create a temporary directory and a filename to use there.
    # This filename will be 8 random bytes expanded into base64. We also need
    # some random bytes to password-protect the keychain we're creating, so we
    # ask for 40 random bytes.
    random_bytes = os.urandom(40)
    filename = base64.b64encode(random_bytes[:8]).decode('utf-8')
    password = base64.b64encode(random_bytes[8:])  # Must be valid UTF-8
    tempdirectory = tempfile.mkdtemp()

    keychain_path = os.path.join(tempdirectory, filename).encode('utf-8')

    # We now want to create the keychain itself.
    keychain = Security.SecKeychainRef()
    status = Security.SecKeychainCreate(
        keychain_path,
        len(password),
        password,
        False,
        None,
        ctypes.byref(keychain)
    )
    _assert_no_error(status)

    # Having created the keychain, we want to pass it off to the caller.
    return keychain, tempdirectory 
Example 59
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: grafana_datasource.py    MIT License 5 votes vote down vote up
def grafana_delete_datasource(module, data):

    # define http headers
    headers = {'content-type': 'application/json'}
    if 'grafana_api_key' in data and data['grafana_api_key']:
        headers['Authorization'] = "Bearer %s" % data['grafana_api_key']
    else:
        auth = base64.b64encode(to_bytes('%s:%s' % (data['grafana_user'], data['grafana_password'])).replace('\n', ''))
        headers['Authorization'] = 'Basic %s' % auth
        grafana_switch_organisation(module, data['grafana_url'], data['org_id'], headers)

    # test if datasource already exists
    datasource_exists, ds = grafana_datasource_exists(module, data['grafana_url'], data['name'], headers=headers)

    result = {}
    if datasource_exists is True:
        # delete
        r, info = fetch_url(module, '%s/api/datasources/name/%s' % (data['grafana_url'], data['name']), headers=headers, method='DELETE')
        if info['status'] == 200:
            res = json.loads(r.read())
            result['msg'] = "Datasource %s deleted : %s" % (data['name'], res['message'])
            result['changed'] = True
            result['name'] = data['name']
            result['id'] = 0
        else:
            raise GrafanaAPIException('Unable to update the datasource id %s : %s' % (ds['id'], info))
    else:
        # datasource does not exist, do nothing
        result = {'msg': "Datasource %s does not exist." % data['name'],
                  'changed': False,
                  'id': 0,
                  'name': data['name']}

    return result 
Example 60
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: grafana_dashboard.py    MIT License 5 votes vote down vote up
def grafana_delete_dashboard(module, data):

    # define http headers
    headers = {'content-type': 'application/json'}
    if 'grafana_api_key' in data and data['grafana_api_key']:
        headers['Authorization'] = "Bearer %s" % data['grafana_api_key']
    else:
        auth = base64.b64encode(to_bytes('%s:%s' % (data['grafana_user'], data['grafana_password'])).replace('\n', ''))
        headers['Authorization'] = 'Basic %s' % auth
        grafana_switch_organisation(module, data['grafana_url'], data['org_id'], headers)

    # test if dashboard already exists
    dashboard_exists, dashboard = grafana_dashboard_exists(module, data['grafana_url'], data['slug'], headers=headers)

    result = {}
    if dashboard_exists is True:
        # delete
        r, info = fetch_url(module, '%s/api/dashboards/db/%s' % (data['grafana_url'], data['slug']), headers=headers, method='DELETE')
        if info['status'] == 200:
            result['msg'] = "Dashboard %s deleted" % data['slug']
            result['changed'] = True
            result['slug'] = data['slug']
        else:
            raise GrafanaAPIException('Unable to update the dashboard %s : %s' % (data['slug'], info))
    else:
        # dashboard does not exist, do nothing
        result = {'msg': "Dashboard %s does not exist." % data['slug'],
                  'changed': False,
                  'slug': data['slug']}

    return result 
Example 61
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pagerduty.py    MIT License 5 votes vote down vote up
def auth_header(user, passwd, token):
    if token:
        return "Token token=%s" % token

    auth = base64.b64encode(to_bytes('%s:%s' % (user, passwd)).replace('\n', ''))
    return "Basic %s" % auth 
Example 62
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: cs_instance.py    MIT License 5 votes vote down vote up
def get_user_data(self):
        user_data = self.module.params.get('user_data')
        if user_data is not None:
            user_data = to_text(base64.b64encode(to_bytes(user_data)))
        return user_data 
Example 63
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: lambda.py    MIT License 5 votes vote down vote up
def sha256sum(filename):
    hasher = hashlib.sha256()
    with open(filename, 'rb') as f:
        hasher.update(f.read())

    code_hash = hasher.digest()
    code_b64 = base64.b64encode(code_hash)
    hex_digest = code_b64.decode('utf-8')

    return hex_digest 
Example 64
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: vr_server.py    MIT License 5 votes vote down vote up
def get_user_data(self):
        user_data = self.module.params.get('user_data')
        if user_data is not None:
            user_data = to_text(base64.b64encode(to_bytes(user_data)))
        return user_data 
Example 65
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: github_hooks.py    MIT License 5 votes vote down vote up
def request(module, url, user, oauthkey, data='', method='GET'):
    auth = base64.b64encode(to_bytes('%s:%s' % (user, oauthkey)).replace('\n', ''))
    headers = {
        'Authorization': 'Basic %s' % auth,
    }
    response, info = fetch_url(module, url, headers=headers, data=data, method=method)
    return response, info 
Example 66
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: letsencrypt.py    MIT License 5 votes vote down vote up
def _der_to_pem(self, der_cert):
        '''
        Convert the DER format certificate in der_cert to a PEM format
        certificate and return it.
        '''
        return """-----BEGIN CERTIFICATE-----\n{0}\n-----END CERTIFICATE-----\n""".format(
            "\n".join(textwrap.wrap(base64.b64encode(der_cert).decode('utf8'), 64))) 
Example 67
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: jira.py    MIT License 5 votes vote down vote up
def request(url, user, passwd, timeout, data=None, method=None):
    if data:
        data = json.dumps(data)

    # NOTE: fetch_url uses a password manager, which follows the
    # standard request-then-challenge basic-auth semantics. However as
    # JIRA allows some unauthorised operations it doesn't necessarily
    # send the challenge, so the request occurs as the anonymous user,
    # resulting in unexpected results. To work around this we manually
    # inject the basic-auth header up-front to ensure that JIRA treats
    # the requests as authorized for this user.
    auth = to_text(base64.b64encode(to_bytes('{0}:{1}'.format(user, passwd), errors='surrogate_or_strict')))

    response, info = fetch_url(module, url, data=data, method=method, timeout=timeout,
                               headers={'Content-Type': 'application/json',
                                        'Authorization': "Basic %s" % auth})

    if info['status'] not in (200, 201, 204):
        module.fail_json(msg=info['msg'])

    body = response.read()

    if body:
        return json.loads(body)
    else:
        return {} 
Example 68
Project: friendly-telegram   Author: friendly-telegram   File: core.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def send_code(self, request):
        uid = int(await request.text())
        if uid in self.uid_to_code.keys():
            return web.Response()
        code = secrets.randbelow(100000)
        asyncio.ensure_future(asyncio.shield(self._clear_code(uid)))
        self.uid_to_code[uid] = b64encode(hashlib.scrypt((str(code).zfill(5) + str(uid)).encode("utf-8"),
                                                         salt="friendlytgbot".encode("utf-8"),
                                                         n=16384, r=8, p=1, dklen=64)).decode("utf-8")
        await self.client_data[uid][1].send_message("me", "Your code is <code>{:05d}</code>\nDo <b>not</b> "
                                                          "share this code with anyone, even is they say they are"
                                                          " from friendly-telegram.\nThe code will expire in "
                                                          "2 minutes.".format(code))
        return web.Response() 
Example 69
Project: esp-sdk-python   Author: EvidentSecurity   File: api_authentication.py    MIT License 5 votes vote down vote up
def body_md5(self):
        """
        :return: A base64 string of the content body passed in.
        :rtype: str
        """
        if not self.body:
            body = ''
        else:
            body = json.dumps(self.body)
        body_bytes = body.encode('utf-8')
        b64 = base64.b64encode(hashlib.md5(body_bytes).digest())
        return b64.decode() 
Example 70
Project: L   Author: vaultah   File: auth.py    MIT License 5 votes vote down vote up
def _prehash(pwd):
    dig = _algo(bytes(pwd, 'utf-8')).digest()
    return base64.b64encode(dig)[:72] 
Example 71
Project: telegram-repeater   Author: googlehosts   File: customservice.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, msg: Message, section: str, status: str):
		self._origin_msg = build_html_parse(msg).parsed_msg
		self.hash_value = custom_service_bot_class.hash_msg(msg)
		self.section = section
		self.status = status
		self.sql = "INSERT INTO `tickets` (`user_id`, `hash`, `timestamp`, `origin_msg`, `section`, `status`) VALUES ({0}, '{1}', CURRENT_TIMESTAMP(), '{2}', '{3}', '{4}')".format(
			msg.chat.id, self.hash_value, base64.b64encode(self._origin_msg.encode()).decode(), self.section, self.status
		) 
Example 72
Project: pnp   Author: HazardDede   File: selector.py    MIT License 5 votes vote down vote up
def _register_globals(self) -> None:
        self._custom["abs"] = abs
        self._custom["bool"] = bool
        self._custom["dict"] = dict
        self._custom["float"] = float
        self._custom["getattr"] = getattr
        self._custom["hasattr"] = hasattr
        self._custom["hash"] = hash
        self._custom["int"] = int
        self._custom["isinstance"] = isinstance
        self._custom["len"] = len
        self._custom["list"] = list
        self._custom["max"] = max
        self._custom["min"] = min
        self._custom["ord"] = ord
        self._custom["pow"] = pow
        self._custom["reversed"] = reversed
        self._custom["round"] = round
        self._custom["sorted"] = sorted
        self._custom["str"] = str
        self._custom["zip"] = zip

        from base64 import b64encode, b64decode
        self._custom["b64encode"] = b64encode
        self._custom["b64decode"] = b64decode
        import os
        self._custom["basename"] = os.path.basename
        from .utils import on_off
        self._custom["on_off"] = on_off 
Example 73
Project: flasky   Author: RoseOu   File: compat.py    MIT License 5 votes vote down vote up
def b64encode(x):
        return base64.b64encode(x).decode('ascii') 
Example 74
Project: hydrus   Author: HTTP-APIs   File: test_auth.py    MIT License 4 votes vote down vote up
def setUpClass(self):
        """Database setup before the tests."""
        print("Creating a temporary datatbase...")
        engine = create_engine('sqlite:///:memory:')
        Base.metadata.create_all(engine)
        session = scoped_session(sessionmaker(bind=engine))

        self.session = session
        self.API_NAME = "demoapi"
        self.HYDRUS_SERVER_URL = "http://hydrus.com/"
        self.app = app_factory(self.API_NAME)
        self.doc = doc_maker.create_doc(
            doc_writer_sample.api_doc.generate(), self.HYDRUS_SERVER_URL, self.API_NAME)

        test_classes = doc_parse.get_classes(self.doc.generate())
        test_properties = doc_parse.get_all_properties(test_classes)
        doc_parse.insert_classes(test_classes, self.session)
        doc_parse.insert_properties(test_properties, self.session)
        add_user(1, "test", self.session)
        self.auth_header = {"X-Authentication": "",
                            "Authorization": "Basic {}".format(
                                b64encode(b"1:test").decode("ascii"))}
        self.wrong_id = {"X-Authentication": "",
                         "Authorization": "Basic {}".format(b64encode(b"2:test").decode("ascii"))}
        self.wrong_pass = {"X-Authentication": "",
                           "Authorization": "Basic {}".format(
                               b64encode(b"1:test2").decode("ascii"))}
        print("Classes, Properties and Users added successfully.")

        print("Setting up Hydrus utilities... ")
        self.api_name_util = set_api_name(self.app, self.API_NAME)
        self.session_util = set_session(self.app, self.session)
        self.doc_util = set_doc(self.app, self.doc)
        self.auth_util = set_authentication(self.app, True)
        self.token_util = set_token(self.app, False)
        self.client = self.app.test_client()

        print("Creating utilities context... ")
        self.api_name_util.__enter__()
        self.session_util.__enter__()
        self.doc_util.__enter__()
        self.auth_util.__enter__()
        self.token_util.__enter__()
        self.client.__enter__()

        print("Setup done, running tests...") 
Example 75
Project: backtrader-cn   Author: pandalibin   File: sina.py    GNU General Public License v3.0 4 votes vote down vote up
def login(self, username, password):
        """
        # 新浪微博登录
        :param username: 微博手机号
        :param password: 微博密码
        :return:
        """
        if username == "" or password == "":
            raise StockMatchError("用户名或密码不能为空")
        post_data = {
            "entry": "finance",
            "gateway": "1",
            "from": None,
            "savestate": "30",
            "qrcode_flag": True,
            "useticket": "0",
            "pagerefer": "http://jiaoyi.sina.com.cn/jy/index.php",
            "vsnf": "1",
            "su": base64.b64encode(username.encode("utf-8")).decode("utf-8"),
            "service": "sso",
            "servertime": get_unix_timestamp(False),
            "nonce": "RA12UM",
            # "pwencode": "rsa2",  # 取消掉使用rsa2加密密码
            "sp": password,
            "sr": "1280*800",
            "encoding": "UTF-8",
            "cdult": "3",
            "domain": "sina.com.cn",
            "prelt": "56",
            "returntype": "TEXT",
        }
        session = requests.Session()
        session.headers.update(conf.SINA_CONFIG["request_headers"])
        res = session.post(conf.SINA_CONFIG["login_url"], data=post_data, params={
            "client": "ssologin.js(v1.4.19)",
            "_": get_unix_timestamp(),
        })
        res.encoding = "gb2312"
        info = json.loads(res.content)
        if info["retcode"] != "0":
            logger.error(info["reason"])
            raise LoginFailedError(info["reason"])
        logger.info("用户%s登录成功" % username)
        return session, info['uid'] 
Example 76
Project: everyclass-server   Author: everyclass   File: session.py    Mozilla Public License 2.0 4 votes vote down vote up
def save_session(self, app, session, response):
        """
        @param app: Flask app
        @param session: Flask / Werkzeug Session
        @param response: Flask HTTP Response
        @summary: Saves the current session. This overrides the default Flask implementation, adding
        AES encryption of the client-side session cookie.
        """

        domain = self.get_cookie_domain(app)
        if not session:
            if session.modified:
                response.delete_cookie(app.session_cookie_name, domain=domain)
            return
        expires = self.get_expiration_time(app, session)

        # Decide whether to compress
        bdict = pickle.dumps(dict(session))
        if len(bdict) > self.compress_threshold:
            prefix = "z"  # session cookie for compressed data starts with "z."
            bdict = zlib.compress(bdict)
        else:
            prefix = "u"  # session cookie for uncompressed data starts with "u."

        # Get the crypto key
        crypto_key = app.config['SESSION_CRYPTO_KEY'] if 'SESSION_CRYPTO_KEY' in app.config else app.crypto_key

        # Encrypt using AES in EAX mode
        cipher = AES.new(crypto_key, AES.MODE_EAX)
        ciphertext, mac = cipher.encrypt_and_digest(bdict)
        nonce = cipher.nonce

        # Convert the ciphertext, mac, and nonce to base64
        b64_ciphertext = base64.b64encode(ciphertext)
        b64_mac = base64.b64encode(mac)
        b64_nonce = base64.b64encode(nonce)

        # Create the session cookie as <u|z>.<base64 cipher text>.<base64 mac>.<base64 nonce>
        tup = [prefix, b64_ciphertext.decode(), b64_mac.decode(), b64_nonce.decode()]
        session_cookie = ".".join(tup)

        # Set the session cookie
        response.set_cookie(self.session_cookie_name, session_cookie,
                            expires=expires, httponly=True,
                            domain=domain) 
Example 77
Project: btcchina-api-python-3   Author: aeromomo   File: btcchina.py    MIT License 4 votes vote down vote up
def _private_request(self,post_data):
        #fill in common post_data parameters
        tonce=self._get_tonce()
        post_data['tonce']=tonce
        post_data['accesskey']=self.access_key.decode()
        post_data['requestmethod']='post'
        # If ID is not passed as a key of post_data, just use tonce
        if not 'id' in post_data:
            post_data['id']=tonce
        pd_hash=self._get_params_hash(post_data)
        # must use b64 encode
        # print(self.access_key)
        # print(pd_hash)
        # print()
        # auth_string='Basic '+base64.b64encode(self.access_key+':'+pd_hash)
        auth_string=b'Basic '+base64.b64encode(self.access_key + b":" + pd_hash.encode('utf-8'))
        auth_string=auth_string.decode()
        # print(auth_string)
        headers={'Authorization':auth_string,'Json-Rpc-Tonce':tonce}

        #post_data dictionary passed as JSON
        # print(post_data)
        self.conn.request("POST",'/api_trade_v1.php',json.dumps(post_data),headers)
        response = self.conn.getresponse()

        # check response code, ID, and existence of 'result' or 'error'
        # before passing a dict of results
        if response.status == 200:
            # this might fail if non-json data is returned
            #the orginal currency_symbol start "\\u" in bad utf8 with will be replaced by "currency_symbol"
            resp_dict = json.loads(response.read().decode('utf-8').replace("\\u", "currency_symbol"))
            # The id's may need to be used by the calling application,
            # but for now, check and discard from the return dict
            if str(resp_dict['id']) == str(post_data['id']):
                if 'result' in resp_dict:
                    # print(resp_dict['result'])
                    return resp_dict['result']
                elif 'error' in resp_dict:
                    # print("error")
                    return resp_dict['error']
        else:
            # not great error handling....
            print("status:",response.status)
            print("reason:",response.reason)

        return None 
Example 78
Project: slidoc   Author: mitotic   File: pptx2md.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def copy_image(self, image_num, img_data, img_params='', img_path='', img_ext='', img_name=''):
        # Return image reference
        if not img_ext and img_path:
            img_ext = os.path.splitext(os.path.basename(img_path))[1][1:].lower()

        if not self.args_dict.get('img_dir'):
            # Embed images within Markdown
            if img_name:
                key = img_name
            else:
                key = 'img%02d' % (len(self.image_defs)+1)
            if key in self.image_keys:
                raise Exception('Duplicate image file name: '+key)
            self.image_keys.add(key)
            ctype = 'jpeg' if img_ext == 'jpg' else img_ext
            self.image_defs.append('[%s]: data:image/%s;base64,%s %s' % (key, ctype, base64.b64encode(img_data), img_params) )
            return '![image%d][%s]' % (image_num, key)

        if img_name:
            img_copy = img_name + '.' + img_ext
        else:
            prefix = self.fileprefix + '-' if self.fileprefix else ''
            if img_path:
                img_copy = prefix + os.path.basename(img_path)
            else:
                self.img_count += 1
                img_copy = prefix + ('image%02d.%s' % (self.img_count, img_ext))

        if self.img_zip:
            # Write image file to zip archive
            zprefix = os.path.splitext(os.path.basename(self.img_dir))[0]
            if zprefix:
                img_copy = zprefix + '/' + img_copy
            self.img_zip.writestr(img_copy, img_data)
        elif not self.nofile:
            # Write image file to disk
            if self.img_dir:
                img_copy = self.img_dir + '/' + img_copy
                if not os.path.exists(self.img_dir):
                    os.makedirs(self.img_dir)

            with open(img_copy, 'w') as f:
                f.write(img_data)

        return '![image%d](%s %s)' % (image_num, img_copy, img_params) 
Example 79
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: pem.py    MIT License 4 votes vote down vote up
def armor(type_name, der_bytes, headers=None):
    """
    Armors a DER-encoded byte string in PEM

    :param type_name:
        A unicode string that will be capitalized and placed in the header
        and footer of the block. E.g. "CERTIFICATE", "PRIVATE KEY", etc. This
        will appear as "-----BEGIN CERTIFICATE-----" and
        "-----END CERTIFICATE-----".

    :param der_bytes:
        A byte string to be armored

    :param headers:
        An OrderedDict of the header lines to write after the BEGIN line

    :return:
        A byte string of the PEM block
    """

    if not isinstance(der_bytes, byte_cls):
        raise TypeError(unwrap(
            '''
            der_bytes must be a byte string, not %s
            ''' % _type_name(der_bytes)
        ))

    if not isinstance(type_name, str_cls):
        raise TypeError(unwrap(
            '''
            type_name must be a unicode string, not %s
            ''',
            _type_name(type_name)
        ))

    type_name = type_name.upper().encode('ascii')

    output = BytesIO()
    output.write(b'-----BEGIN ')
    output.write(type_name)
    output.write(b'-----\n')
    if headers:
        for key in headers:
            output.write(key.encode('ascii'))
            output.write(b': ')
            output.write(headers[key].encode('ascii'))
            output.write(b'\n')
        output.write(b'\n')
    b64_bytes = base64.b64encode(der_bytes)
    b64_len = len(b64_bytes)
    i = 0
    while i < b64_len:
        output.write(b64_bytes[i:i + 64])
        output.write(b'\n')
        i += 64
    output.write(b'-----END ')
    output.write(type_name)
    output.write(b'-----\n')

    return output.getvalue() 
Example 80
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: docker_login.py    MIT License 4 votes vote down vote up
def update_config_file(self):
        '''
        If the authorization not stored in the config file or reauthorize is True,
        update the config file with the new authorization.

        :return: None
        '''

        path = self.config_path
        if not self.config_file_exists(path):
            self.create_config_file(path)

        try:
            # read the existing config
            config = json.load(open(path, "r"))
        except ValueError:
            self.log("Error reading config from %s" % (path))
            config = dict()

        if not config.get('auths'):
            self.log("Adding auths dict to config.")
            config['auths'] = dict()

        if not config['auths'].get(self.registry_url):
            self.log("Adding registry_url %s to auths." % (self.registry_url))
            config['auths'][self.registry_url] = dict()

        b64auth = base64.b64encode(
            to_bytes(self.username) + b':' + to_bytes(self.password)
        )
        auth = to_text(b64auth)

        encoded_credentials = dict(
            auth=auth,
            email=self.email
        )

        if config['auths'][self.registry_url] != encoded_credentials or self.reauthorize:
            # Update the config file with the new authorization
            config['auths'][self.registry_url] = encoded_credentials
            self.log("Updating config file %s with new authorization for %s" % (path, self.registry_url))
            self.results['actions'].append("Updated config file %s with new authorization for %s" % (
                path, self.registry_url))
            self.results['changed'] = True
            self.write_config(path, config)