473,396 Members | 1,810 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

Convert to binary and convert back to strings

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

Feb 22 '07 #1
29 5048
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
Try opening your file in the 'wb' mode.

Colin W.
Feb 22 '07 #2
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
Try opening your file in the 'wb' mode.

Colin W.

Feb 22 '07 #3
On Feb 21, 7:02 pm, "Colin J. Williams" <c...@sympatico.cawrote:
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

Try opening your file in the 'wb' mode.

Colin W.
Thanks for the help.

I tried doing this:

text = 'supercalifragilisticexpialidocius'

open('sambleb.conf', 'wb').write(text)

Afterwards, I was able to successfully open the file with a text
editor and it showed:
'supercalifragilisticexpialidocius'

I am hoping to have it show up some weird un-readable text. And then
of course be able to convert it right back to a string. Is this even
possible?

Thanks,

Harlin

Feb 22 '07 #4
On 2007-02-21, Harlin Seritt <ha**********@yahoo.comwrote:
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.
Why wouldn't they be able to read it? ASCII _is_ binary.
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?
What you're describing as "this" doesn't seem to make any
sense.

--
Grant Edwards grante Yow! Kids, don't gross me
at off... "Adventures with
visi.com MENTAL HYGIENE" can be
carried too FAR!
Feb 22 '07 #5
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
Feb 22 '07 #6
On Feb 21, 7:12 pm, Larry Bates <lba...@websafe.comwrote:
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

Feb 22 '07 #7
On Feb 21, 5:50 pm, "Harlin Seritt" <harlinser...@yahoo.comwrote:
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
import gmpy # GNU Multi-Prceision library for Python

f = open('getty.txt','r')
s = f.read()
f.close

print
print 'source file:'
print
print s

count = 0
f = open('getty_binary.txt','w')
for c in s:
o = ord(c)
b = gmpy.digits(o,2)
d = '0'*(8-len(b)) + b
w = '%s ' % d
f.write(w)
count += 1
if count % 5==0:
f.write('\n')
f.close

f = open('getty_binary.txt','r')
s = f.readlines()
f.close

print
print 'binary file:'
print

for i in s:
print i,
print

c = []
for k in s:
q = k.split()
for m in q:
c.append(chr(int(m,2)))

new_s = ''.join(c)

print
print 'decoded binary:'
print
print new_s
print
## output
## source file:
##
## Four score and seven years ago,
## our fathers brought forth on this continent
## a new nation, conceived in liberty
## and dedicated to the propostion that
## all men are created equal.
##
##
## binary file:
##
## 01000110 01101111 01110101 01110010 00100000
## 01110011 01100011 01101111 01110010 01100101
## 00100000 01100001 01101110 01100100 00100000
## 01110011 01100101 01110110 01100101 01101110
## 00100000 01111001 01100101 01100001 01110010
## 01110011 00100000 01100001 01100111 01101111
## 00101100 00001010 01101111 01110101 01110010
## 00100000 01100110 01100001 01110100 01101000
## 01100101 01110010 01110011 00100000 01100010
## 01110010 01101111 01110101 01100111 01101000
## 01110100 00100000 01100110 01101111 01110010
## 01110100 01101000 00100000 01101111 01101110
## 00100000 01110100 01101000 01101001 01110011
## 00100000 01100011 01101111 01101110 01110100
## 01101001 01101110 01100101 01101110 01110100
## 00001010 01100001 00100000 01101110 01100101
## 01110111 00100000 01101110 01100001 01110100
## 01101001 01101111 01101110 00101100 00100000
## 01100011 01101111 01101110 01100011 01100101
## 01101001 01110110 01100101 01100100 00100000
## 01101001 01101110 00100000 01101100 01101001
## 01100010 01100101 01110010 01110100 01111001
## 00001010 01100001 01101110 01100100 00100000
## 01100100 01100101 01100100 01101001 01100011
## 01100001 01110100 01100101 01100100 00100000
## 01110100 01101111 00100000 01110100 01101000
## 01100101 00100000 01110000 01110010 01101111
## 01110000 01101111 01110011 01110100 01101001
## 01101111 01101110 00100000 01110100 01101000
## 01100001 01110100 00001010 01100001 01101100
## 01101100 00100000 01101101 01100101 01101110
## 00100000 01100001 01110010 01100101 00100000
## 01100011 01110010 01100101 01100001 01110100
## 01100101 01100100 00100000 01100101 01110001
## 01110101 01100001 01101100 00101110 00001010
##
##
## decoded binary:
##
## Four score and seven years ago,
## our fathers brought forth on this continent
## a new nation, conceived in liberty
## and dedicated to the propostion that
## all men are created equal.


