Convert to binary and convert back to strings

H

Harlin Seritt

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
 
C

Colin J. Williams

Harlin said:
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.
 
C

Colin J. Williams

Harlin said:
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.
 
H

Harlin Seritt

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
 
G

Grant Edwards

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.
 
L

Larry Bates

Harlin said:
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
 
H

Harlin Seritt

Harlin said:
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?

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
 
M

mensanator

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.
 
G

Grant Edwards

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
 
G

Ganesan Rajagopal

Harlin" == Harlin Seritt said:
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
 
G

Grant Edwards

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.
 
G

Ganesan Rajagopal

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
 
H

Hendrik van Rooyen

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
 
J

Jussi Salmela

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 '!"#¤%%'
#================
 
P

Paul Rubin

Grant Edwards said:
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)))
 
S

Steven D'Aprano

Thanks Larry! I was looking for something more beautiful but what the
hey, it works!


Is this beautiful enough?

'Clguba'


For extra security, you can encode the string with rot13 twice.
 
J

Jussi Salmela

Steven D'Aprano kirjoitti:
Is this beautiful enough?


'Clguba'


For extra security, you can encode the string with rot13 twice.

Like this? ;)
'Python'


Cheers,
Jussi
 
N

Neil Cerutti

Steven D'Aprano kirjoitti:

Like this? ;)

'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.
 
G

Grant Edwards

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...
 
S

Steven D'Aprano

Like this? ;)

'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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,904
Latest member
HealthyVisionsCBDPrice

Latest Threads

Top