Пример #1
0
 def getaccountstr(self):
     retstr = ""
     if self.controlleruser != "" or self.controllerpassword != "":
         acc = binascii.b2a_base64(bytes(self.controlleruser))
         pw = binascii.b2a_base64(bytes(self.controllerpassword))
         retstr = "&username="******"&password=" + str(pw)
     return retstr
Пример #2
0
    def start(self, boot=True):
        if not self.sta_if.isconnected():
            print('Tentando conectar...', end="")
            self.sta_if.active(True)
            i = 0
            while i < len(self.config) and not self.sta_if.isconnected():
                self.connection(
                    ubinascii.a2b_base64(ubinascii.unhexlify(
                        self.config[i][0])),
                    ubinascii.a2b_base64(ubinascii.unhexlify(
                        self.config[i][1])))
                print(".", end="")
                time.sleep_ms(200)
                i += 1

        if not self.sta_if.isconnected() and boot:
            self.sta_if.active(False)
            print('Rede não conectada')
            d = dnsquery.start()
            self.connection(d[b's'].decode(), d[b'p'].decode())
            if self.sta_if.isconnected():
                self.config[self.lconf] = [
                    ubinascii.hexlify(ubinascii.b2a_base64(d[b's'])[:-1]),
                    ubinascii.hexlify(ubinascii.b2a_base64(d[b'p'])[:-1])
                ]
                f = open('config.json', 'w')
                f.write(ujson.dumps(self.config))
                f.close()
                machine.reset()
            else:
                time.sleep(1)
                machine.reset()

        return self.sta_if
Пример #3
0
 def encode_key(cls, prevout):
     # hash up the txid and output number, truncate, and encode as base64
     # - truncating at (mod3) bytes so no padding on b64 output
     # - expects a COutPoint
     md = tcc.sha256('OutptValueCache')
     md.update(prevout.serialize())
     return b2a_base64(md.digest()[:15])[:-1].decode()
Пример #4
0
    def server_handshake(self):
        clr = self.s.makefile("rwb", 0)
        l = clr.readline()
        #sys.stdout.write(repr(l))
        webkey = None
        while 1:
            l = clr.readline()
            if not l:
                raise OSError("EOF in headers")
            if l == b"\r\n":
                break
        #    sys.stdout.write(l)
            h, v = [x.strip() for x in l.split(b":", 1)]
            if DEBUG:
                print((h, v))
            if h == b'Sec-WebSocket-Key':
                webkey = v

        if not webkey:
            raise OSError("Not a websocket request")

        if DEBUG:
            print("Sec-WebSocket-Key:", webkey, len(webkey))

        respkey = webkey + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
        respkey = hashlib.sha1(respkey).digest()
        respkey = binascii.b2a_base64(respkey)[:-1]

        resp = b'HTTP/1.1 101 Switching Protocols\r\nUpgrade: websocket\r\nConnection: Upgrade\r\nSec-WebSocket-Accept: %s\r\n\r\n' % respkey

        if DEBUG:
            print(resp)
        self.s.send(resp)
Пример #5
0
async def initiatewebsocket(w, secwebsocketkey):
    guid = b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    acc = uhashlib.sha1(secwebsocketkey + guid).digest()
    acc = ubinascii.b2a_base64(acc).strip()
    await w.awrite(b"HTTP/1.1 101 Switching Protocols\r\n")
    await w.awrite(b"Upgrade: websocket\r\nConnection: Upgrade\r\n")
    await w.awrite(b"Sec-WebSocket-Accept: %s\r\n\r\n" % acc)
Пример #6
0
    def __onboard_device(self):
        print("Onboarding device...")
        # Onboarding consists of registering your serial number and public key with the server
        status_code = 0
        attempt_serial = unique_id()  # first serial to try is the MAC address
        pub_key = bytearray(self.__namespace.get_i32("pub_key_len"))
        self.__namespace.get_blob("pub_key", pub_key)
        pub_key_b64 = b2a_base64(pub_key).strip().decode('utf-8')

        while status_code != 200:  # will keep generating new serials until one works
            self.serial_number = hexlify(attempt_serial).strip().decode(
                'utf-8').upper()
            r = self.__requester.request(
                'POST',
                'https://letterbox.mayursaxena.com/.netlify/functions/onboard',
                json={
                    'id': self.serial_number,
                    'pk': pub_key_b64
                })
            status_code = r.status_code
            print('{0}: {1}'.format(r.status_code, r.reason))
            attempt_serial = urandom(6)
            r.close()
        self.__namespace.set_blob(
            'serial_number',
            self.serial_number)  # store the serial that worked in NVS
        self.__namespace.commit()
        print("Device onboarded with serial {0}.".format(self.serial_number))
Пример #7
0
    def save_visualization(self, msg, sign_text=False):
        # write text into spi flash, maybe signing it as we go
        # - return length and checksum
        txt_len = msg.seek(0, 2)
        msg.seek(0)

        chk = self.chain.hash_message(msg_len=txt_len) if sign_text else None

        with SFFile(TXN_OUTPUT_OFFSET, max_size=txt_len+300, message="Visualizing...") as fd:
            await fd.erase()

            while 1:
                blk = msg.read(256).encode('ascii')
                if not blk: break
                if chk:
                    chk.update(blk)
                fd.write(blk)

            if chk:
                from ubinascii import b2a_base64
                # append the signature
                digest = tcc.sha256(chk.digest()).digest()
                sig = sign_message_digest(digest, 'm', None)
                fd.write(b2a_base64(sig).decode('ascii').strip())
                fd.write('\n')

            return (fd.tell(), fd.checksum.digest())
Пример #8
0
def b42_urlsafe_encode(payload):

    return string.translate(
        b2a_base64(payload)[:-1].decode('utf-8'), {
            ord('+'): '-',
            ord('/'): '_'
        })
Пример #9
0
    def __init__(self, request, conn, buflen=128):
        print("bring up websocket ...") # DEBUG
        self.conn = conn
        self._buf = bytearray(buflen)
        self.buf = memoryview(self._buf)

        # negotiate websocket, assumes caller tested is_websocket_request
        self.conn.send( self.RHEAD )
        self.conn.send( b"Upgrade: websocket\r\nConnection: Upgrade" ) 

        key = bytes( request.options["Sec-WebSocket-Key"], "utf-8" )
        key.update( self.MAGIC )
        self.conn.send( b"Sec-WebSocket-Accept: " + b2a_base64(key.digest)[:-1] )

        # client will fail if extensions or protocol don't match request
        if "Sec-Websocket-Extensions" in request.options:
            self.conn.send( 
                b"Sec-WebSocket-Extensions: " + \
                bytes(request.options["Sec-WebSocket-Extensions"], "utf-8") + \
                b"\r\n" 
            )
        if "Sec-WebSocket-Protocol" in request.options:
            self.conn.send(
                b"Sec-WebSocket-Protocol" + \
                bytes(request.options["Sec-WebSocket-Protocol"], "utf-8") + \
                b"\r\n"
            )
        self.conn.send(b"\r\n")

        print("websocket up ...")
Пример #10
0
    def websocket_handshake(self, req, writer):
        try:
            import ubinascii as binascii
            import uhashlib as hashlib
            import uwebsocket as websocket
        except:
            import binascii
            import hashlib
            import websocket

        if b"Upgrade" in req.headers and b"Sec-WebSocket-Key" in req.headers:
            d = hashlib.sha1(req.headers[b"Sec-WebSocket-Key"])
            d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
            respkey = d.digest()
            respkey = binascii.b2a_base64(respkey)[:-1]
            yield from writer.awrite(b"""\
HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: """ + respkey + b"\r\n\r\n")
            ws = WSWrapper(req.reader.s, writer)
            yield from self.websocket_loop(ws)
        else:
            yield from picoweb.start_response(writer, status="400")
            yield from writer.awrite(
                "400 Missing Upgrade or Sec-WebSocket-Key for websocket connection.\r\n\r\n"
            )
            yield from writer.awrite("Your headers: %s\r\n" % req.headers)
            return True