Feb 22 '07 #8
On 2007-02-22, Harlin Seritt <ha**********@yahoo.comwrote:
>Try opening your file in the 'wb' mode.
I tried doing this:

text = 'supercalifragilisticexpialidocius'

open('sambleb.conf', 'wb').write(text)

Afterwards, I was able to successfully open the file with a text
editor and it showed:
'supercalifragilisticexpialidocius'
Of course it did.
I am hoping to have it show up some weird un-readable text.
And then of course be able to convert it right back to a
string. Is this even possible?
Sure. That's what is called "encryption". There are a bunch
of encryption libraries for Python.

http://www.amk.ca/python/code/crypto
http://www.freenet.org.nz/ezPyCrypto
http://www.example-code.com/python/encryption.asp
http://www.chilkatsoft.com/python-encryption.asp

--
Grant Edwards grante Yow! Two with FLUFFO,
at hold th' BEETS...side of
visi.com SOYETTES!
Feb 22 '07 #9
>>>>"Harlin" == Harlin Seritt <ha**********@yahoo.comwrites:
I tried doing this:
text = 'supercalifragilisticexpialidocius'
open('sambleb.conf', 'wb').write(text)
Afterwards, I was able to successfully open the file with a text
editor and it showed:
'supercalifragilisticexpialidocius'

I am hoping to have it show up some weird un-readable text. And then
of course be able to convert it right back to a string. Is this even
possible?
Looks like you just want to obfuscate the string. How about this?

import base64
text = 'supercalifragilisticexpialidocius'
open('sambleb.conf', 'w').write(base64.encodestring(text))

print base64.decodestring(open('sambleb.conf', 'r').read())

Ganesan

--
Ganesan Rajagopal

Feb 22 '07 #10
On 2007-02-22, Ganesan Rajagopal <rg******@myrealbox.comwrote:
>I am hoping to have it show up some weird un-readable text.
And then of course be able to convert it right back to a
string. Is this even possible?

Looks like you just want to obfuscate the string. How about
this?

import base64
text = 'supercalifragilisticexpialidocius'
open('sambleb.conf', 'w').write(base64.encodestring(text))

print base64.decodestring(open('sambleb.conf', 'r').read())
It'll only remain obfuscated for about 30 seconds after even a
mildly curious user looks at the file.

--
Grant Edwards grante Yow! INSIDE, I have the
at same personality disorder
visi.com as LUCY RICARDO!!
Feb 22 '07 #11
>>>>Grant Edwards <gr****@visi.comwrites:
>print base64.decodestring(open('sambleb.conf', 'r').read())
It'll only remain obfuscated for about 30 seconds after even a
mildly curious user looks at the file.
It depends on the requirement. If the intention is to just to
discourage someone with messing around with some config
settings, it's good enough. If the user can figure out that
it's base64 encoded and takes pains to decode, modify, encode
and save it back, then he's earned the right to mess around
;-).

Ganesan

--
Ganesan Rajagopal

Feb 22 '07 #12
"Harlin Seritt" <ha**********@yahoo.comwrote:

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?
I would xor each char in it with 'U' as a mild form of obfuscation...

Look at the array module to get things you can xor, or use ord() on
each byte, and char()

Note that char(ord('U')) is 'U', and ord('U') is the equivalent of 0x55,
or five sixteens plus five - 85.

If its ascii just writing it out as binary is useless for what you want to do.

This will invert every alternate bit, producing apparent gibberish.

HTH - Hendrik

Feb 22 '07 #13
Harlin Seritt kirjoitti:
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
Here's my suggestion using compression. Seems to work, but a word of
warning: I've never used the codecs explicitly before!

#==============
# -*- coding: cp1252 -*-
import codecs

s = 'This is so secret that it must be hidden åäö€'
print s
f = codecs.open('secret.txt', 'wb', 'zlib_codec')
f.write(s)
f.close()

f = codecs.open('secret.txt', 'rb', 'zlib_codec')
s2 = f.read()
f.close()
print s2
if s == s2: print 'OK'
else: print '!"#¤%%'
#================
Feb 22 '07 #14
Grant Edwards <gr****@visi.comwrites:
print base64.decodestring(open('sambleb.conf', 'r').read())
It'll only remain obfuscated for about 30 seconds after even a
mildly curious user looks at the file.
You could use the mult127 function, self-inverting like its better
known but more easily recognized rot13 relative:

def mult127(text):
return ''.join(map(chr, ((127*ord(c)) % 256 for c in text)))
Feb 22 '07 #15
On Wed, 21 Feb 2007 16:46:19 -0800, Harlin Seritt wrote:
>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!

Is this beautiful enough?

>>s = "Python"
u = unicode(s, "ascii")
u
u'Python'
>>u.encode('rot13')
'Clguba'
For extra security, you can encode the string with rot13 twice.

--
Steven.

Feb 22 '07 #16
Steven D'Aprano kirjoitti:
On Wed, 21 Feb 2007 16:46:19 -0800, Harlin Seritt wrote:
>>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!


Is this beautiful enough?

>>>s = "Python"
u = unicode(s, "ascii")
u
u'Python'
>>>u.encode('rot13')
'Clguba'
For extra security, you can encode the string with rot13 twice.
Like this? ;)
>>s = "Python" ; u = unicode(s, "ascii") ; u
u'Python'
>>u.encode('rot13')
'Clguba'
>>u.encode('rot13').encode('rot13')
'Python'
Cheers,
Jussi
Feb 22 '07 #17
On 2007-02-22, Jussi Salmela <ti*********@hotmail.comwrote:
Steven D'Aprano kirjoitti:
>On Wed, 21 Feb 2007 16:46:19 -0800, Harlin Seritt wrote:
>>>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!


Is this beautiful enough?

>>>>s = "Python"
u = unicode(s, "ascii")
u
u'Python'
>>>>u.encode('rot13')
'Clguba'
For extra security, you can encode the string with rot13 twice.

Like this? ;)
>s = "Python" ; u = unicode(s, "ascii") ; u
u'Python'
>u.encode('rot13')
'Clguba'
>u.encode('rot13').encode('rot13')
'Python'
Woah! You better quadruple it instead.

How about Double Pig Latin?

No, wait! Use the feared UDPLUD code.

You go Ubbi Dubbi to Pig Latin, and then Ubbi Dubbi again.

Let's see here... Ubububythubububonubpubay

That's what I call ubububeautubububifubububulbubay.

--
Neil Cerutti
This is not a book to be put down lightly. It should be thrown with great
force. --Dorothy Parker
Feb 22 '07 #18
On 2007-02-22, Grant Edwards <gr****@visi.comwrote:
On 2007-02-22, Ganesan Rajagopal <rg******@myrealbox.comwrote:
>>I am hoping to have it show up some weird un-readable text.
And then of course be able to convert it right back to a
string. Is this even possible?

Looks like you just want to obfuscate the string. How about
this?

import base64
text = 'supercalifragilisticexpialidocius'
open('sambleb.conf', 'w').write(base64.encodestring(text))

print base64.decodestring(open('sambleb.conf', 'r').read())

It'll only remain obfuscated for about 30 seconds after even a
mildly curious user looks at the file.
I should add that even "strong" encryption will only slow down
a curious user by 10 minutes if the encryption/decryption key
is embedded in the program...

Trying to hide things from users is usually futile unless you
want put a lot of work into it...

--
Grant Edwards grante Yow! Do you have exactly
at what I want in a plaid
visi.com poindexter bar bat??
Feb 22 '07 #19
On Thu, 22 Feb 2007 11:55:22 +0000, Jussi Salmela wrote:
>For extra security, you can encode the string with rot13 twice.

Like this? ;)
>>s = "Python" ; u = unicode(s, "ascii") ; u
u'Python'
>>u.encode('rot13')
'Clguba'
>>u.encode('rot13').encode('rot13')
'Python'

Exactly! People will think that you're using some terribly advanced
encryption algorithm that looks like plain text, and think "anything that
clever is way too clever for me" and just give up.
--
Steven.

Feb 22 '07 #20
On Thu, 22 Feb 2007 08:18:07 +0200, Hendrik van Rooyen wrote:
I would xor each char in it with 'U' as a mild form of obfuscation...
I've often wished this would work.
>>'a' ^ 'U'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for ^: 'str' and 'str'

instead of the more verbose
>>chr(ord('a') ^ ord('U'))
'4'

Look at the array module to get things you can xor, or use ord() on
each byte, and char()
Arrays don't support XOR any more than strings do. What's the advantage to
using the array module if you still have to jump through hoops to get it
to work?

''.join([chr(ord(c) ^ 85) for c in text])

is probably about as simple as you can get.

--
Steven.

Feb 22 '07 #21
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrites:
Arrays don't support XOR any more than strings do. What's the advantage to
using the array module if you still have to jump through hoops to get it
to work?
It's a lot faster. Sometimes that matters.
Feb 22 '07 #22
On Thu, 22 Feb 2007 14:29:13 -0800, Paul Rubin wrote:
Steven D'Aprano <st***@REMOVE.THIS.cybersource.com.auwrites:
>Arrays don't support XOR any more than strings do. What's the advantage to
using the array module if you still have to jump through hoops to get it
to work?

It's a lot faster. Sometimes that matters.
But is it?
>>import array
import timeit

def flip1(text):
.... mask = ord('U')
.... return ''.join([chr(ord(c) ^ mask) for c in text])
....
>>def flip2(text):
.... mask = ord('U')
.... text = array.array('b', [b ^ mask for b in array.array('b',text)])
.... return text.tostring()
....
>>text = "Python"
setup = 'from __main__ import flip1, flip2, text'

timeit.Timer('flip1(text)', setup).repeat()
[25.757978916168213, 23.174431085586548, 23.188597917556763]
>>timeit.Timer('flip2(text)', setup).repeat()
[25.736327886581421, 25.76999306678772, 26.135013818740845]
For a short string like "Python", using an array is a tiny bit slower, at
the cost of more complex code.

What about for a long string?
>>text = 'Python'*1000

timeit.Timer('flip1(text)', setup).repeat(3, 2000)
[24.483185052871704, 26.007826089859009, 24.498424053192139]
>>timeit.Timer('flip2(text)', setup).repeat(3, 2000)
[12.18204402923584, 12.342558860778809, 12.16040301322937]

Well, that answers that question -- if you're converting a long string,
using array is faster. If it is a short string, it doesn't make much
difference.

--
Steven D'Aprano

Feb 23 '07 #23
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrites:
For a short string like "Python", using an array is a tiny bit slower, at
the cost of more complex code.... if you're converting a long string,
using array is faster. If it is a short string, it doesn't make much
difference.
I modified your array version slightly:

def flip3(text):
n = len(text)
mask = ord('U')
text = array('b', text)
for i in xrange(n):
text[i] ^= mask
return text.tostring()

and I got flip3("Python") a little faster than the listcomp version,
but yeah, I was concerned mostly about long strings.

For fixed-sized short strings, using array('l') and unrolling the loop
makes a big difference:

text = "Pythonic"
mask = array('l','UUUU')[0]

def flip4(text):
text = array('l', text)
text[0] ^= mask
text[1] ^= mask
return text.tostring()
>>timeit.Timer('flip1(text)', setup).repeat() # your version
[35.932021141052246, 36.262560844421387, 40.019834041595459]
>>timeit.Timer('flip3(text)', setup).repeat() # flip3 above
[33.44039511680603, 31.375681161880493, 31.374078035354614]
>>timeit.Timer('flip4(text)', setup).repeat() # flip4 above
[15.349261045455933, 15.526498794555664, 15.351589202880859]

See http://www.nightsong.com/phr/crypto/p3.py for an encryption
routine written this way.
Feb 23 '07 #24
"Steven D'Aprano" <st***@REMOVE.THIS.cybersource.com.auwrote:

On Thu, 22 Feb 2007 08:18:07 +0200, Hendrik van Rooyen wrote:
I would xor each char in it with 'U' as a mild form of obfuscation...

I've often wished this would work.
>'a' ^ 'U'
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: unsupported operand type(s) for ^: 'str' and 'str'

instead of the more verbose
>chr(ord('a') ^ ord('U'))
'4'
you are not alone in this - to do something simple like calculating a BCC on a
string, or a checksum like at the end of a line in an Intel hex file is a bit of
a pain
in Python.
>
Look at the array module to get things you can xor, or use ord() on
each byte, and char()

