def make_sccrq (self): # make avp avp_data = '' # Start_Control_Request avp_data += self.make_avp(attr_type=0, attr_value=1) # Protocol Version avp_data += self.make_avp(attr_type=2, attr_value=256) # Framing Capabilities avp_data += self.make_avp(attr_type=3, avp_len=10, attr_value1=0, attr_value2=3) # Bearer Capabilities avp_data += self.make_avp(attr_type=4, avp_len=10, attr_value1=0, attr_value2=0) # Firmware Revision avp_data += self.make_avp(attr_type=6, attr_value=1680) # Host Name avp_data += self.make_avp(attr_type=7, avp_len=6+len(HOSTNAME), avp_raw_data=binascii.a2b_qp(HOSTNAME)) # Vendor Name avp_data += self.make_avp(attr_type=8, avp_len=6+len(VENDOR), avp_raw_data=binascii.a2b_qp(VENDOR)) # Assigned Tunnel ID avp_data += self.make_avp(attr_type=9, attr_value=64773) # Receive Window Size avp_data += self.make_avp(attr_type=10, attr_value=4) # construct l2tp packet header_data = self.make_header(plen=12+87) l2tp_data = header_data + avp_data return l2tp_data
def test_not_implemented(self): test_cases = [ lambda: binascii.a2b_qp(None), lambda: binascii.a2b_qp(None, None), lambda: binascii.a2b_hqx(None), lambda: binascii.rledecode_hqx(None), lambda: binascii.rlecode_hqx(None), lambda: binascii.b2a_hqx(None), lambda: binascii.crc_hqx(None, None), ] for temp_func in test_cases: self.assertRaises(NotImplementedError, temp_func)
def getBalance(): """ Get balance request :return: JSON request tous les capteurs de la classe """ sipout = siphash.SipHash_2_4(key) sipin = siphash.SipHash_2_4(key) now = round(time.time()) # if request._headers['Content-Type'] == 'application/json': dict_req = request.get_json() badge = dict_req['Badge'] time_req = dict_req['Time'] hash_verif = badge + time_req for c in hash_verif: sipin.update(binascii.a2b_qp(c)) #reqHash = hex(sipin.hash())[2:-1].upper() #This change does not work on Coltello reqHash = hex(sipin.hash())[2:].upper() reqHash = reqHash.zfill(16) if dict_req['Hash'] == reqHash: print("Cool hash's OK") else: print("Pas Cool !!!!!!!!!!") badgeId = int(badge, 16) element = session.query(User, User.name, User.balance).filter(User.id == badgeId) if element.count() == 0: messages = ['ERROR', 'UNKNOWN USER'] ret = {'Melody': "c5", 'Message': messages, 'Time': now} else: messages = [element.one().name, "{:.2f}".format(element.one().balance/100)] ret = {'Melody': "a1c1a1c1a1c1a1c1", 'Message': messages, 'Time': now} hash_str = ret['Melody'] + "".join(messages) + now.__str__() for c in hash_str: sipout.update(binascii.a2b_qp(c)) #retHash = hex(sipout.hash())[2:-1].upper() #This change does not work on Coltello works on PI retHash = hex(sipout.hash())[2:].upper() retHash = retHash.zfill(16) ret['Hash'] = retHash return json.dumps(ret)
def test_qp(self): binascii.a2b_qp(data=b"", header=False) # Keyword arguments allowed # A test for SF bug 534347 (segfaults without the proper fix) try: binascii.a2b_qp(b"", **{1:1}) except TypeError: pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") self.assertEqual(binascii.a2b_qp(b"= "), b"= ") self.assertEqual(binascii.a2b_qp(b"=="), b"=") self.assertEqual(binascii.a2b_qp(b"=AX"), b"=AX") self.assertRaises(TypeError, binascii.b2a_qp, foo="bar") self.assertEqual(binascii.a2b_qp(b"=00\r\n=00"), b"\x00\r\n\x00") self.assertEqual( binascii.b2a_qp(b"\xff\r\n\xff\n\xff"), b"=FF\r\n=FF\r\n=FF") self.assertEqual( binascii.b2a_qp(b"0"*75+b"\xff\r\n\xff\r\n\xff"), b"0"*75+b"=\r\n=FF\r\n=FF\r\n=FF") self.assertEqual(binascii.b2a_qp(b'\0\n'), b'=00\n') self.assertEqual(binascii.b2a_qp(b'\0\n', quotetabs=True), b'=00\n') self.assertEqual(binascii.b2a_qp(b'foo\tbar\t\n'), b'foo\tbar=09\n') self.assertEqual(binascii.b2a_qp(b'foo\tbar\t\n', quotetabs=True), b'foo=09bar=09\n') self.assertEqual(binascii.b2a_qp(b'.'), b'=2E') self.assertEqual(binascii.b2a_qp(b'.\n'), b'=2E\n') self.assertEqual(binascii.b2a_qp(b'a.\n'), b'a.\n')
def sync(): """ return drinks catalog :return: JSON request tous les capteurs de la classe """ sip = siphash.SipHash_2_4(key) now = round(time.time()) elements = session.query(Inventory, Inventory.name, Inventory.price).filter(Inventory.quantity > 0).all() elementsID = session.query(Inventory, Inventory.id).filter(Inventory.quantity > 0).all() catalog = [e.name + " " + "{:.2f}".format(e.price/100) for e in elements] catalogDBID = [e.id for e in elementsID] request = {'Header': "DrinkingBuddy", 'Products': catalog, 'DBID': catalogDBID, 'Time': now} hash_str = request['Header'] + "".join(catalog) + now.__str__() for c in hash_str: sip.update(binascii.a2b_qp(c)) #reqHash = hex(sip.hash())[2:-1].upper() #This change is not working on Coltello, but works on the RaspberryPi!!! reqHash = hex(sip.hash())[2:].upper() reqHash = reqHash.zfill(16) request['Hash'] = reqHash print(request['Hash']) return json.dumps(request)
def write(self, directory='.'): """ Writes the chat to a file in the directory. """ f = open('%s/%s.chat' % (directory, self.id), 'w') f.write(a2b_qp(self.raw)) f.close()
def __get_header(self): nonce = str(time.time()) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)) created_date = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.localtime()) sha_object = sha.new(nonce + created_date + self.shared_secret) password_64 = binascii.b2a_base64(sha_object.digest()) return 'UsernameToken Username="******", PasswordDigest="%s", Nonce="%s", Created="%s"' % (self.user_name, password_64.strip(), base64nonce.strip(), created_date)
def download(file_path): '''Download the file by name of "file_path"''' if (user.is_user_signed_in()): client = c.get_client() filename = os.path.basename(file_path) file_path = sanitize_path(file_path) if (os.path.isfile(filename) or os.path.isdir(filename)): logger.die('File or dir with name "' + filename + '" in current directory') else: existance = check_existance(file_path, client) if (existance[0]): try: client.download_file("mf:" + file_path , '.') file_info = existance[1] xattr.setxattr(filename, 'hash', binascii.a2b_qp(file_info['hash'])) logger.log('File "' + filename + '" downloaded successfully.') except NotAFolderError: logger.die('Path "' + remote_path + '" not found on MediaFire') except ResourceNotFoundError: logger.die('Path "' + remote_path + '" not found on MediaFire.') except requests.exceptions.RequestException: logger.die('Network error, please check network status and try again') else: logger.log('File path and name "' + file_path + '" does not exist.') else: user.get_auth()
def write(self, data): """Takes any input data provided, decodes it as quoted-printable, and passes it on to the underlying object. :param data: quoted-printable data to decode """ # Prepend any cache info to our data. if len(self.cache) > 0: data = self.cache + data # If the last 2 characters have an '=' sign in it, then we won't be # able to decode the encoded value and we'll need to save it for the # next decoding step. if data[-2:].find(b'=') != -1: enc, rest = data[:-2], data[-2:] else: enc = data rest = b'' # Encode and write, if we have data. if len(enc) > 0: self.underlying.write(binascii.a2b_qp(enc)) # Save remaining in cache. self.cache = rest return len(data)
def auto_scan(self): """ Make scan in network to verify if servers is online """ self.first_searcher() self.replace_aux() self.update_all() self.logger.debug(" Neighbors map:\n {}".format( str(self.get_neighbors()) ) ) last_hash=b'0' count=self.TIMES_TO_UPDATE_MAP while True: self.verify_map() count-=1 if(count<=0 and not self.UPDATE.is_set()): count=self.TIMES_TO_UPDATE_MAP self.first_searcher() hash_ = hashlib.md5() hash_.update( binascii.a2b_qp(str(self.get_neighbors())) ) if(last_hash != hash_.digest()): self.logger.debug("Update map all servers") self.replace_aux() self.update_all() last_hash=hash_.digest() self.logger.debug(" Neighbors map:\n {}".format( str(self.get_neighbors()) ) ) sleep(self.TIME_AUTO_SCAN)
def _ConvertDictToObject(self, json_dict): """Converts a JSON dict into an object. Note that json_dict is a dict of dicts and the _ConvertDictToObject method will be called for every dict. That is how the deserialized objects are created. Args: json_dict: a dictionary of the JSON serialized objects. Returns: A deserialized object which can be: * an analysis report (instance of AnalysisReport); * a dictionary. """ # Use __type__ to indicate the object class type. class_type = json_dict.get(u'__type__', None) if class_type not in self._CLASS_TYPES: # Dealing with a regular dict. return json_dict # Remove the class type from the JSON dict since we cannot pass it. del json_dict[u'__type__'] if class_type == u'bytes': return binascii.a2b_qp(json_dict[u'stream']) elif class_type == u'EventTag': return self._ConvertDictToEventTag(json_dict) return self._ConvertDictToAnalysisReport(json_dict)
def get_opcode_pub_uri_payload(payload_data): ''' Get M2M Payload for Publish Uri message opcode :param payload_data: Payload data :return: Payload string ''' payload_str = '' payload_tuple = ast.literal_eval(payload_data) temp_iter = 0 payload_len = len(payload_tuple) if temp_iter < payload_len: source_node = "{0:0.2X}".format(payload_tuple[temp_iter]) payload_str += source_node else: return payload_str temp_iter += 1 if temp_iter < payload_len: namespace_id = "{0:0.2X}".format(payload_tuple[temp_iter]) payload_str += namespace_id else: return payload_str temp_iter += 1 if temp_iter < payload_len: uri = (binascii.b2a_hex(binascii.a2b_qp(payload_tuple[temp_iter]))).decode('ascii') length = (len(source_node)/2) + (len(namespace_id)/2) + (len(uri)/2) payload_str = payload_str + uri return payload_str
def decodestring(s, header = 0): if a2b_qp is not None: return a2b_qp(s, header = header) from cStringIO import StringIO infp = StringIO(s) outfp = StringIO() decode(infp, outfp, header = header) return outfp.getvalue()
def decodestring(s, header=False): if a2b_qp is not None: return a2b_qp(s, header=header) from io import BytesIO infp = BytesIO(s) outfp = BytesIO() decode(infp, outfp, header=header) return outfp.getvalue()
def __create_header(self): utc_timestamp = datetime.datetime.utcnow() nonce = str(calendar.timegm(utc_timestamp.timetuple())) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)) created_on = utc_timestamp.strftime("%Y-%m-%dT%H:%M:%SZ") sha_object = sha1(nonce + created_on + self._secret) password_64 = base64.b64encode(bytes(sha_object.digest())) return 'UsernameToken Username="******", PasswordDigest="%s", Nonce="%s", Created="%s"' % ( self._user_name, password_64.strip(), base64nonce.strip(), created_on)
def _decode_content_transfer(self, data): encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower() if encoding == "base64": return base64.b64decode(data) elif encoding == "quoted-printable": return binascii.a2b_qp(data) else: raise RuntimeError("unknown content transfer encoding: {}" "".format(encoding))
def store_in_cache(arg): fileName = hashlib.md5(arg.encode()).hexdigest() + ".cache" timestamp = str(time.time()).split(".")[0] timestamp = timestamp + "\n\n Moet Hier iets tussen zetten voor het geval iemand veel enters gebruikt in zijn html \n\n" pageContent = arg.text with open("cache/"+fileName, 'wb') as cacheFile: cacheFile.writelines([binascii.a2b_qp(bytearray(timestamp,"ascii", "replace")), binascii.a2b_qp(bytearray(pageContent,"ascii", "replace"))]) cacheFile.close()
def _decode_content_transfer(self, data): encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower() if encoding == 'base64': return base64.b64decode(data) elif encoding == 'quoted-printable': return binascii.a2b_qp(data) else: raise RuntimeError('unknown content transfer encoding: {}' ''.format(encoding))
def decodestring(s, header = 0): if a2b_qp is not None: return a2b_qp(s, header = header) StringIO = StringIO import cStringIO infp = StringIO(s) outfp = StringIO() decode(infp, outfp, header = header) return outfp.getvalue()
def function953(self, arg1016): var549 = self.attribute173[CONTENT_TRANSFER_ENCODING].lower() if (var549 == 'base64'): return base64.b64decode(arg1016) elif (var549 == 'quoted-printable'): return binascii.a2b_qp(arg1016) elif (var549 in ('binary', '8bit', '7bit')): return arg1016 else: raise RuntimeError('unknown content transfer encoding: {}'.format(var549))
def unserialize(s, config, newformat=False, transl=None): ''' Unserializes the string s, and returns the tuple (bit, boards, spacing) ''' # new format uue encoding support if newformat: s = binascii.a2b_qp(s) else: s = s.encode() inp = BytesIO(s) u = pickle.Unpickler(inp) version = u.load() if config.debug: print('unserialized version:', version) # form the units metric = u.load() num_increments = u.load() units = utils.Units(config.english_separator, metric, num_increments, transl) # form the bit width = u.load() depth = u.load() angle = u.load() bit = router.Router_Bit(units, width, depth, angle) # form the boards nb = u.load() boards = [] for _ in lrange(nb): boards.append(router.Board(bit, 10)) # dummy width argument, for now for b in boards: b.width = u.load() b.height = u.load() b.wood = u.load() b.active = u.load() b.dheight = u.load() # form the spacing sp_type = u.load() if sp_type == 'Edit': if config.debug: print('unserialized edit spacing') cuts = u.load() sp = spacing.Edit_Spaced(bit, boards, config) sp.set_cuts(cuts) else: if sp_type == 'Equa': sp = spacing.Equally_Spaced(bit, boards, config) else: sp = spacing.Variable_Spaced(bit, boards, config) sp.params = u.load() if config.debug: print('unserialized ', sp_type, str(sp.params)) sp.set_cuts() return (bit, boards, sp, sp_type)
def __get_xwsse_header(self): nonce = str(time.time()) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)) created_date = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) sha_object = hashlib.sha1(nonce + created_date + self.shared_secret).digest() password_64 = binascii.b2a_base64(sha_object) return 'UsernameToken Username="******", PasswordDigest="%s", Nonce="%s", Created="%s"' % ( self.user_name, password_64.strip(), base64nonce.strip(), created_date)
def decode(self, s): o = JSONDecoder.decode(self, s) pickle_str = o.get(JSONCodec._obj, None) if pickle_str: # file_ver = o[JSONCodec._ver_key] # if file_ver != JSONCodec._ver: # msg = 'Unsopported json-encoded version(%s != %s)!' # raise ValueError(msg % (file_ver, JSONCodec._ver)) pickle_bytes = binascii.a2b_qp(pickle_str.encode(encoding="utf8")) o = pickle.loads(pickle_bytes) return o
def __buildheader(self): """ Returns required header for authenticating API calls. This is an internal method to be used by other public method calls. """ nonce = str(time.time()) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)) created_date = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) sha_object = hashlib.sha1(nonce + created_date + '%s' % (self.__shared_secret)) password_64 = binascii.b2a_base64(sha_object.digest()) X_str = 'UsernameToken Username="******", PasswordDigest="%s", Nonce="%s", Created="%s"' % ('%s:%s' % (self.__user_name, self.__company), password_64.strip(), base64nonce.strip(), created_date) return {'X-WSSE':X_str}
def _decode_content_transfer(self, data: bytes) -> bytes: encoding = self.headers.get(CONTENT_TRANSFER_ENCODING, "").lower() if encoding == "base64": return base64.b64decode(data) elif encoding == "quoted-printable": return binascii.a2b_qp(data) elif encoding in ("binary", "8bit", "7bit"): return data else: raise RuntimeError("unknown content transfer encoding: {}" "".format(encoding))
def _decode_content_transfer(self, data: bytes) -> bytes: encoding = cast(str, self.headers[CONTENT_TRANSFER_ENCODING]).lower() if encoding == 'base64': return base64.b64decode(data) elif encoding == 'quoted-printable': return binascii.a2b_qp(data) elif encoding in ('binary', '8bit', '7bit'): return data else: raise RuntimeError('unknown content transfer encoding: {}' ''.format(encoding))
def xor_hex(str1, str2): try: if len(str2) != len(str1): raise ValueError('Length of strings is not equal') bstr1 = ba.a2b_hex(str1) bstr2 = ba.a2b_hex(str2) tmp = [chr(bstr1[x] ^ bstr2[x]) for x in range(len(bstr1))] outstr = ba.a2b_qp("".join(tmp)) except Exception as e: raise e return ba.b2a_hex(outstr)
def addPadding(message): #print '\n*** PAD ***' # determine number of padding bytes needed padLength = AES_CBC_BLOCK_SIZE - (len(message) % AES_CBC_BLOCK_SIZE) #print 'pad length: ', padLength for i in range(padLength - 1): # add random padding bytes to end of message message = message + 'X' # print 'final pad byte (hex): ', binascii.hexlify(binascii.a2b_qp(chr(padLength-1))) messagePadded = message + binascii.a2b_qp(chr(padLength-1)) # add final padding byte = number of padding bytes added #print 'padded message (hex): ', binascii.hexlify(messagePadded) # print 'padded message length: ', len(messagePadded) return messagePadded
def decode(self, s,): o = JSONDecoder.decode(self, s) pickle_str = o.get(JSONCodec._obj, None) if pickle_str: #file_ver = o[JSONCodec._ver_key] # if file_ver != JSONCodec._ver: # msg = 'Unsopported json-encoded version(%s != %s)!' # raise ValueError(msg % (file_ver, JSONCodec._ver)) pickle_bytes = binascii.a2b_qp(pickle_str.encode( encoding='utf8')) o = pickle.loads(pickle_bytes) return o
def _decode_content_transfer(self, data): encoding = self.headers[CONTENT_TRANSFER_ENCODING].lower() if encoding == 'base64': return base64.b64decode(data) elif encoding == 'quoted-printable': return binascii.a2b_qp(data) elif encoding in ('binary', '8bit', '7bit'): return data else: raise RuntimeError( f'unknown content transfer encoding: {encoding}')
def test_qp(self): # A test for SF bug 534347 (segfaults without the proper fix) try: binascii.a2b_qp("", **{1:1}) except TypeError: pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") self.assertEqual(binascii.a2b_qp("= "), "= ") self.assertEqual(binascii.a2b_qp("=="), "=") self.assertEqual(binascii.a2b_qp("=AX"), "=AX") self.assertRaises(TypeError, binascii.b2a_qp, foo="bar") self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00") self.assertEqual( binascii.b2a_qp("\xff\r\n\xff\n\xff"), "=FF\r\n=FF\r\n=FF" ) self.assertEqual( binascii.b2a_qp("0"*75+"\xff\r\n\xff\r\n\xff"), "0"*75+"=\r\n=FF\r\n=FF\r\n=FF" ) self.assertEqual(binascii.b2a_qp('\0\n'), '=00\n') self.assertEqual(binascii.b2a_qp('\0\n', quotetabs=True), '=00\n') self.assertEqual(binascii.b2a_qp('foo\tbar\t\n'), 'foo\tbar=09\n') self.assertEqual(binascii.b2a_qp('foo\tbar\t\n', quotetabs=True), 'foo=09bar=09\n') self.assertEqual(binascii.b2a_qp('.'), '=2E') self.assertEqual(binascii.b2a_qp('.\n'), '=2E\n') self.assertEqual(binascii.b2a_qp('a.\n'), 'a.\n')
def test_qp(self): if test_support.due_to_ironpython_bug( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=317834" ): return # A test for SF bug 534347 (segfaults without the proper fix) try: binascii.a2b_qp("", **{1: 1}) except TypeError: pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") self.assertEqual(binascii.a2b_qp("= "), "= ") self.assertEqual(binascii.a2b_qp("=="), "=") self.assertEqual(binascii.a2b_qp("=AX"), "=AX") self.assertRaises(TypeError, binascii.b2a_qp, foo="bar") self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00") self.assertEqual(binascii.b2a_qp("\xff\r\n\xff\n\xff"), "=FF\r\n=FF\r\n=FF") self.assertEqual(binascii.b2a_qp("0" * 75 + "\xff\r\n\xff\r\n\xff"), "0" * 75 + "=\r\n=FF\r\n=FF\r\n=FF") self.assertEqual(binascii.b2a_qp("\0\n"), "=00\n") self.assertEqual(binascii.b2a_qp("\0\n", quotetabs=True), "=00\n") self.assertEqual(binascii.b2a_qp("foo\tbar\t\n"), "foo\tbar=09\n") self.assertEqual(binascii.b2a_qp("foo\tbar\t\n", quotetabs=True), "foo=09bar=09\n") self.assertEqual(binascii.b2a_qp("."), "=2E") self.assertEqual(binascii.b2a_qp(".\n"), "=2E\n") self.assertEqual(binascii.b2a_qp("a.\n"), "a.\n")
def test_qp(self): # A test for SF bug 534347 (segfaults without the proper fix) try: binascii.a2b_qp("", **{1: 1}) except TypeError: pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") self.assertEqual(binascii.a2b_qp("= "), "= ") self.assertEqual(binascii.a2b_qp("=="), "=") self.assertEqual(binascii.a2b_qp("=AX"), "=AX") self.assertRaises(TypeError, binascii.b2a_qp, foo="bar") self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00") self.assertEqual(binascii.b2a_qp("\xff\r\n\xff\n\xff"), "=FF\r\n=FF\r\n=FF") self.assertEqual(binascii.b2a_qp("0" * 75 + "\xff\r\n\xff\r\n\xff"), "0" * 75 + "=\r\n=FF\r\n=FF\r\n=FF") self.assertEqual(binascii.b2a_qp('\0\n'), '=00\n') self.assertEqual(binascii.b2a_qp('\0\n', quotetabs=True), '=00\n') self.assertEqual(binascii.b2a_qp('foo\tbar\t\n'), 'foo\tbar=09\n') self.assertEqual(binascii.b2a_qp('foo\tbar\t\n', quotetabs=True), 'foo=09bar=09\n') self.assertEqual(binascii.b2a_qp('.'), '=2E') self.assertEqual(binascii.b2a_qp('.\n'), '=2E\n') self.assertEqual(binascii.b2a_qp('a.\n'), 'a.\n')
def test_qp(self): if test_support.due_to_ironpython_bug( "http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=317834" ): return # A test for SF bug 534347 (segfaults without the proper fix) try: binascii.a2b_qp("", **{1: 1}) except TypeError: pass else: self.fail("binascii.a2b_qp(**{1:1}) didn't raise TypeError") self.assertEqual(binascii.a2b_qp("= "), "= ") self.assertEqual(binascii.a2b_qp("=="), "=") self.assertEqual(binascii.a2b_qp("=AX"), "=AX") self.assertRaises(TypeError, binascii.b2a_qp, foo="bar") self.assertEqual(binascii.a2b_qp("=00\r\n=00"), "\x00\r\n\x00") self.assertEqual(binascii.b2a_qp("\xff\r\n\xff\n\xff"), "=FF\r\n=FF\r\n=FF") self.assertEqual(binascii.b2a_qp("0" * 75 + "\xff\r\n\xff\r\n\xff"), "0" * 75 + "=\r\n=FF\r\n=FF\r\n=FF") self.assertEqual(binascii.b2a_qp('\0\n'), '=00\n') self.assertEqual(binascii.b2a_qp('\0\n', quotetabs=True), '=00\n') self.assertEqual(binascii.b2a_qp('foo\tbar\t\n'), 'foo\tbar=09\n') self.assertEqual(binascii.b2a_qp('foo\tbar\t\n', quotetabs=True), 'foo=09bar=09\n') self.assertEqual(binascii.b2a_qp('.'), '=2E') self.assertEqual(binascii.b2a_qp('.\n'), '=2E\n') self.assertEqual(binascii.b2a_qp('a.\n'), 'a.\n')
def decode(input, output, header = 0): """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. If 'header' is true, decode underscore as space (per RFC 1522).""" if a2b_qp is not None: data = input.read() odata = a2b_qp(data, header=header) output.write(odata) return else: new = '' while 1: line = input.readline() if not line: break i, n = 0, len(line) if n > 0 and line[n - 1] == '\n': partial = 0 n = n - 1 while n > 0 and line[n - 1] in ' \t\r': n = n - 1 else: partial = 1 while i < n: c = line[i] if c == '_' and header: new = new + ' ' i = i + 1 elif c != ESCAPE: new = new + c i = i + 1 elif i + 1 == n and not partial: partial = 1 break elif i + 1 < n and line[i + 1] == ESCAPE: new = new + ESCAPE i = i + 2 elif i + 2 < n and ishex(line[i + 1]) and ishex(line[i + 2]): new = new + chr(unhex(line[i + 1:i + 3])) i = i + 3 else: new = new + c i = i + 1 if not partial: output.write(new + '\n') new = '' if new: output.write(new) return
def decode(input, output, header=0): """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are files with readline() and write() methods. If 'header' is true, decode underscore as space (per RFC 1522).""" if a2b_qp is not None: data = input.read() odata = a2b_qp(data, header=header) output.write(odata) return else: new = '' while 1: line = input.readline() if not line: break i, n = 0, len(line) if n > 0 and line[n - 1] == '\n': partial = 0 n = n - 1 while n > 0 and line[n - 1] in ' \t\r': n = n - 1 else: partial = 1 while i < n: c = line[i] if c == '_' and header: new = new + ' ' i = i + 1 elif c != ESCAPE: new = new + c i = i + 1 elif i + 1 == n and not partial: partial = 1 break elif i + 1 < n and line[i + 1] == ESCAPE: new = new + ESCAPE i = i + 2 elif i + 2 < n and ishex(line[i + 1]) and ishex(line[i + 2]): new = new + chr(unhex(line[i + 1:i + 3])) i = i + 3 else: new = new + c i = i + 1 if not partial: output.write(new + '\n') new = '' if new: output.write(new) return
def decode(input, output, header = 0): if a2b_qp is not None: data = input.read() odata = a2b_qp(data, header = header) output.write(odata) return None new = '' while None: line = input.readline() if not line: break i = 0 n = len(line) if n > 0 and line[n - 1] == '\n': partial = 0 n = n - 1 while n > 0 and line[n - 1] in ' \t\r': n = n - 1 else: partial = 1 while i < n: c = line[i] if c == '_' and header: new = new + ' ' i = i + 1 continue if c != ESCAPE: new = new + c i = i + 1 continue if i + 1 == n and not partial: partial = 1 break continue if i + 1 < n and line[i + 1] == ESCAPE: new = new + ESCAPE i = i + 2 continue if i + 2 < n and ishex(line[i + 1]) and ishex(line[i + 2]): new = new + chr(unhex(line[i + 1:i + 3])) i = i + 3 continue new = new + c i = i + 1 if not partial: output.write(new + '\n') new = '' continue if new: output.write(new)
def onConnect(self, Connection, Status, Description): Domoticz.Log("onConnect called") #MQTT ENABLED if self.mqttClient is not None: self.mqttClient.onConnect(Connection, Status, Description) else: if Status != 0: Domoticz.Error(Description) self._actuatorOnLine = False else: Domoticz.Debug('Connected') self._actuatorOnLine = True Connection.Send(binascii.a2b_qp(self.passwd + '\r\n'))
def string_to_binary(input_string: str) -> str: """Convert Ascii string to binary string. :param input_string: An input Ascii encoded string. :return: The binary encoded equivalence of the input Ascii string. """ byte_from_str = binascii.a2b_qp(input_string) binary_from_byte = bin(int.from_bytes(byte_from_str, byteorder="big")) binary_from_byte = binary_from_byte.replace("b", "") # Make sure what ever being returned is multiple of 8. return f"{'0' * (8 - len(binary_from_byte) % 8)}{binary_from_byte}" \ if len(binary_from_byte) % 8 != 0 \ else binary_from_byte
def __buildheader(self): """ Returns required header for authenticating API calls. This is an internal method to be used by other public method calls. """ nonce = str(time.time()) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)).decode('utf-8') created_date = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()) sha_object = hashlib.sha1((nonce + created_date + '%s' % (self.__shared_secret)).encode('utf-8')) password_64 = binascii.b2a_base64(sha_object.digest()).decode('utf-8') X_str = 'UsernameToken Username="******", PasswordDigest="%s", Nonce="%s", Created="%s"' % ( '%s:%s' % (self.__user_name, self.__company), password_64.strip(), base64nonce.strip(), created_date) return {'X-WSSE': X_str}
def decode(input, output, header=False): """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are binary file objects. If 'header' is true, decode underscore as space (per RFC 1522).""" if a2b_qp is not None: data = input.read() odata = a2b_qp(data, header=header) output.write(odata) return new = b'' while 1: line = input.readline() if not line: break i, n = 0, len(line) if n > 0 and line[n - 1:n] == b'\n': partial = 0 n = n - 1 # Strip trailing whitespace while n > 0 and line[n - 1:n] in b" \t\r": n = n - 1 else: partial = 1 while i < n: c = line[i:i + 1] if c == b'_' and header: new = new + b' ' i = i + 1 elif c != ESCAPE: new = new + c i = i + 1 elif i + 1 == n and not partial: partial = 1 break elif i + 1 < n and line[i + 1:i + 2] == ESCAPE: new = new + ESCAPE i = i + 2 elif i + 2 < n and ishex(line[i + 1:i + 2]) and ishex( line[i + 2:i + 3]): new = new + bytes((unhex(line[i + 1:i + 3]), )) i = i + 3 else: # Bad escape sequence -- leave it in new = new + c i = i + 1 if not partial: output.write(new + b'\n') new = b'' if new: output.write(new)
def decode(encoding, fields): #encoding: An encoding for field in fields: if encoding == 'base64': field.value = binascii.a2b_base64(field.value) elif encoding == 'hex': field.value = binascii.a2b_hex(field.value) elif encoding == 'hqx': field.value = binascii.a2b_hqx(field.value) elif encoding == 'qp': field.value = binascii.a2b_qp(field.value) elif encoding == 'uu': field.value = binascii.a2b_uu(field.value) yield field
def decode(input, output, header=False): """Read 'input', apply quoted-printable decoding, and write to 'output'. 'input' and 'output' are binary file objects. If 'header' is true, decode underscore as space (per RFC 1522).""" if a2b_qp is not None: data = input.read() odata = a2b_qp(data, header=header) output.write(odata) return new = b"" while 1: line = input.readline() if not line: break i, n = 0, len(line) if n > 0 and line[n - 1 : n] == b"\n": partial = 0 n = n - 1 # Strip trailing whitespace while n > 0 and line[n - 1 : n] in b" \t\r": n = n - 1 else: partial = 1 while i < n: c = line[i : i + 1] if c == b"_" and header: new = new + b" " i = i + 1 elif c != ESCAPE: new = new + c i = i + 1 elif i + 1 == n and not partial: partial = 1 break elif i + 1 < n and line[i + 1 : i + 2] == ESCAPE: new = new + ESCAPE i = i + 2 elif i + 2 < n and ishex(line[i + 1 : i + 2]) and ishex(line[i + 2 : i + 3]): new = new + bytes((unhex(line[i + 1 : i + 3]),)) i = i + 3 else: # Bad escape sequence -- leave it in new = new + c i = i + 1 if not partial: output.write(new + b"\n") new = b"" if new: output.write(new)
def set_server_hash(self): """ Compute hash of primary servers and find what is your ip """ rsa_pub_dir = self.configs.loaded_config.get("User", "private key") + ".pub" rsa_pub = open(rsa_pub_dir, 'rb').read() hash = md5() hash.update(rsa_pub) for i in range(3): hash_chunk = hash.copy() #convert int->str->bin hash_chunk.update(a2b_qp(str(i))) self.server_hash.append(hash_chunk.hexdigest())
def url_dehydrate(self, url): if len(url) <= 0: return None url_s = '' crc = binascii.crc32(binascii.a2b_qp(url)) while crc != 0: url_s += str(self.base_map[math.floor(crc % self.base)]) crc = math.floor(crc/ (self.base)) #print (url_s) #url_s = base64.urlsafe_b64encode(url_s.encode()) #logger.info ("{} [{}] ".format(url, url_s.decode()) ) #print (url_s.decode()) return url_s
def bCommand(self, commandstring): data = binascii.a2b_qp("\n" + commandstring + "\r") s = self.serial s.flushInput() resp = bytearray(0) # begin buffered command by sending \n until the device echos \n or times out firstErrorPrinted = False # This is used to prevent repetitive printing # begin loop while (True): s.write(data[0:1]) # send line feed resp_raw = s.read(1) # Will return empty array after timeout if (len(resp_raw) == 0): raise Exception( str(datetime.datetime.now()) + "No response from device") readySig = resp_raw[0] if (readySig == 10): print( str(datetime.datetime.now()) + " -- Starting Buffered command") break elif (readySig == 35): if (not firstErrorPrinted): print("Device busy. Waiting...") firstErrorPrinted = True else: raise Exception("Did not recieve \\n (0x0A) or # as response") resp.append(readySig) # Send buffered data for i in range(1, len(data)): s.write(data[i:i + 1]) resp_raw = s.read(1) # Will return empty array after timeout if (len(resp_raw) == 0): raise Exception( str(datetime.datetime.now()) + "No response from device") resp.append(resp_raw[0]) if (resp[i] != data[i]): raise Exception("Recieved " + str(resp, 'ascii') + " instead of " + str(data[i:i + 1])) if (resp[i] == 13): print( str(datetime.datetime.now()) + " -- Buffered command complete") return resp # This will happen if sending the data failed print(str(datetime.datetime.now()) + " -- Buffered command FAILED") resp_no_whitespace = resp[1:len(resp) - 2] return resp_no_whitespace.decode("ascii")
def next_steps(self): """ Make next steps (generator)""" m = hashlib.md5() m.update(binascii.a2b_qp(self.SALT + ''.join(self.path))) digest = m.hexdigest() moves = [((0, -1), 'U'), ((0, 1), 'D'), ((-1, 0), 'L'), ((1, 0), 'R')] for i, move in enumerate(moves): x = self.x + move[0][0] y = self.y + move[0][1] if x < 0 or y < 0 or x > 3 or y > 3 or (self.x == 3 and self.y == 3): continue if is_open(i, digest): yield MazeState(x, y, path=self.path + [move[1]])
def pad(self, msg): block_len = self.bytes_per_block block_pad = (block_len - len(msg) % block_len) block_pad = (block_len - len(msg) % block_len) * chr(block_pad) block_pad = binascii.a2b_qp(block_pad) # print("size:\t\t", self.bytes_per_block) num_of_substr = int(len(msg + block_pad) / self.bytes_per_block) complete_message = msg + block_pad msg_array = list() for i in range(num_of_substr): msg_array.append( (i, complete_message[i * self.bytes_per_block:(i + 1) * self.bytes_per_block])) return tuple(msg_array)
def is_SSH_req(string): if string == None: return False try : if 'OpenSSH_' in base64.b64decode(string): return True except: pass try : if 'OpenSSH_' in base64.b32decode(string): return True except: pass try : if 'OpenSSH_' in base64.b16decode(string): return True except: pass try : if 'OpenSSH_' in binascii.a2b_uu(string): return True except: pass try : if 'OpenSSH_' in binascii.a2b_base64(string): return True except: pass try : if 'OpenSSH_' in binascii.a2b_qp(string): return True except: pass try : if 'OpenSSH_' in binascii.a2b_hqx(string): return True except: pass try : if 'OpenSSH_' in binascii.a2b_hex(string): return True except: pass try : if 'OpenSSH_' in string: return True except: pass return False
def make_sccrq(self): # make avp avp_data = '' # Start_Control_Request avp_data += self.make_avp(attr_type=0, attr_value=1) # Protocol Version avp_data += self.make_avp(attr_type=2, attr_value=256) # Framing Capabilities avp_data += self.make_avp(attr_type=3, avp_len=10, attr_value1=0, attr_value2=3) # Bearer Capabilities avp_data += self.make_avp(attr_type=4, avp_len=10, attr_value1=0, attr_value2=0) # Firmware Revision avp_data += self.make_avp(attr_type=6, attr_value=1680) # Host Name avp_data += self.make_avp(attr_type=7, avp_len=6 + len(HOSTNAME), avp_raw_data=binascii.a2b_qp(HOSTNAME)) # Vendor Name avp_data += self.make_avp(attr_type=8, avp_len=6 + len(VENDOR), avp_raw_data=binascii.a2b_qp(VENDOR)) # Assigned Tunnel ID avp_data += self.make_avp(attr_type=9, attr_value=64773) # Receive Window Size avp_data += self.make_avp(attr_type=10, attr_value=4) # construct l2tp packet header_data = self.make_header(plen=12 + 87) l2tp_data = header_data + avp_data return l2tp_data
def _build_token(self): nonce = str(uuid.uuid4()) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)) created_date = datetime.utcnow().isoformat() + 'Z' sha_object = sha.new(nonce + created_date + self.secret) password_64 = binascii.b2a_base64(sha_object.digest()) properties = { "Username": self.username, "PasswordDigest": password_64.strip(), "Nonce": base64nonce.strip(), "Created": created_date, } header = 'UsernameToken ' + self._serialize_header(properties) return {'X-WSSE': header}
def _ConvertJSONToBytes(cls, json_dict): """Converts a JSON dictionary into a bytes value. The dictionary of the JSON serialized objects consists of: { '__type__': 'bytes' 'stream': an encoded bytes values. } Args: json_dict (dict[str, object]): JSON serialized objects. Returns: bytes: a bytes value. """ return binascii.a2b_qp(json_dict['stream'])
def verify_crc(self): # From TDesktop's generate.py cleanline = self.dump(self) cleanline = re.sub(r' [a-zA-Z0-9_]+\:flags\.[0-9]+\?true', '', cleanline) cleanline = cleanline.replace('<', ' ').replace('>', ' ').replace(' ', ' ') cleanline = cleanline.replace(':bytes ', ':string ') cleanline = cleanline.replace('?bytes ', '?string ') cleanline = cleanline.replace('{', '').replace('}', '') cleanline = cleanline.strip() if self.crc == binascii.crc32(binascii.a2b_qp(cleanline)): print('WARNING: CRC MISMATCH -- expected {} in: '.format( self.crc2hex(self.crc))) print(self.dump(self), end='\n\n')
def fromDict(cls, d): attrs = {'name': d['name']} if 'index' in d: attrs['index'] = d['index'] if 'ind_vars' in d: attrs['ind_vars'] = [cls.fromDict(v) for v in d['ind_vars']] if 'function' in d: f = types.FunctionType( marshal.loads(binascii.a2b_qp(d['function'][0])), globals(), name=None, argdefs=None, closure=tuple([cls.make_cell(val) for val in d['function'][1]])) attrs['function'] = f return cls(**attrs)
def build_headers(password, username): nonce = str(uuid.uuid4()) base64nonce = binascii.b2a_base64(binascii.a2b_qp(nonce)) created_date = datetime.datetime.utcnow().isoformat() + "Z" sha = nonce + created_date + password sha_object = hashlib.sha1(sha.encode()) password_64 = binascii.b2a_base64(sha_object.digest()) properties = { "Username": username, "PasswordDigest": password_64.decode().strip(), "Nonce": base64nonce.decode().strip(), "Created": created_date, } header = "UsernameToken " + _serialize_header(properties) return {"X-WSSE": header}
def dataReceived(self, data): """ Data sent by the attacker will replace the buffered data """ if not self.mode: if data.startswith("a"): self.transport.write( bcolors.OKBLUE + "Automatic mode selected. Sit back and check the script's output\n" + bcolors.ENDC ) self.mode = "auto" elif data.startswith("m"): self.transport.write(bcolors.OKBLUE + "Manual mode selected.\n" + bcolors.ENDC) self.mode = "manual" else: self.transport.write(bcolors.FAIL + "Invalid option\n" + bcolors.ENDC) self.transport.write(bcolors.OKGREEN + "Select (a)uto or (m)anual mode:\n" + bcolors.ENDC) elif self.mode == "manual" and len(self.buffer): if self.edit: # edit message (packetNo, olddata, source, target) = self.buffer.pop() target.write(a2b_qp(data)) print bcolors.WARNING + "Eve changed some data: " + bcolors.ENDC + "%s" % data self.transport.write(bcolors.OKBLUE + ("%d: OK! Edited\n" % packetNo) + bcolors.ENDC) self.edit = False self.ask() elif data.startswith("e"): # mark message for editing self.edit = True elif data.startswith("f"): # forward it (packetNo, olddata, source, target) = self.buffer.pop() target.write(olddata) self.transport.write(bcolors.OKBLUE + ("%d: OK! Forwarded\n" % packetNo) + bcolors.ENDC) self.ask() elif data.startswith("b"): # block it self.buffer.pop() self.ask() else: # invalid input, ask again self.transport.write( bcolors.OKGREEN + ("%d: (f)orward, (e)dit, (b)lock? " % self.buffer[-1][0]) + bcolors.ENDC ) elif self.mode == "auto": pass
def finalize(self): """Finalize this object. This should be called when no more data should be written to the stream. This function will not raise any exceptions, but it may write more data to the underlying object if there is data remaining in the cache. If the underlying object has a `finalize()` method, this function will call it. """ # If we have a cache, write and then remove it. if len(self.cache) > 0: self.underlying.write(binascii.a2b_qp(self.cache)) self.cache = b'' # Finalize our underlying stream. if hasattr(self.underlying, 'finalize'): self.underlying.finalize()