Пример #11
0
    def _encodeBase64(self, data):
        s = data
        if isinstance(s, str):
            s = bytes(data, "utf-8")

        b64 = ubinascii.b2a_base64(s)[:-1]
        return b64.replace(b"=", b"").replace(b"+", b"-").replace(b"/", b"_")
Пример #12
0
def sign_psbt(wallet=None, tx=None, success_callback=None):
    wallet.fill_psbt(tx)
    keystore.sign(tx)
    keystore.update_wallet_indexes(wallet, tx)
    # remove everything but partial sigs
    # to reduce QR code size
    tx.unknown = {}
    tx.xpubs = {}
    for i in range(len(tx.inputs)):
        tx.inputs[i].unknown = {}
        tx.inputs[i].non_witness_utxo = None
        tx.inputs[i].witness_utxo = None
        tx.inputs[i].sighash_type = None
        tx.inputs[i].bip32_derivations = {}
        tx.inputs[i].witness_script = None
        tx.inputs[i].redeem_script = None
    for i in range(len(tx.outputs)):
        tx.outputs[i].unknown = {}
        tx.outputs[i].bip32_derivations = {}
        tx.outputs[i].witness_script = None
        tx.outputs[i].redeem_script = None
    b64_tx = b2a_base64(tx.serialize()).decode('utf-8')
    if b64_tx[-1:] == "\n":
        b64_tx = b64_tx[:-1]
    popups.qr_alert("Signed transaction:", b64_tx, "Scan it with your software wallet", width=480)
    if success_callback is not None:
        success_callback(b64_tx)
Пример #13
0
    def send(self, sf, radio, freq, payload):
        payload_size = len(payload)

        sf_string = ""
        # check sf in range
        if sf < 7 or sf > 12:
            return
        else:
            sf_string = "SF{}BW125".format(sf)
        if len(payload) > 255:
            return

        # Base64 encode payload
        if type(payload) is str:
            payload = bytes(payload,'utf-8')
        b64 = ubinascii.b2a_base64(payload)
        b64_str = b64.decode('utf-8')
        b64_str = b64_str.replace("\n","")

        # msg object
        msg = {
            "txpk": {
                "freq":freq,
                "rfch":radio,
                "powe":14,
                "datr":sf_string,
                "codr":"4/5",
                "size":payload_size,
                "data":b64_str
            }
        }
        json = ujson.dumps(msg)
        self.sock.sendto(json, (self.ip, self.udp_send_port))
Пример #14
0
def make_respkey(webkey):
    d = uhashlib.sha1(webkey)
    d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
    respkey = d.digest()
    respkey = ubinascii.b2a_base64(respkey) #[:-1]
    # Return with trailing "\n".
    return respkey
Пример #15
0
    def _getToken(self, debug = False):
        if self.apiKey == None or self.apiSecret == None or self.userName == None :
            raise OSError('Missing authentication info!')
            
        if self.validUntil == None or time() >= self.validUntil:
            basic_auth = ubinascii.b2a_base64("{}:{}".format(self.apiKey, self.apiSecret)).decode('ascii')
            auth_header = {'Authorization':'Basic {}'.format(basic_auth), 'Accept':'application/json'}

            body = 'grant_type=client_credentials&scope=openid'
            if debug: print(self.connectToURLforToken)
            resp = http_client.post(self.connectToURLforToken, headers=auth_header, textMsg=body, contentType='application/x-www-form-urlencoded',  debug = debug)
            resp.raise_for_status()
            resp.content
            if debug:
                print ('Response : ')
                print (resp.content)
            
            authInfo = resp.json()
            self.tokenBearer = authInfo['access_token']
            
            try:
                self.validUntil = time() + authInfo['expires_in']
                localtime(self.validUntil)
            except OverflowError:
                if debug:
                    print("Permanent token, setting to 1 week validity")
                self.validUntil = time() + 7 * 24 * 60 * 60

            resp.close()
            if debug: print ("Token retrieved ! valid until {}".format(localtime(self.validUntil)))
        else:
            if debug: print ("Token still valid !  Re-using it ! {}".format(self.tokenBearer))