Arrays don't support XOR any more than strings do. What's the advantage to
using the array module if you still have to jump through hoops to get it
to work?
I think you will have less function calls, but I may be wrong:

s = 'some string that needs a bcc appended'
ar = array.array('B',s)
bcc = 0
for x in ar[:]:
bcc ^= x
ar.append(bcc)
s=ar.tostring()
>
''.join([chr(ord(c) ^ 85) for c in text])

is probably about as simple as you can get.
This is nice and compact.

It would be very nice if you could just use a single char string like
an int and apply the operators to it - the Python way seems so left-
handed - make it an int, do the work, make it back into a string -
and all the time we are working on essentially a one byte value...

- Hendrik

Feb 23 '07 #25
"Hendrik van Rooyen" <ma**@microcorp.co.zawrites:
s = 'some string that needs a bcc appended'
ar = array.array('B',s)
bcc = 0
for x in ar[:]:
bcc ^= x
ar.append(bcc)
s=ar.tostring()
Untested:

import operator
s = 'some string that needs a bcc appended'
ar = array.array('B',s)
s += chr(reduce(operator.xor, ar))
Feb 23 '07 #26


Neil Cerutti wrote:
Woah! You better quadruple it instead.
How about Double Pig Latin?
No, wait! Use the feared UDPLUD code.
You go Ubbi Dubbi to Pig Latin, and then Ubbi Dubbi again.
Let's see here... Ubububythubububonubpubay
That's what I call ubububeautubububifubububulbubay.
That looks slightly like the toy language that Swedish kids refer to as
the robbers language: You double each consonant, and place an o between
each such double consonant. So, applying that to Python, you would get
popytothohonon. Actually, one of the largest Swedish telecom companies
has used this toy language in one of their commercials.

/MiO
Feb 23 '07 #27
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
To my mind, the more sensible job you do at programming this the worse
off you are, unless you use strong encryption. There are nearly
infinite approaches, so the random approach you use will be part of the
"security" of the obfuscation.

OK, I am not really taking this so seriously, but it is a fun question
(Python makes these minor things fun). Is there anyway to do this in
Python? You bet, so many ways... here's another:

s="""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?"""

