On Feb 21, 7:12 pm, Larry Bates <[EMAIL PROTECTED]> wrote: > Harlin Seritt wrote: > > Hi... > > > I would like to take a string like 'supercalifragilisticexpialidocius' > > and write it to a file in binary forms -- this way a user cannot read > > the string in case they were try to open in something like ascii text > > editor. I'd also like to be able to read the binary formed data back > > into string format so that it shows the original value. Is there any > > way to do this in Python? > > > Thanks! > > > Harlin > > I promise you that everything written to a file is done in binary. > Computers don't know how to work with anything BUT binary. I think > what you want to do is to encrypt/obstifucate the string. For that > you will need to encrypt the string, write it out, read it back in, > and decrypt it. If you want it to be REALLY strong use pyCrypto > and something like AES-256. > > http://www.amk.ca/python/code/crypto > > If you just want to make it somewhat hard for someone to decypher > you can do something like below (sorry I can't remember where I > found this to attribute to someone): > import random > import zlib > import time > > def tinycode(key, text, reverse=False): > rand = random.Random(key).randrange > if not reverse: > text = zlib.compress(text) > text = ''.join([chr(ord(elem)^rand(256)) for elem in text]) > if reverse: > text = zlib.decompress(text) > return text > > def strToHex(aString): > hexlist = ["%02X" % ord(x) for x in aString] > return ''.join(hexlist) > > def HexTostr(hString): > res = "" > for i in range(len(hString)/2): > realIdx = i*2 > res = res + chr(int(hString[realIdx:realIdx+2],16)) > return res > > if __name__ == "__main__": > > keyStr = "This is a key" > #testStr = "which witch had which witches wrist watch abc def ghi" > > testStr=time.strftime("%Y%m%d", time.localtime()) > > print "String:", testStr > etestStr = tinycode(keyStr, testStr) > print "Encrypted string:", etestStr > hex=strToHex(etestStr) > print "Hex : ", hex > print "Len(hex):", len(hex) > nonhex=HexTostr(hex) > #testStr = tinycode(keyStr, etestStr, reverse=True) > testStr = tinycode(keyStr, nonhex, reverse=True) > print "Decrypted string:", testStr > > WARNING: THIS IS NOT A STRONG ENCRYPTION ALGORITHM. It is just a > nuisance for someone that really wants to decrypt the string. But > it might work for your application. > > -Larry
Thanks Larry! I was looking for something more beautiful but what the hey, it works! Harlin -- http://mail.python.org/mailman/listinfo/python-list