Re: [Tutor] flag to call methods on objects?
(You replied off-list, so I'm copying your email, plus my response, to the list) prasad rao wrote: >I still see four problems. Hello Dave.I made modification as suggested by you. You made the first three. But the problem of zlib.compress() producing a string with an embedded (0a) still hasn't been addressed. And I suspect this is your next problem. If you don't give the whole string that zlib.compress() produced to zlib.uncompress(), then it'll fail as you saw here. import mcript Traceback (most recent call last): File "", line 1, in import mcript File "C:\Python26\mcript.py", line 84, in a.main() File "C:\Python26\mcript.py", line 65, in main nl= self.__shorten(self.__undigi(self.__decompress(line.strip(+'\n' File "C:\Python26\mcript.py", line 47, in __decompress astring=zlib.decompress(astring) error: Error -5 while decompressing data on interactive mode it is(decompress())working well. What should I do to rectifi this error? I dont know java,know basics of c++ I started to lear python hardly onyear back. This is my 1st program using classes. Thanks for your time. #! usr/bin/env python import ast,random,os,zlib,string key=5 class Cripto(object): def __init__(self,afile): self.afile=afile def __digi(self,astring): y=[] for x in astring: y.append(ord(x)) y=str(y) return y def __undigi(self,astring): alist=ast.literal_eval(astring) y=[] for x in alist: y.append(chr(x)) astring=''.join(y) return astring def __gen_string(self): s='' nl=random.sample(string.ascii_letters,key) for x in nl:s+=x return s def __lengthen(self,astring): s=list(astring) ns='' for x in s: ns+=x ns+=self.__gen_string() return ns def __shorten(self,astring): s=list(astring) ns='' for x in range(0,len(s),key+1): ns+=s[x] return ns def __compress(self,astring): astring=zlib.compress(astring) return astring def __decompress(self,astring): astring=zlib.decompress(astring) return astring def main(self): sorce=open(self.afile,'r') data=(sorce.readlines()) dest=open((os.path.split(self.afile)[0]+os.sep+'temp'),'w') if (data[0]).strip()=='flag1': ns='flag0\n' data=data[1:] for line in data: nl= self.__compress(self.__digi(self.__lengthen(line.strip(+'\n' ns+=nl dest.write(ns) elif data[0].strip()=='flag0': ns='flag1\n' data=data[1:] for line in data: nl= self.__shorten(self.__undigi(self.__decompress(line.strip(+'\n' ns+=nl dest.write(ns) else: print 'File does not begin with the flag' sorce.close() dest.close() os.remove(os.path.split(self.afile)[0]+os.sep+'temp') return sorce.close() dest.close() os.remove(self.afile) os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) # a=Cripto('C:/pp.txt') a.main() There are a couple of places where indentation has been broken. For example, in method __shorten(), the for loop body isn't indented. Are you retyping these, or are you using tabs in your source, or is paste broken on your system? What Python version are you using? It's clear that you're using Windows, so you will need to store the encoded file as binary. Furthermore, something I didn't spot before is that strip() isn't safe on the compressed data. You said you tested the lower-level functions manually. But they're not correct, so clearly it's past time to put in place some form of test harness. To properly test the code, you'll need to remove most of those double-underscores. And I'd suggest factoring out two methods, encode() and decode(), as follows: def encode(self, unencoded): nl= self.__compress(self.digi(self.lengthen(unencoded.strip(+'\n' return nl def decode(self, encoded): nl= self.shorten(self.undigi(self.__decompress(encoded.strip(+'\n' return nl I don't have your data file to test with, so I may not get exactly the same errors. In fact, multiple runs with the same data give different results. Sometimes I get bad data, and sometimes an exception like yours. Probably that's because of the random string you append in lengthen(). But the crash itself is probably caused by the bug I described in #4 of my previous message. zlib.compress() produces binary data, and you're assuming leading and trailing whitespace is irrelevant, and that there are no embedded 0a codes. So the first test I wrote was: def test_lengthen(line): xx = a.lengthen(line)
Re: [Tutor] flag to call methods on objects?
prasad rao wrote: hello I removed the bugs.But still getting error report. import mcript Traceback (most recent call last): File "", line 1, in import mcript File "C:\Python26\mcript.py", line 78, in a.main() File "C:\Python26\mcript.py", line 58, in main nl=__compress(__digi(__lengthen(line.strip(+'\n' NameError: global name '_Cripto__compress' is not defined There is no string '_Cripto__compress' any whare in the script. So I dont know what corrections Ineed to make in the script. I am giving my code below again again . #! usr/bin/env python import ast,random,os,zlib,string key=5 class Craipto(object): def __init__(self,afile): self.afile=afile def __digi(self,astring): y=[] for x in astring: y.append(ord(x)) y=str(y) return y def __undigi(self,astring): alist=ast.literal_eval(astring) y=[] for x in alist: y.append(chr(x)) astring=''.join(y) return astring def __gen_string(self): s='' nl=random.sample(string.ascii_letters,key) for x in nl:s+=x return s def __lengthen(self,astring): s=list(astring) ns='' for x in s: ns+=x ns+=gen_string() return ns def __shorten(self,astring): s=list(astring) ns='' for x in range(0,len(s),key+1): ns+=s[x] return ns def __compress(self,astring): astring=zlib.compress(astring) return astring def __decompress(self,astring): astring=zlib.decompress(astring) return astring def main(self): sorce=open(self.afile,'r') data=(sorce.readlines()) dest=open((os.path.split(self.afile)[0]+os.sep+'temp'),'w') if (data[0]).strip()=='flag1': ns='flag0\n' data=data[1:] for line in data: nl= __compress(__digi(__lengthen(line.strip(+'\n' ns+=nl dest.write(ns) elif data[0].strip()=='flag0': ns='flag1\n' data=data[1:] for line in data: nl= __shorten((__undigi(__decompress(line.strip()+'\n' ns+=nl dest.write(ns) else:prind 'File does not begin with the flag' sorce.close() dest.close() os.remove(self.afile) os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) # a=Cripto('C:/pp.txt') a.main() <\code> I still see four problems. Your runtime error occurs because you omitted the "self" on the call to self.__compress(). In fact, you omit it nearly everywhere. Without it, Python will look for a global name, which doesn't exist. Second problem is that you spelled "print" as "prind" in your else clause. Third is that when you do detect that the file doesn't begin properly, you still truncate the file to nothing. The else clause should be roughly: else: print "File is malformed, no signature at beginning" sorce.close() dest.close() os.remove( the temp file ) return Fourth is that you're separating the "lines" of the encoded file with a newline character, but I suspect that zlib.compress makes no promises about avoiding that character(0a). If I'm right, you'll need another approach. Either escape the byte sequence in __compress(), or use a count instead of a separator. In either case, you'll need binary mode for that part of the file I/O, if you want to be able to run on Windows. There are a few other comments I could make about the code. First, why did you make it a class? Perhaps your last language was Java, which forces you into that particular paradigm? You never use self in any of the methods except for __init__() and main(). And once main() is finished, you now longer need the object. That should tell you that you could make them all regular functions, and pass the filename directly to main(). Next, why the double-underscore prefix on most of the methods? The only effect that has on execution is that the error message shows a "mangled" version of the function name. When it's a global, it mangles it with the module name (_Cripto__compress), and when it's a method, it uses the class name. DaveA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flag to call methods on objects?
On Thu, Jul 30, 2009 at 11:29 PM, prasad rao wrote: > hello > I removed the bugs.But still getting error report. > > > >>import mcript > > Traceback (most recent call last): > File "", line 1, in > import mcript > File "C:\Python26\mcript.py", line 78, in > a.main() > File "C:\Python26\mcript.py", line 58, in main > That line tells you where the problem is > nl=__compress(__digi(__lengthen(line.strip(+'\n' > That's the code that produced the error > NameError: global name '_Cripto__compress' is not defined > You're trying to call a method __compress which doesn't exist. self.__compress exists, but __compress doesn't. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flag to call methods on objects?
On Thu, Jul 30, 2009 at 09:11:42AM -0500, Wayne wrote: > If you're only partially concerned (i.e. don't care about 'real' encryption) > you can use some of the string library encryptions. Please don't get used to calling these "encryption". They have nothing at all to do with encrypting data. (Well, ROT13 does, I suppose, but not seriously). They are for "encoding" which is simply representing data in a different FORMAT. They do not encrypt data. Yes, people have actually tried "encrypting" passwords sent between browsers and web apps using base64 and suchlike. BIG mistake. You do say that somewhat, but I think using the word "encryption" or implying that these represent a casual level of encryption, is just leading to trouble. These are things a lot of people can decode in their heads. Libraries like the Python Cryptography Toolkit provide real encryption very easily if you need encryption. > Of course any of these methods presume you're just trying to keep the casual > snoop from getting access to your data. Anyone with time/inclination/tools > can go ahead and break most encryptions. In one line of code, you can convert a string to base64 or hex and get a string that would take anyone caring to about 2 seconds to reverse, using tools as simple as most text editors, python itself, or for that matter some network monitoring programs which might pick up that data in flight would just automatically decode that for you. However, in only another line or so of code, you can encrypt your data using AES or Blowfish or whatever, which would require highly specialized tools, extremely expensive equipment, and if you were not either a major government, independently wealthy and very motivated to get that data, it's not going to be broken. -- Steve Willoughby| Using billion-dollar satellites st...@alchemy.com | to hunt for Tupperware. ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flag to call methods on objects?
prasad rao wrote: On 7/30/09, Dave Angel wrote: prasad rao wrote: hello "it is not working." is not very descriptive. DaveA Hello! Sorry, I forgot to mention the problem. It simply wipes clean the file,resulting in empty file. Yes .I should compare with a string.Hope I will get it right with that correction. That's due to another bug in the main() method. You have an if, elif, but no else clause when you're checking the first line. So if you have a file that does *not* begin with the magic string, it'll get truncated. Probably not part of your spec. DaveA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flag to call methods on objects?
On 7/30/09, Dave Angel wrote: > > prasad rao wrote: > >> hello >> >> >"it is not working." is not very descriptive. >> >> >> DaveA >> >Hello! Sorry, I forgot to mention the problem. It simply wipes clean the file,resulting in empty file. Yes .I should compare with a string.Hope I will get it right with that correction. Thank you Wayne. I never know string module can be used for encryption. I will try all those methods(shown by you) in my module. Thank you all Prasad ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flag to call methods on objects?
prasad rao wrote: hello I wanted to prevent other users of my computers to read my files. So tried to creat a module to achieve it. I used a flag to deside which methods to be called on the object. somehow it is not working.I realise after 2 days of struggle that as it is usuel , I am blind to my faults. I tested all the metheds except main() in idle interactively,found them working. So there is a bug in the main(), kan anyone point it out to me? #! usr/bin/env python import ast,random,os,zlib,string key=5 class Cripto(object): def __init__(self,afile): self.afile=afile def __digi(self,astring): y=[] for x in astring: y.append(ord(x)) y=str(y) return y def __undigi(self,astring): alist=ast.literal_eval(astring) y=[] for x in alist: y.append(chr(x)) astring=''.join(y) return astring def __gen_string(self): s='' nl=random.sample(string.ascii_letters,key) for x in nl:s+=x return s def __lengthen(self,astring): s=list(astring) ns='' for x in s: ns+=x ns+=gen_string() return ns def __shorten(self,astring): s=list(astring) ns='' for x in range(0,len(s),key+1): ns+=s[x] return ns def __compress(self,astring): astring=zlib.compress(astring) return astring def __decompress(self,astring): astring=zlib.decompress(astring) return astring def main(self): sorce=open(self.afile,'r') data=(sorce.readlines()) dest=open ((os.path.split(self.afile)[0]+os.sep+'temp'),'w') if data[:1]=='flag1\n': ns='flag0\n' data=data[1:] for line in data: nl=__compress((__digi(__lengthen(line.strip()+'\n' ns+=nl dest.write(ns) elif data[:1]=='flag0\n': ns='flag1\n' data=data[1:] for line in data: nl=__decompress((__undigi(__shorten(line.strip()+'\n' ns+=nl dest.write(ns) sorce.close() dest.close() os.remove(self.afile) os.rename((os.path.split(self.afile)[0]+os.sep+'temp'),self.afile) # a=Cripto('C:/pp.txt') a.main() <\code> First problem is the indentation. It won't compile as it is. I'll assume that was somehow a pasting error. Next problem is where you're comparing for 'flag1'Your line if data[:1] == 'flag1\n' is comparing a list on the left side to a string on the right. If it were me, I'd replace that test, and the similar one below it, with if data[0].rstrip()=='flag1': The reason for the rstrip() is to make it easier for a test harness, where it may be a pain to get the newlines on each line. Also, it's harder to spot a whitespace error. Next problem/question is whether this is only going to be used for files that happen to begin with a line flag1. If so, it should be documented as part of the code, along with all the other missing documentation/docstrings. That's as far as I went; I did not test the actual encoding logic But some free advice for next time:When you ask a question, please supply a compilable program, and either test data, or enough description that we can build such. And please tell us what the symptom is. "it is not working." is not very descriptive. DaveA ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flag to call methods on objects?
On Thu, Jul 30, 2009 at 8:49 AM, prasad rao wrote: > > > On 7/30/09, Rich Lovely wrote: >> >> 2009/7/30 prasad rao prasadarao...@gmail.com: > > > > > >I'm sure there are modules available for PGP that are either part of >> >the stdlib, or available from a quick google. PGP (or GPG) encryopts >> > > I never know there is an encryption module in stdlib. > What is its name? > If you're only partially concerned (i.e. don't care about 'real' encryption) you can use some of the string library encryptions. def test_encod(mystr): mystr = str(mystr) print "%s zip encoded: %s" % (mystr, mystr.encode('zip')) print "%s rot13 encoded: %s" % (mystr, mystr.encode('rot13')) print "%s hex encoded: %s" % (mystr, mystr.encode('hex')) print "%s Base 64 encoded: %s" % (mystr, mystr.encode('base64')) In [41]: test_encode("The quick brown fox jumps over the lazy dogs") The quick brown fox jumps over the lazy dogs zip encoded: xœ ÉHU(,ÍLÎVH*Ê/ÏSH˯PÈ*Í-(VÈ/K-R(Jç$VU*¤ä§l)M The quick brown fox jumps over the lazy dogs rot13 encoded: Gur dhvpx oebja sbk whzcf bire gur ynml qbtf The quick brown fox jumps over the lazy dogs hex encoded: 54686520717569636b2062726f776e20666f78206a756d7073206f76657220746865206c617a7920646f6773 The quick brown fox jumps over the lazy dogs Base 64 encoded: VGhlIHF1aWNrIGJyb3duIGZveCBqdW1wcyBvdmVyIHRoZSBsYXp5IGRvZ3M= So you could easily convert with encode and then reconvert with decode. Another option would be a simple XOR of your data ( from here: http://www.evanfosmark.com/2008/06/xor-encryption-with-python/ ) from itertools import izip, cycle def xor_crypt_string(data, key): return ''.join(chr(ord(x) ^ ord(y)) for (x,y) in izip(data, cycle(key))) On the page provided someone also gave their code that can encrypt files. Of course any of these methods presume you're just trying to keep the casual snoop from getting access to your data. Anyone with time/inclination/tools can go ahead and break most encryptions. HTH, Wayne ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] flag to call methods on objects?
On 7/30/09, Rich Lovely wrote: > > 2009/7/30 prasad rao prasadarao...@gmail.com: >I'm sure there are modules available for PGP that are either part of > >the stdlib, or available from a quick google. PGP (or GPG) encryopts > I never know there is an encryption module in stdlib. What is its name? Prasad ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor