def test_uu(self): if self.type2test is not str and test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171" ): return MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.type2test(self.rawdata[i : i + MAX_UU]) a = binascii.b2a_uu(b) lines.append(a) res = "" for line in lines: a = self.type2test(line) b = binascii.a2b_uu(a) res += b self.assertEqual(res, self.rawdata) self.assertEqual(binascii.a2b_uu("\x7f"), "\x00" * 31) self.assertEqual(binascii.a2b_uu("\x80"), "\x00" * 32) self.assertEqual(binascii.a2b_uu("\xff"), "\x00" * 31) self.assertRaises(binascii.Error, binascii.a2b_uu, "\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, "!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46 * "!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu("x"), "!> \n")
def test_uu(self): if self.type2test is not str and test_support.due_to_ironpython_bug( "http://ironpython.codeplex.com/workitem/28171"): return MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.type2test(self.rawdata[i:i + MAX_UU]) a = binascii.b2a_uu(b) lines.append(a) res = "" for line in lines: a = self.type2test(line) b = binascii.a2b_uu(a) res += b self.assertEqual(res, self.rawdata) self.assertEqual(binascii.a2b_uu("\x7f"), "\x00" * 31) self.assertEqual(binascii.a2b_uu("\x80"), "\x00" * 32) self.assertEqual(binascii.a2b_uu("\xff"), "\x00" * 31) self.assertRaises(binascii.Error, binascii.a2b_uu, "\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, "!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46 * "!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu('x'), '!> \n')
def write_ram(addr, data): data = bytearray(data) s.write("W %u %d\r\n" % (addr, len(data))) _check_return_code() offset = 0 while offset < len(data): end = None for j in range(0, 20): start = offset + j * 45 if start > len(data): break end = min(offset + (j + 1) * 45, len(data)) l = binascii.b2a_uu(data[start:end]) s.write("%s\r\n" % l) chunk = data[offset:end] s.write("%d\r\n" % _compute_checksum(chunk)) r = s.readline() if r == "RESEND\r\n": logging.info("Checksum mismatch during write... retrying") continue elif r == "OK\r\n": offset += 20 * 45 else: raise RuntimeError("Unknown response during write: %s" % r)
def convert(cls): code = input('Type binary code to get translated letters') cls.check_input(code) autocomplete = (ceil(len(code) / 8) * 8) - len(code) code = autocomplete * '0' + code letter = 0 output = '' if cls.choose_endian(): code = reversed(code) for byte in code: if not (letter % 8): output += output.join(':') output += output.join(byte) letter += 1 print('This is your byte code') print(output) output = output.split(':') output.remove('') for key, val in enumerate(output): output[key] = binascii.b2a_uu(val.encode()) output[key] = str(output[key]).replace(r'\n', '').replace('b', '') print('And there is your bytecode translated') print(output)
def uu_encode(input, errors='strict', filename='<data>', mode=0666): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' from cStringIO import StringIO from binascii import b2a_uu # using str() because of cStringIO's Unicode undesired Unicode behavior. infile = StringIO(str(input)) outfile = StringIO() read = infile.read write = outfile.write # Encode write('begin %o %s\n' % (mode & 0777, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return (outfile.getvalue(), len(input))
def encode(in_file, out_file, name=None, mode=None): if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): out_file = open(out_file, 'w') if name is None: name = '-' if mode is None: mode = 438 out_file.write('begin %o %s\n' % (mode & 511, name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n')
def main(): parser= argparse.ArgumentParser(description="Get file") parser.add_argument("output") args= parser.parse_args() # uu.decode(args.output, args.output+".txt") outfile= open(args.output+".txt", "w") f= open(args.output, "rb") try: byte=f.read(1) while byte != "": # num= num= binascii.b2a_uu(byte) outfile.write(num+"\n") byte= f.read(1) finally: f.close() # with open(args.output, "rb") as output: # data= output.read(1) # text= data.decode('utf-8') # for byte in text: # print byte # outfile.write(byte+"\n") outfile.close()
def write_ram_block(self, addr, data): data_len = len(data) for i in range(0, data_len, self.uu_line_size): c_line_size = data_len - i if c_line_size > self.uu_line_size: c_line_size = self.uu_line_size block = data[i:i + c_line_size] bstr = binascii.b2a_uu(block) self.dev_write(bstr) retry = 3 while retry > 0: retry -= 1 self.dev_writeln('%s' % self.sum(data)) status = self.dev_readline() print(status) if status: break if not status: return "timeout" if status == self.RESEND: return "resend" if status == self.OK: return "" # unknown status result panic(status)
def uu_encode(input,errors='strict',filename='<data>',mode=0666): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ assert errors == 'strict' from cStringIO import StringIO from binascii import b2a_uu # using str() because of cStringIO's Unicode undesired Unicode behavior. infile = StringIO(str(input)) outfile = StringIO() read = infile.read write = outfile.write # Encode write('begin %o %s\n' % (mode & 0777, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return (outfile.getvalue(), len(input))
def create_and_write(dbname, file_path): """ Utility to write files to dbname from file_path. :param dbname: Name of the database. :type dbname: str :param file_path: Absolute path of the directory that contains the files. :type file_path: str """ # Note: When the os.urandom() data is encoded to be inserted as a # doc_content in u1db, its size may change depending on the encoding # chosen. So the code is being benchmarked against larger files than # what it may appear to be. db = u1db.open(os.path.join(BASE_DB_PATH, dbname), create=True) files = os.listdir(file_path) for f in files: file_ob = open(os.path.join(file_path, f), "rb") data = "" while True: byte = file_ob.read(45) if not byte: break data += binascii.b2a_uu(byte) file_ob.close() db.create_doc({ "name": f, "data": data }) docs = db.get_all_docs() db.close()
def encode(in_file, out_file, name=None, mode=None): opened_files = [] try: if in_file == '-': in_file = sys.stdin.buffer elif isinstance(in_file, str): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') opened_files.append(in_file) if out_file == '-': out_file = sys.stdout.buffer elif isinstance(out_file, str): out_file = open(out_file, 'wb') opened_files.append(out_file) if name is None: name = '-' if mode is None: mode = 438 out_file.write(('begin %o %s\n' % (mode & 511, name)).encode('ascii')) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) data = in_file.read(45) out_file.write(b' \nend\n') finally: for f in opened_files: f.close()
def encode(in_file, out_file, name = None, mode = None): opened_files = [] try: if in_file == '-': in_file = sys.stdin elif isinstance(in_file, basestring): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') opened_files.append(in_file) if out_file == '-': out_file = sys.stdout elif isinstance(out_file, basestring): out_file = open(out_file, 'wb') opened_files.append(out_file) if name is None: name = '-' if mode is None: mode = 438 out_file.write('begin %o %s\n' % (mode & 511, name)) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) data = in_file.read(45) out_file.write(' \nend\n') finally: for f in opened_files: f.close()
def write_ram_block(self, addr, data): data_len = len(data) self.isp_command("W %d %d\n" % ( addr, data_len )) for i in range(0, data_len, self.uu_line_size): c_line_size = data_len - i if c_line_size > self.uu_line_size: c_line_size = self.uu_line_size block = data[i:i+c_line_size] bstr = binascii.b2a_uu(block) self.dev_write(bstr) self.dev_write("%s\n" % self.sum(data)) status = self.dev_readline() if not status: return "timeout" if status == self.RESEND: return "resend" if status == self.OK: return "" # unknown status result panic(status)
def test_checksum_handles_p3strs_and_binary(): digest = checksum('test_my_market_data_$ymB0l', { 'key1': u'unicode', 'key2': b'binary_data' }) expected = b'4O11 ;<[email protected](JRB1.?D[ZEN!8' assert binascii.b2a_uu(digest).strip() == expected
def get_digsignature(file_path): # Get size of the file totsize = os.path.getsize(file_path) # Open the PE file with fast load file = pefile.PE(file_path, fast_load = True) # Parse the directories for IMAGE_DIRECTORY_ENtRY_SECURITY file.parse_data_directories(directories= [pefile.DIRECTORY_ENTRY['IMAGE_DIRECTORY_ENTRY_SECURITY'] ] ) # Set offset and length of table sigoff = 0 siglen = 0 # Get the entry security directory for s in file.__structures__: if s.name == 'IMAGE_DIRECTORY_ENTRY_SECURITY': sigoff = s.VirtualAddress siglen = s.Size # Now that we have our information we can close the file file.close() if sigoff < totsize: f = open(file_path, 'rb') #move to begininng of signature table f.seek(sigoff) # read signature table thesig = f.read(siglen) f.close() thesig = thesig[8:] return binascii.b2a_uu(thesig) else: return None
def prog_file(self, fname, complete_func=None): """To Program the Microcontroller""" if complete_func: complete_func(0) data_len = os.path.getsize(fname) binfile = open(fname, "rb") block_crc = 0 wr_byts = 0 for block in self.chunked(binfile, 11520): cmd = ("W {} {}".format(0x10000300, len(block))).encode("ascii") self.write_and_expect(cmd, b"0") for chunk in self.chunkedio(block, 900): for number, line in enumerate(self.chunkedio(chunk, 45)): for i, byts in enumerate(line): block_crc += byts wr_byts += 1 if complete_func: complete_func(wr_byts / data_len) cmd = binascii.b2a_uu(line).replace(b" ", b"`").strip() self.write_and_expect(cmd, b"") self.write_and_expect(("{}".format(block_crc)).encode("ascii"), b"OK") block_crc = 0 self.copy_to_sector(len(block), 0x10000300)
def write_ram_block(self, addr, data): data_len = len(data) for i in range(0, data_len, self.uu_line_size): c_line_size = data_len - i if c_line_size > self.uu_line_size: c_line_size = self.uu_line_size block = data[i:i+c_line_size] bstr = binascii.b2a_uu(block) self.dev_write(bstr) retry = 3 while retry > 0: retry -= 1 self.dev_writeln('%s' % self.sum(data)) status = self.dev_readline() if status: break if not status: return "timeout" if status == self.RESEND: return "resend" if status == self.OK: return "" # unknown status result panic(status)
def lock(self): passwd = pbkdf2_hmac( self.alg, bytes(self.keyphrase, "utf-8"), bytes(self.salt, "utf-8"), 100000 ) return b2a_uu(passwd).decode("utf-8").strip(" \n")[:self.length]
def to_uu(data): """ uu编码 :param data: 字符串 :return: 编码后的字符串 """ r = binascii.b2a_uu(force_bytes(data)) return force_text(r)
def bytes_to_ascii(data): " converts bytes to ascii format " from binascii import b2a_uu ascii_string = b2a_uu(data) return ascii_string
def git_output(*commands): try: kwargs = get_subprocess_kwargs() result = subprocess.check_output( [get_git()] + list(commands), **kwargs) result = b2a_uu(result) except: result = "" return result
def encode(in_file, out_file, name=None, mode=None, *, backtick=False): """Uuencode file""" # # If in_file is a pathname open it and change defaults # opened_files = [] try: if in_file == '-': in_file = sys.stdin.buffer elif isinstance(in_file, str): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') opened_files.append(in_file) # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout.buffer elif isinstance(out_file, str): out_file = open(out_file, 'wb') opened_files.append(out_file) # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0o666 # # Remove newline chars from name # name = name.replace('\n', '\\n') name = name.replace('\r', '\\r') # # Write the data # out_file.write( ('begin %o %s\n' % ((mode & 0o777), name)).encode("ascii")) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data, backtick=backtick)) data = in_file.read(45) if backtick: out_file.write(b'`\nend\n') else: out_file.write(b' \nend\n') finally: for f in opened_files: f.close()
def process(value): if self.version == 6: value = socket.inet_pton(socket.AF_INET6, value) else: value = socket.inet_pton(socket.AF_INET, value) if PYVERSION < 3: value = binascii.b2a_uu(value) return value
def uuencode(in_file, out_file, name=None, mode=None): """Uuencode file""" """Implementation of the UUencode and UUdecode functions. encode(in_file, out_file [,name, mode]) decode(in_file [, out_file, mode]) """ # # If in_file is a pathname open it and change defaults # opened_files = [] try: if in_file == '-': in_file = sys.stdin.buffer elif isinstance(in_file, str): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') opened_files.append(in_file) # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout.buffer elif isinstance(out_file, str): out_file = open(out_file, 'wb') opened_files.append(out_file) # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0o666 # # Write the data # out_file.write(('begin %o %s\n' % ((mode & 0o777), name)).encode("ascii")) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) data = in_file.read(45) out_file.write(b' \nend\n') finally: for f in opened_files: f.close()
def encode(self, str, mode): if type(mode).__name__ == 'int': if mode == ENCODE_BASE64: return binascii.b2a_base64(str)[:-1] elif mode == ENCODE_UUENCODE: return binascii.b2a_uu(str)[:-1] elif type(mode).__name__ == 'str': try: return unicode(str).encode(mode) except LookupError: return
def test_uu(self): MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.type2test(self.rawdata[i:i + MAX_UU]) a = binascii.b2a_uu(b) lines.append(a) res = bytes() for line in lines: a = self.type2test(line) b = binascii.a2b_uu(a) res += b self.assertEqual(res, self.rawdata) self.assertEqual(binascii.a2b_uu(b'\x7f'), b'\x00' * 31) self.assertEqual(binascii.a2b_uu(b'\x80'), b'\x00' * 32) self.assertEqual(binascii.a2b_uu(b'\xff'), b'\x00' * 31) self.assertRaises(binascii.Error, binascii.a2b_uu, b'\xff\x00') self.assertRaises(binascii.Error, binascii.a2b_uu, b'!!!!') self.assertRaises(binascii.Error, binascii.b2a_uu, 46 * b'!') self.assertEqual(binascii.b2a_uu(b'x'), b'!> \n')
def uu_encode(input, errors='strict', filename='<data>', mode=438): infile = BytesIO(input) outfile = BytesIO() read = infile.read write = outfile.write write(('begin %o %s\n' % (mode & 511, filename)).encode('ascii')) chunk = read(45) while chunk: write(binascii.b2a_uu(chunk)) chunk = read(45) write(b' \nend\n') return (outfile.getvalue(), len(input))
def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # close_in_file = False close_out_file = False if in_file == '-': in_file = sys.stdin elif isinstance(in_file, basestring): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') close_in_file = True # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, basestring): out_file = open(out_file, 'w') close_out_file = True # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode & 0777), name)) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) data = in_file.read(45) out_file.write(' \nend\n') # Jython and other implementations requires files to be explicitly # closed if we don't want to wait for GC if close_in_file: in_file.close() if close_out_file: out_file.close()
def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # close_in_file = False close_out_file = False if in_file == '-': in_file = sys.stdin elif isinstance(in_file, basestring): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') close_in_file = True # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, basestring): out_file = open(out_file, 'w') close_out_file = True # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) data = in_file.read(45) out_file.write(' \nend\n') # Jython and other implementations requires files to be explicitly # closed if we don't want to wait for GC if close_in_file: in_file.close() if close_out_file: out_file.close()
def uuencode(phenny, input): """uuencode""" for x in phenny.bot.commands["high"].values(): if x[0].__name__ == "aa_hook": if x[0](phenny, input): return # Abort function if not input.group(2): return phenny.reply("Nothing to encode.") q = input.group(2).encode('utf-8') try: return phenny.say(binascii.b2a_uu(q)) except BaseException as e: return phenny.reply(e.message)
def uu_enc(path): wf = open("operation.txt", 'w') if os.path.isfile(path): with open(path) as f: content = f.readlines() for number in content: enc = binascii.b2a_uu(number) wf.write(enc) f.close() wf.close() print("Done.... Data Stored in operation.txt file") sys.exit(0) else: print("There is something wrong with your file name!")
def encode(encoding, fields): #encoding: An encoding for field in fields: if encoding == 'base64': field.value = binascii.b2a_base64(field.value) elif encoding == 'hex': field.value = binascii.b2a_hex(field.value).upper() elif encoding == 'hqx': field.value = binascii.b2a_hqx(field.value) elif encoding == 'qp': field.value = binascii.b2a_qp(field.value) elif encoding == 'uu': field.value = binascii.b2a_uu(field.value) yield field
def test_uu(self): MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.data[i:i+MAX_UU] a = binascii.b2a_uu(b) lines.append(a) res = "" for line in lines: b = binascii.a2b_uu(line) res += b self.assertEqual(res, self.data) self.assertEqual(binascii.a2b_uu("\x7f"), "\x00"*31) self.assertEqual(binascii.a2b_uu("\x80"), "\x00"*32) self.assertEqual(binascii.a2b_uu("\xff"), "\x00"*31) self.assertRaises(binascii.Error, binascii.a2b_uu, "\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, "!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46*"!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu('x'), '!> \n')
def __convert(self, byte): if self.format == TextFormat.BINARY: return (bin(int(binascii.hexlify(byte), 16))[2:]).zfill(8) elif self.format == TextFormat.DECIMAL: return str(int(binascii.hexlify(byte), 16)).zfill(3) elif self.format == TextFormat.HEX: return codecs.decode(binascii.hexlify(byte), 'ascii') elif self.format == TextFormat.ASCII: return codecs.decode(binascii.b2a_uu(byte), 'ascii').rstrip(self.linesep) elif self.format == TextFormat.BASE64: return codecs.decode(binascii.b2a_base64(byte), 'ascii').rstrip('==' + self.linesep) return None
def test_uu(self): MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.data[i:i + MAX_UU] a = binascii.b2a_uu(b) lines.append(a) res = "" for line in lines: b = binascii.a2b_uu(line) res += b self.assertEqual(res, self.data) self.assertEqual(binascii.a2b_uu("\x7f"), "\x00" * 31) self.assertEqual(binascii.a2b_uu("\x80"), "\x00" * 32) self.assertEqual(binascii.a2b_uu("\xff"), "\x00" * 31) self.assertRaises(binascii.Error, binascii.a2b_uu, "\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, "!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46 * "!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu('x'), '!> \n')
def encode(in_file, out_file, name=None, mode=None, *, backtick=False): """Uuencode file""" # # If in_file is a pathname open it and change defaults # opened_files = [] try: if in_file == '-': in_file = sys.stdin.buffer elif isinstance(in_file, str): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') opened_files.append(in_file) # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout.buffer elif isinstance(out_file, str): out_file = open(out_file, 'wb') opened_files.append(out_file) # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0o666 # # Write the data # out_file.write(('begin %o %s\n' % ((mode & 0o777), name)).encode("ascii")) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data, backtick=backtick)) data = in_file.read(45) if backtick: out_file.write(b'`\nend\n') else: out_file.write(b' \nend\n') finally: for f in opened_files: f.close()
def write_ram_block(self, addr, data): data_len = len(data) for i in range(0, data_len, self.uu_line_size): c_line_size = data_len - i if c_line_size > self.uu_line_size: c_line_size = self.uu_line_size block = data[i:i+c_line_size] bstr = binascii.b2a_uu(block).decode("UTF-8")[0:-1] self.dev_writeln(bstr) if self.echo_on: echo = self.dev_readline() if echo != bstr: log("Invalid echo from RAM block") # sometimes the echo could be invalid because a newline was erroneously inserted. # In this case, clear out any remaining lines in the buffer to fix things. self.device._serial.flushInput() retry = 3 status = None while retry > 0: retry -= 1 checksum_str = '%s' % self.sum(data) self.dev_writeln(checksum_str) if self.echo_on: echo = self.dev_readline() if echo != checksum_str: log("Invalid echo from RAM block checksum") continue status = self.dev_readline() if status == self.OK or status == self.RESEND: break if not status: return "timeout" if status == self.RESEND: return "resend" if status == self.OK: return "" # unknown status result panic("Unknown status from writing RAM block: " + status)
def test_uu(self): MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.type2test(self.rawdata[i:i + MAX_UU]) a = binascii.b2a_uu(b) lines.append(a) res = bytes() for line in lines: a = self.type2test(line) b = binascii.a2b_uu(a) res += b self.assertEqual(res, self.rawdata) self.assertEqual(binascii.a2b_uu(b"\x7f"), b"\x00" * 31) self.assertEqual(binascii.a2b_uu(b"\x80"), b"\x00" * 32) self.assertEqual(binascii.a2b_uu(b"\xff"), b"\x00" * 31) self.assertRaises(binascii.Error, binascii.a2b_uu, b"\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, b"!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46 * b"!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu(b'x'), b'!> \n')
def uu_encode(input, errors = 'strict', filename = '<data>', mode = 438): from cStringIO import StringIO from binascii import b2a_uu infile = StringIO(str(input)) outfile = StringIO() read = infile.read write = outfile.write write('begin %o %s\n' % (mode & 511, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return (outfile.getvalue(), len(input))
def uu_encode(input, errors='strict', filename='<data>', mode=438): from cStringIO import StringIO from binascii import b2a_uu infile = StringIO(str(input)) outfile = StringIO() read = infile.read write = outfile.write write('begin %o %s\n' % (mode & 511, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return (outfile.getvalue(), len(input))
def test_uu(self): MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.type2test(self.rawdata[i:i+MAX_UU]) a = binascii.b2a_uu(b) lines.append(a) res = bytes() for line in lines: a = self.type2test(line) b = binascii.a2b_uu(a) res += b self.assertEqual(res, self.rawdata) self.assertEqual(binascii.a2b_uu(b"\x7f"), b"\x00"*31) self.assertEqual(binascii.a2b_uu(b"\x80"), b"\x00"*32) self.assertEqual(binascii.a2b_uu(b"\xff"), b"\x00"*31) self.assertRaises(binascii.Error, binascii.a2b_uu, b"\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, b"!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46*b"!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu(b'x'), b'!> \n')
def encodedata(data, encoding, lower=string.lower): """ Encode data using the given encoding. Possible values for encoding include: 'base64' - BASE 64 encoding 'hex' - HEX encoding (no line breaks) 'hexlines' - HEX encoding (with CR line breaks) In Python 2.0 and up, encoding may also be an encoding supported natively by Python via the codec registry. """ encoding = lower(encoding) if encoding == 'base64': import base64 return base64.encodestring(data) elif encoding == 'hex' or \ encoding == 'hexlines': from mx.TextTools import str2hex import cStringIO result = str2hex(data) if encoding == 'hexlines': return _addlinebreaks(result, 72) return result elif encoding == 'uu': import binascii out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n') return base64.encodestring(data) else: # This works in Python >=2.0 only try: return data.encode(encoding) except AttributeError: raise ValueError, 'unknown encoding "%s"' % encoding
def lpcWriteDataToRam(self, addr_base, data): data_size = len(data) uuline_size = 45 uublock_size = 900 #45 byte length x 20 lines cur_addr = addr_base for i in range(0, data_size, uublock_size): cur_block_size = uublock_size if (data_size - i) <= uublock_size: cur_block_size = data_size - i #--- Process individual blocks data_block = data[i : i + cur_block_size] data_block_size = len(data_block) #--- Set LPC1768 to receive block self.sd.write("W %d %d\n" % (cur_addr, data_block_size)) ret = self.sd.readline() if not ret: hostFault("ERROR: Unable to write data to RAM. Timed out: %s" % ret) elif int(ret) != 0: hostFault("ERROR: Unable to write data to RAM: %d" % int(ret)) #--- Write uuencoded lines (20 lines of 45 bytes) for each block for j in range(0, data_block_size, uuline_size): cur_line_size = uuline_size if (data_block_size - j) <= uuline_size: cur_line_size = data_block_size - j #uu.encode(img_file) uudata = binascii.b2a_uu(data_block[j:j+cur_line_size]) self.sd.write(uudata) #--- Calculate and send string checksum datasum = 0 for ch in data_block: datasum = datasum + ord(ch) self.sd.write("%d\n" % datasum) ret = self.sd.readline() #print "\'" + str(datasum) + "\'" if not ret: hostFault("Error in checksum for RAM write. Timed out: %s" % ret) if ret != "OK\r\n": hostFault("Error in checksum for RAM write: %s" % ret) #--- Move to next block cur_addr = cur_addr + cur_block_size return
def hash_password(self, pw): unhexed = [] shift_pw = [] # convert pw to binary bin_pw = ''.join(format(ord(i), '08b') for i in pw) # Shift digits for bit in bin_pw: shift_pw.append(bit) shift_pw.reverse() rev_pw = ''.join(shift_pw) # Convert to decimal dec_pw = int(rev_pw, 2) # Multiply by diameter of the sun calc_pw = dec_pw * 865370 # Back to binary binary_pw = bin(calc_pw) # Shift digits shift_pw.clear() for bit in binary_pw: shift_pw.append(bit) shift_pw.reverse() rev_pw = '' rev_pw = ''.join(shift_pw) # Convert to Hex bits = [] bites = [] count = 0 for bit in rev_pw: if count < 8: bits.append(bit) count += 1 if count == 8: octet = "".join(bits) hashed = binascii.b2a_uu(bytes(octet, encoding='utf-8')) bites.append(hashed) bits.clear() count = 0 hashed_password = ''.join(str(bites)) # Save / Return hashed password if path.exists(self.master_file) == False: self.save_password(hashed_password) else: return hashed_password
def uu_encode(input, errors='strict', filename='<simba_data>', mode=0o666): assert errors == 'strict' infile = BytesIO(input) outfile = BytesIO() read = infile.read write = outfile.write # Encode write(('begin %o %s\n' % (mode & 0o777, filename)).encode('ascii')) chunk = read(45) while chunk: write(binascii.b2a_uu(chunk)) chunk = read(45) write(b' \nend\n') return (outfile.getvalue(), len(input))
def uu_encode(input, errors='strict', filename='<tmp>', mode=0o666): assert errors == 'strict' infile = BytesIO(input) outfile = BytesIO() read = infile.read write = outfile.write # Encode write(('begin %o %s\n' % (mode & 0o777, filename)).encode('ascii')) chunk = read(45) while chunk: write(binascii.b2a_uu(chunk)) chunk = read(45) write(b' \nend\n') return (outfile.getvalue(), len(input))
def _uu_encode(data, filename='<data>', mode=0666): from cStringIO import StringIO from binascii import b2a_uu infile = StringIO(data) outfile = StringIO() read = infile.read write = outfile.write # Encode write('begin %o %s\n' % (mode & 0777, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return outfile.getvalue()
def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # opened_files = [] try: if in_file == "-": in_file = sys.stdin.buffer elif isinstance(in_file, str): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, "rb") opened_files.append(in_file) # # Open out_file if it is a pathname # if out_file == "-": out_file = sys.stdout.buffer elif isinstance(out_file, str): out_file = open(out_file, "wb") opened_files.append(out_file) # # Set defaults for name and mode # if name is None: name = "-" if mode is None: mode = 0o666 # # Write the data # out_file.write(("begin %o %s\n" % ((mode & 0o777), name)).encode("ascii")) data = in_file.read(45) while len(data) > 0: out_file.write(binascii.b2a_uu(data)) data = in_file.read(45) out_file.write(b" \nend\n") finally: for f in opened_files: f.close()
def test_uu(self): MAX_UU = 45 lines = [] for i in range(0, len(self.data), MAX_UU): b = self.data[i:i+MAX_UU] a = binascii.b2a_uu(b) lines.append(a) res = bytes() for line in lines: b = binascii.a2b_uu(line) res += b self.assertEqual(res, self.data) self.assertEqual(binascii.a2b_uu(b"\x7f"), b"\x00"*31) self.assertEqual(binascii.a2b_uu(b"\x80"), b"\x00"*32) self.assertEqual(binascii.a2b_uu(b"\xff"), b"\x00"*31) self.assertRaises(binascii.Error, binascii.a2b_uu, b"\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, b"!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46*b"!")
def encode(in_file, out_file, name=None, mode=None): """Uuencode file""" # # If in_file is a pathname open it and change defaults # if in_file == '-': in_file = sys.stdin elif isinstance(in_file, StringType): if name is None: name = os.path.basename(in_file) if mode is None: try: mode = os.stat(in_file).st_mode except AttributeError: pass in_file = open(in_file, 'rb') # # Open out_file if it is a pathname # if out_file == '-': out_file = sys.stdout elif isinstance(out_file, StringType): out_file = open(out_file, 'w') # # Set defaults for name and mode # if name is None: name = '-' if mode is None: mode = 0666 # # Write the data # out_file.write('begin %o %s\n' % ((mode&0777),name)) str = in_file.read(45) while len(str) > 0: out_file.write(binascii.b2a_uu(str)) str = in_file.read(45) out_file.write(' \nend\n')
def test_uu(self): MAX_UU = 45 for backtick in (True, False): lines = [] for i in range(0, len(self.data), MAX_UU): b = self.type2test(self.rawdata[i:i+MAX_UU]) a = binascii.b2a_uu(b, backtick=backtick) lines.append(a) res = bytes() for line in lines: a = self.type2test(line) b = binascii.a2b_uu(a) res += b self.assertEqual(res, self.rawdata) self.assertEqual(binascii.a2b_uu(b"\x7f"), b"\x00"*31) self.assertEqual(binascii.a2b_uu(b"\x80"), b"\x00"*32) self.assertEqual(binascii.a2b_uu(b"\xff"), b"\x00"*31) self.assertRaises(binascii.Error, binascii.a2b_uu, b"\xff\x00") self.assertRaises(binascii.Error, binascii.a2b_uu, b"!!!!") self.assertRaises(binascii.Error, binascii.b2a_uu, 46*b"!") # Issue #7701 (crash on a pydebug build) self.assertEqual(binascii.b2a_uu(b'x'), b'!> \n') self.assertEqual(binascii.b2a_uu(b''), b' \n') self.assertEqual(binascii.b2a_uu(b'', backtick=True), b'`\n') self.assertEqual(binascii.a2b_uu(b' \n'), b'') self.assertEqual(binascii.a2b_uu(b'`\n'), b'') self.assertEqual(binascii.b2a_uu(b'\x00Cat'), b'$ $-A= \n') self.assertEqual(binascii.b2a_uu(b'\x00Cat', backtick=True), b'$`$-A=```\n') self.assertEqual(binascii.a2b_uu(b'$`$-A=```\n'), binascii.a2b_uu(b'$ $-A= \n')) with self.assertRaises(TypeError): binascii.b2a_uu(b"", True)
def uu_encode(input, errors = 'strict', filename = '<data>', mode = 438): """ Encodes the object input and returns a tuple (output object, length consumed). errors defines the error handling to apply. It defaults to 'strict' handling which is the only currently supported error handling for this codec. """ raise errors == 'strict' or AssertionError from cStringIO import StringIO from binascii import b2a_uu infile = StringIO(str(input)) outfile = StringIO() read = infile.read write = outfile.write write('begin %o %s\n' % (mode & 511, filename)) chunk = read(45) while chunk: write(b2a_uu(chunk)) chunk = read(45) write(' \nend\n') return (outfile.getvalue(), len(input))
def encode(pk): from binascii import b2a_uu from struct import pack return b2a_uu(pack("!L", pk))[0:-1]
c, noise = noise[0], noise[1:] res = res + c return res + noise + line res = "" for line in map(addnoise, lines): b = binascii.a2b_base64(line) res = res + b assert res == testdata # Test uu print "uu test" MAX_UU = 45 lines = [] for i in range(0, len(testdata), MAX_UU): b = testdata[i:i+MAX_UU] a = binascii.b2a_uu(b) lines.append(a) print a, res = "" for line in lines: b = binascii.a2b_uu(line) res = res + b assert res == testdata # Test crc32() crc = binascii.crc32("Test the CRC-32 of") crc = binascii.crc32(" this string.", crc) if crc != 1571220330: print "binascii.crc32() failed." # The hqx test is in test_binhex.py
"""Test the binascii C module.""" from test_support import verify, verbose import binascii # Show module doc string print binascii.__doc__ # Show module exceptions print binascii.Error print binascii.Incomplete # Check presence and display doc strings of all functions funcs = [] for suffix in "base64", "hqx", "uu": prefixes = ["a2b_", "b2a_"] if suffix == "hqx": prefixes.extend(["crc_", "rlecode_", "rledecode_"]) for prefix in prefixes: name = prefix + suffix funcs.append(getattr(binascii, name)) for func in funcs: print "%-15s: %s" % (func.__name__, func.__doc__) # Create binary test data testdata = "The quick brown fox jumps over the lazy dog.\r\n" for i in range(256): # Be slow so we don't depend on other modules testdata = testdata + chr(i) testdata = testdata + "\r\nHello world.\n" # Test base64 with valid data print "base64 test" MAX_BASE64 = 57 lines = [] for i in range(0, len(testdata), MAX_BASE64):