Пример #16
0
 def set_auth(self, credentials, auth_scheme="Basic"):
     if auth_scheme == "Basic":
         self.auth = "Basic " + ubinascii.b2a_base64(credentials['username'] + ":" + credentials['password']).decode().strip()
     elif auth_scheme == "Bearer":
         self.auth = "Bearer " + credentials['token']
     else:
         raise AuthorizationException("Unsupported authorization scheme: " + auth_scheme)
Пример #17
0
def make_respkey(webkey):
    d = uhashlib.sha1(webkey)
    d.update(b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11")
    respkey = d.digest()
    respkey = ubinascii.b2a_base64(respkey)  # [:-1]
    # Return with trailing "\n".
    return respkey
Пример #18
0
def save_pem(contents, pem_marker):
    """Saves a PEM file.

    :param contents: the contents to encode in PEM format
    :param pem_marker: the marker of the PEM content, such as 'RSA PRIVATE KEY'
        when your file has '-----BEGIN RSA PRIVATE KEY-----' and
        '-----END RSA PRIVATE KEY-----' markers.

    :return: the base64-encoded content between the start and end markers, as bytes.

    """

    (pem_start, pem_end) = _markers(pem_marker)

    b64 = ubinascii.b2a_base64(contents).replace(b'\n', b'')
    pem_lines = [pem_start]

    for block_start in range(0, len(b64), 64):
        block = b64[block_start:block_start + 64]
        pem_lines.append(block)

    pem_lines.append(pem_end)
    pem_lines.append(b'')

    return b'\n'.join(pem_lines)
Пример #19
0
 def message(self, history = False):
     import machine
     import network
     import json
     import ubinascii
     import app
     msg = {}
     msg['node'] = app.cfg.node
     msg['utc'] = "{}T{}".format(app.date(), app.time())
     msg['val'] = app.vals 
     msg['dev'] = app.devs
     msg['label'] = app.units
     msg['ver'] = app.VERSION
     msg['mac'] = ubinascii.hexlify(network.WLAN(network.STA_IF).config('mac'), ':').decode()
     msg['ip'] = network.WLAN(network.STA_IF).ifconfig()[0]
     # every hour add config and history
     if history:
         f = open('config', 'r')
         msg['cfg'] = json.loads(f.read())
         f.close()
         import os
         osv = os.uname()
         msg['os'] = "{}_{}".format(osv[0], osv[3]).replace(" ", "_")
         if osv[0] == 'esp32':
             try:
                 msg['mem'] = ubinascii.b2a_base64(machine.RTC().memory()).rstrip().decode()
             except:
                 pass
     return json.dumps(msg).replace(' ', '')
Пример #20
0
def GenerateAzureSasToken(uri, key, expiryTimestamp, policy_name=None):
    from ubinascii import a2b_base64, b2a_base64

    def _quote(s):
        r = ''
        for c in str(s):
            if (c >= 'a' and c <= 'z') or \
               (c >= '0' and c <= '9') or \
               (c >= 'A' and c <= 'Z') or \
               (c in '.-_') :
                r += c
            else:
                r += '%%%02X' % ord(c)
        return r

    uri = _quote(uri)
    sign_key = b'%s\n%d' % (uri, int(expiryTimestamp))
    key = a2b_base64(key)
    hmac = HMACSha256(key, sign_key)
    signature = _quote(b2a_base64(hmac).decode().strip())
    token = 'sr=' + uri + '&' + 'sig=' + signature + '&' + 'se=' + str(
        expiryTimestamp)
    if policy_name:
        token += '&' + 'skn=' + policy_name
    return 'SharedAccessSignature ' + token
Пример #21
0
    def connect(cls, uri):
        uri = urlparse(uri)
        assert uri

        sock = socket.socket()
        addr = socket.getaddrinfo(uri.hostname, uri.port)
        sock.connect(addr[0][4])

        def send_header(header, *args):
            sock.send(header % args + '\r\n')

        key = binascii.b2a_base64(
            bytes(random.getrandbits(8) for _ in range(16)))[:-1]

        send_header(b'GET %s HTTP/1.1', uri.path or '/')
        send_header(b'Host: %s:%s', uri.hostname, uri.port)
        send_header(b'Connection: Upgrade')
        send_header(b'Upgrade: websocket')
        send_header(b'Sec-WebSocket-Key: %s', key)
        send_header(b'Sec-WebSocket-Version: 13')
        send_header(b'Origin: http://localhost')
        send_header(b'')

        header = sock.readline()[:-2]
        assert header == b'HTTP/1.1 101 Switching Protocols', header

        while header:
            header = sock.readline()[:-2]

        return Websocket(sock, True)
Пример #22
0
def calc_websocket_resp(key):
    concatkey = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    binarr = uhashlib.sha1(concatkey).digest()
    #hexstr = ubinascii.hexlify(binarr)
    #print(hexstr)
    respkey = ubinascii.b2a_base64(binarr).decode('utf-8').rstrip()
    #respkey = respkey[:-1] # strips the \n
    return respkey
Пример #23
0
    def setValue(self, byteArrayValue):
        #        if not isinstance(byteArrayValue , array):
        #            raise OSError('Invalid \'byteArrayValue\' parameter!')

        # BASE64 encode the data !!!!
        converted = str(b2a_base64(byteArrayValue), 'utf-8').strip('\n')
        self.data['binaryMeterValue'] = converted
        self._updateTimestamp()
Пример #24
0
def generate_owner_key(passphrase, mnemonic=None):
    owner_key = bytearray(108)
    master_secret, master_cofactor = get_beam_kdf(mnemonic)
    beam.export_owner_key(master_secret, master_cofactor, passphrase,
                          len(passphrase), owner_key)
    owner_key = ubinascii.b2a_base64(owner_key)

    return owner_key
Пример #25
0
    def setValue(self, byteArrayValue):
#        if not isinstance(byteArrayValue , array):
#            raise OSError('Invalid \'byteArrayValue\' parameter!')
        
        # BASE64 encode the data !!!!
        converted = str(b2a_base64(byteArrayValue), 'utf-8').strip('\n')
        self.data['binaryMeterValue'] = converted
        self._updateTimestamp()
Пример #26
0
def cat_base64(fn):
	f = open(fn, 'rb')
	while True:
		c = ubinascii.b2a_base64(f.read())
		sys.stdout.write(c)
		sys.stdout.write("\n")
		if not len(c) or c == b'\n':
			break
	f.close()
Пример #27
0
def send_abp(msg = "Empty string!"):
    global frameCounterABP
    encmsg = list(ubinascii.b2a_base64(msg)[:])

    lorawan = LoRaWAN.new(nwskeyABP, appskeyABP)
#    lorawan.create(MHDR.UNCONF_DATA_UP, {'devaddr': devaddrABP, 'fcnt': frameCounterABP, 'data': list(map(ord, 'Python rules!')) })
    lorawan.create(MHDR.UNCONF_DATA_UP, {'devaddr': devaddrABP, 'fcnt': frameCounterABP, 'data': encmsg})
    sendRAW(lorawan.to_raw())
    frameCounterABP += 1
Пример #28
0
 def _encrypt(self, id, message):
     gc.collect()
     try:
         iv = crypto.getrandbits(128)
         cipher = AES(self._module['metrics'][id]['key'].encode('utf-8'), AES.MODE_CFB, iv)
         return b2a_base64(iv + cipher.encrypt(message.encode('utf-8'))).decode('utf-8')
     except:
         print("ERROR encrypting message for metric: " + str(id) + " of sensor " + str(self._module['name']) + ". Cannot proceed!")
         return None
Пример #29
0
def create_payload(dht_sensor):
    dht_sensor.measure()
    measures = OrderedDict([('temperature', dht_sensor.temperature()),
                            ('humidity', dht_sensor.humidity())])

    values = [v for _, v in measures.items()]
    packed = pack('>HH', *values)
    base64 = b2a_base64(packed)
    return base64.strip()  # dump trailing \n
Пример #30
0
    def done(signature, address):
        # complete. write out result
        from ubinascii import b2a_base64
        orig_path, basename = filename.rsplit('/', 1)
        orig_path += '/'
        base = basename.rsplit('.', 1)[0]
        out_fn = None

        sig = b2a_base64(signature).decode('ascii').strip()

        while 1:
            # try to put back into same spot
            # add -signed to end.
            target_fname = base+'-signed.txt'

            for path in [orig_path, None]:
                try:
                    with CardSlot() as card:
                        out_full, out_fn = card.pick_filename(
                            target_fname, path)
                        out_path = path
                        if out_full:
                            break
                except CardMissingError:
                    prob = 'Missing card.\n\n'
                    out_fn = None

            if not out_fn:
                # need them to insert a card
                prob = ''
            else:
                # attempt write-out
                try:
                    with CardSlot() as card:
                        with open(out_full, 'wt') as fd:
                            # save in full RFC style
                            fd.write(RFC_SIGNATURE_TEMPLATE.format(addr=address, msg=text,
                                                                   blockchain='BITCOIN', sig=sig))

                    # success and done!
                    break

                except OSError as exc:
                    prob = 'Failed to write!\n\n%s\n\n' % exc
                    sys.print_exception(exc)
                    # fall thru to try again

            # prompt them to input another card?
            ch = await ux_show_story(prob+"Please insert an SDCard to receive signed message, "
                                     "and press OK.", title="Need Card")
            if ch == 'x':
                return

        # done.
        msg = "Created new file:\n\n%s" % out_fn
        await ux_show_story(msg, title='File Signed')
Пример #31
0
def encodebytes(s):
    """Encode a bytestring into a bytestring containing multiple lines
    of base-64 data."""
    if not isinstance(s, bytes_types):
        raise TypeError("expected bytes, not %s" % s.__class__.__name__)
    pieces = []
    for i in range(0, len(s), MAXBINSIZE):
        chunk = s[i : i + MAXBINSIZE]
        pieces.append(binascii.b2a_base64(chunk))
    return b"".join(pieces)
Пример #32
0
 def save_users(self, users, features):
     feas_encode = []
     for fea in features:
         print("raw feature:", fea)
         fea = ubinascii.b2a_base64(fea)
         feas_encode.append(fea)
     info = {"users": users, "features": feas_encode}
     with open(self.users_conf_name, "w") as f:
         info = json.dumps(info)
         f.write(info)
Пример #33
0
 def _make_node_packet(self, rx_data, rx_time, tmst, sf, bw, rssi, snr):
     RX_PK["rxpk"][0]["time"] = "%d-%02d-%02dT%02d:%02d:%02d.%dZ" % (rx_time[0], rx_time[1], rx_time[2], rx_time[3], rx_time[4], rx_time[5], rx_time[6])
     RX_PK["rxpk"][0]["tmst"] = tmst
     RX_PK["rxpk"][0]["freq"] = self._freq_to_float(self.frequency)
     RX_PK["rxpk"][0]["datr"] = self._sf_bw_to_dr(sf, bw)
     RX_PK["rxpk"][0]["rssi"] = rssi
     RX_PK["rxpk"][0]["lsnr"] = snr
     RX_PK["rxpk"][0]["data"] = ubinascii.b2a_base64(rx_data)[:-1]
     RX_PK["rxpk"][0]["size"] = len(rx_data)
     return ujson.dumps(RX_PK)
Пример #34
0
 def _make_node_packet(self, rx_data, rx_time, tmst, sf, bw, rssi, snr):
     RX_PK["rxpk"][0]["time"] = "%d-%02d-%02dT%02d:%02d:%02d.%dZ" % (rx_time[0], rx_time[1], rx_time[2], rx_time[3], rx_time[4], rx_time[5], rx_time[6])
     RX_PK["rxpk"][0]["tmst"] = tmst
     RX_PK["rxpk"][0]["freq"] = self._freq_to_float(self.frequency)
     RX_PK["rxpk"][0]["datr"] = self._sf_bw_to_dr(sf, bw)
     RX_PK["rxpk"][0]["rssi"] = rssi
     RX_PK["rxpk"][0]["lsnr"] = snr
     RX_PK["rxpk"][0]["data"] = ubinascii.b2a_base64(rx_data)[:-1]
     RX_PK["rxpk"][0]["size"] = len(rx_data)
     return ujson.dumps(RX_PK)
Пример #35
0
 def ddnsupdate(self):
   if self.enabled():
     import urequests as req
     from ubinascii import b2a_base64
     auth = b2a_base64('{}:{}'.format(self.cfg['user'], self.cfg['pass']))
     headers = { 'Authorization': 'Basic {}'.format(auth) }
     url = '{}?{}={}'.format(self.cfg['url'], 'hostname', self.cfg['host'])
     res = req.get(url, headers=headers)
     logger.info(res.status_code)
     res.close()
Пример #36
0
def encrypt(key,data):

    # ended up not hasing the key, just pad it, make sure it's 16 bytes
    cryptor = aes(pad_mod_16(key),2,iv)
    # append chunk delimiter string before base64 encoding
    ciphertext = cryptor.encrypt(pad_mod_16(str.encode(data)))
    # encode to base 64 for sending
    ciphertext_b64 = ubinascii.b2a_base64(ciphertext)

    return ciphertext_b64+delimiter
Пример #37
0
def encode(input, output):
    """Encode a file; input and output are binary files."""
    while True:
        s = input.read(MAXBINSIZE)
        if not s:
            break
        while len(s) < MAXBINSIZE:
            ns = input.read(MAXBINSIZE-len(s))
            if not ns:
                break
            s += ns
        line = binascii.b2a_base64(s)
        output.write(line)
def server_handshake(sock):
    print("start_handshake")
    clr = sock.makefile("rwb", 0)
    l = clr.readline()
    #sys.stdout.write(repr(l))

    webkey = None

    while 1:
        l = clr.readline()
        if not l:
            raise OSError("EOF in headers")
        if l == b"\r\n":
            break
    #    sys.stdout.write(l)
        h, v = [x.strip() for x in l.split(b":", 1)]
        if DEBUG:
            print("h, v:")
            print((h, v))
        if h == b'Sec-WebSocket-Key':
            webkey = v

    if not webkey:
        raise OSError("Not a websocket request")

    if DEBUG:
        print("Sec-WebSocket-Key:", webkey, len(webkey))

    respkey = webkey + b"258EAFA5-E914-47DA-95CA-C5AB0DC85B11"
    respkey = hashlib.sha1(respkey).digest()
    respkey = binascii.b2a_base64(respkey)[:-1]

    resp = b"""\
HTTP/1.1 101 Switching Protocols\r
Upgrade: websocket\r
Connection: Upgrade\r
Sec-WebSocket-Accept: %s\r
\r
""" % respkey

    if DEBUG:
        print(resp)
    sock.send(resp)
Пример #39
0
def _download():
    if _read_timeout(3) != "###":
        return
    with open("file_name.py", "rb") as f:
        while True:
            chunk = f.read(48)
            if not chunk:
                break
            chunk = b2a_base64(chunk).strip()
            if isinstance(chunk, bytes):
                chunk = chunk.decode("ascii")
            cl = len(chunk)
            x = sys.stdout.write("".join(["#", "0" if cl < 10 else "", str(cl), chunk]))
            ack = _read_timeout(2)
            if not ack or ack != "#1":
                return

        # Mark end
        x = sys.stdout.write("#00")
Пример #40
0
def b64encode(s, altchars=None):
    """Encode a byte string using Base64.

    s is the byte string to encode.  Optional altchars must be a byte
    string of length 2 which specifies an alternative alphabet for the
    '+' and '/' characters.  This allows an application to
    e.g. generate url or filesystem safe Base64 strings.

    The encoded byte string is returned.
    """
    if not isinstance(s, bytes_types):
        raise TypeError("expected bytes, not %s" % s.__class__.__name__)
    # Strip off the trailing newline
    encoded = binascii.b2a_base64(s)[:-1]
    if altchars is not None:
        if not isinstance(altchars, bytes_types):
            raise TypeError("expected bytes, not %s"
                            % altchars.__class__.__name__)
        assert len(altchars) == 2, repr(altchars)
        return encoded.translate(bytes.maketrans(b'+/', altchars))
    return encoded
Пример #41
0
try:
    import ubinascii as binascii
except ImportError:
    import binascii

print(binascii.b2a_base64(b''))
print(binascii.b2a_base64(b'f'))
print(binascii.b2a_base64(b'fo'))
print(binascii.b2a_base64(b'foo'))
print(binascii.b2a_base64(b'foob'))
print(binascii.b2a_base64(b'fooba'))
print(binascii.b2a_base64(b'foobar'))

print(binascii.b2a_base64(b'\x00\x01\x02\x03\x04\x05\x06\x07'))
print(binascii.b2a_base64(b'\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f'))
print(binascii.b2a_base64(b'\x7f\x80\xff'))
print(binascii.b2a_base64(b'1234ABCDabcd'))
Пример #42
0
def socket_handler(listen_s):
    gc.collect()

    try:
        client, remote_addr = listen_s.accept()
        if not client.readline() == b'GET / HTTP/1.1\r\n':
            client.close()
            return

        ws = None
        ws_key = None

        while True:
            line = client.readline()
            if line == b'\r\n' or line == b'':
                break
            h, v = [x.strip() for x in line.split(b':', 1)]
            if h == b'Connection':
                if v == b'Upgrade':
                    ws = True
            elif h == b'Sec-WebSocket-Key':
                ws_key = v
            print(v, h)
        if not ws:
            client.close()
            return
        print('Got valid socket connection from', remote_addr)
        d = uhashlib.sha1(ws_key)
        d.update(b'258EAFA5-E914-47DA-95CA-C5AB0DC85B11')
        client.send(b'\\n'
                    b'HTTP/1.1 101 Switching Protocols\r\n'
                    b'Upgrade: websocket\r\n'
                    b'Connection: Upgrade\r\n'
                    b'Sec-WebSocket-Accept: ')
        client.send(ubinascii.b2a_base64(d.digest())[:-1])
        client.send(b'\r\n\r\n')
        ws = websocket.websocket(client)

        def socket_handler_inner(client):
            global settings
            cmd = ws.readline().strip()
            if len(cmd) == 0:
                ws.close()
                client.close()
                return
            elif cmd == b'get':
                ws.write(json.dumps(settings))
                ws.write(b'OK\n')
            elif cmd == b'set':
                settings = json.loads(ws.readline())
                ws.write(b'OK\n')
            elif cmd == b'exec':
                try:
                    exec(ws.readline())
                    ws.write(b'OK\n')
                except Exception as e:
                    print('error', e)
                    ws.write(b'ERROR\n')
                    ws.write(json.dumps(repr(e)))
                    ws.write(b'\n')
            else:
                ws.write(b'ERROR\nUnknown action')
                ws.write(cmd)
                ws.write(b'\n')

        client.setblocking(False)
        client.setsockopt(socket.SOL_SOCKET, 20, socket_handler_inner)
        gc.collect()
    except Exception as e:
        print('Error handing socket:', e)
Пример #43
0
def generate_nonce(length):
	""" Generates a pseudorandom hex string, in a lightweight way """
	if length > 1:
		l = [ x for x in b2a_base64(urandom(length*2)).decode() if x.isalpha() ]
		return (''.join(l))[:length]