s0=s+"$"
s2="0 ".join([str(ord(c)) for c in s])
s1="".join([chr(int(i[:-1])) for i in s2.split("
")[:-1]])+chr(int(s2[-1]))[:-1]

def codeMe(s):
s0=s+"$"
return "0 ".join([str(ord(c)) for c in s0])

def uncodeMe(s):
return "".join([chr(int(i[:-1])) for i in s.split("
")[:-1]])+chr(int(s[-1]))[:-1]

def testit(s):
s2=codeMe(s)
s1=uncodeMe(s2)
strings={"original":s, "obfuscated":s2, "decoded":s1}
for k in strings.keys():
print k,": ","\n",strings[k], "\n\n"

testit(s)

-------------
the obfuscated looks like this:

730 320 1190 1110 1170 1080 1000 320 1080 1050 1070 1010 320 1160 1110
320 1160 970 1070 1010 320 970 320 1150 1160 1140 1050 1100 1030 320
1080 1050 1070 1010 320 390 1150 1170 1120 1010 1140 990 970 1080 1050
1020 1140 970 1030 1050 1080 1050 1150 1160 1050 990 1010 1200 1120 1050
970 1080 1050 1000 1110 990 1050 1170 1150 390 100 970 1100 1000 320
1190 1140 1050 1160 1010 320 1050 1160 320 1160 1110 320 970 320 1020
1050 1080 1010 320 1050 1100 320 980 1050 1100 970 1140 1210 320 1020
1110 1140 1090 1150 320 450 450 320 1160 1040 1050 1150 320 1190 970
1210 320 970 320 1170 1150 1010 1140 320 990 970 1100 1100 1110 1160 320
1140 1010 970 1000 100 1160 1040 1010 320 1150 1160 1140 1050 1100 1030
320 1050 1100 320 990 970 1150 1010 320 1160 1040 1010 1210 320 1190
1010 1140 1010 320 1160 1140 1210 320 1160 1110 320 1110 1120 1010 1100
320 1050 1100 320 1150 1110 1090 1010 1160 1040 1050 1100 1030 320 1080
1050 1070 1010 320 970 1150 990 1050 1050 320 1160 1010 1200 1160 100
1010 1000 1050 1160 1110 1140 460 320 730 390 1000 320 970 1080 1150
1110 320 1080 1050 1070 1010 320 1160 1110 320 980 1010 320 970 980 1080
1010 320 1160 1110 320 1140 1010 970 1000 320 1160 1040 1010 320 980
1050 1100 970 1140 1210 320 1020 1110 1140 1090 1010 1000 320 1000 970
1160 970 320 980 970 990 1070 100 1050 1100 1160 1110 320 1150 1160 1140
1050 1100 1030 320 1020 1110 1140 1090 970 1160 320 1150 1110 320 1160
1040 970 1160 320 1050 1160 320 1150 1040 1110 1190 1150 320 1160 1040
1010 320 1110 1140 1050 1030 1050 1100 970 1080 320 1180 970 1080 1170
1010 460 320 730 1150 320 1160 1040 1010 1140 1010 320 970 1100 1210 100
1190 970 1210 320 1160 1110 320 1000 1110 320 1160 1040 1050 1150 320
1050 1100 320 800 1210 1160 1040 1110 1100 630 36

Of course some overly curious application user may note the pattern of
"0" endings, strip those off, concatenate the numbers, and try several
conversions on them, at which point they may figure this out- and
contact you to gloat that they have hacked the file.

That's when you recruit them onto your development team and give them
some real work. :-)

Have fun
EP

Feb 23 '07 #28
"Paul Rubin" <http://ph****@NOSPAM.invalidwrote:
"Hendrik van Rooyen" <ma**@microcorp.co.zawrites:
s = 'some string that needs a bcc appended'
ar = array.array('B',s)
bcc = 0
for x in ar[:]:
bcc ^= x
ar.append(bcc)
s=ar.tostring()

Untested:

import operator
s = 'some string that needs a bcc appended'
ar = array.array('B',s)
s += chr(reduce(operator.xor, ar))
Yikes! - someday soon I am going to read the docs on
what reduce does...

Won't this be slow because of the double function call on each char?

- Hendrik

Feb 24 '07 #29
"Hendrik van Rooyen" <ma**@microcorp.co.zawrites:
s += chr(reduce(operator.xor, ar))
Yikes! - someday soon I am going to read the docs on what reduce does...
Reduce just intersperses an operator over a sequence. For example,
reduce(operator.add, (a,b,c,d,e))
is a+b+c+d+e.
Won't this be slow because of the double function call on each char?
I think there's the same number of func calls, one xor per char.
Feb 24 '07 #30

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

4
by: David Lawson | last post by:
I know how to conver a string to an array of strings, but I need to convert an ascii string to an array of integers (really unsigned chars). Eg, $str ="ABC"; needs to convert to something...
13
by: Hako | last post by:
I try this command: >>> import string >>> string.atoi('78',16) 120 this is 120 not 4E. Someone can tell me how to convert a decimal number to hex number? Can print A, B, C,DEF. Thank you.
3
by: craig.wagner | last post by:
I've got an application that is calling a command-line executable. The command-line tool uses stdin and stdout as its interface, and it expects a binary stream in and sends a binary stream out. ...
2
by: Christopher Beltran | last post by:
I am currently trying to replace certain strings, not single characters, with other strings inside a word document which is then sent to a browser as a binary file. Right now, I read in the word...
13
by: HNT20 | last post by:
Hello All i am new to python language. i am working on a gnuradio project where it uses python as the primary programming language. i am trying to convert a message, text, or numbers into binary...
4
by: Russell Warren | last post by:
I've got a case where I want to convert binary blocks of data (various ctypes objects) to base64 strings. The conversion calls in the base64 module expect strings as input, so right now I'm...
5
by: =?Utf-8?B?YmJkb2J1ZGR5?= | last post by:
I am having a problem converting string to binary and I am hoping someone can help me out I have a sql query that does an update that updates a binary field calles password ...
10
by: cmdolcet69 | last post by:
Public ArrList As New ArrayList Public bitvalue As Byte() Public Sub addvalues() Dim index As Integer ArrList.Add(100) ArrList.Add(200) ArrList.Add(300) ArrList.Add(400) ArrList.Add(500)
6
by: Bob Altman | last post by:
Hi all, I'm looking for the fastest way to convert an array of bytes to String. I also need to convert a String back to its original Byte() representation. Convert.ToBase64String and...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.