473,734 Members | 2,375 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Convert to binary and convert back to strings

Hi...

I would like to take a string like 'supercalifragi listicexpialido cius'
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 5084
Harlin Seritt wrote:
Hi...

I would like to take a string like 'supercalifragi listicexpialido cius'
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 'supercalifragi listicexpialido cius'
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 'supercalifragi listicexpialido cius'
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 = 'supercalifragi listicexpialido cius'

open('sambleb.c onf', 'wb').write(tex t)

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

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**********@y ahoo.comwrote:
I would like to take a string like
'supercalifragi listicexpialido cius' 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 'supercalifragi listicexpialido cius'
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(k ey).randrange
if not reverse:
text = zlib.compress(t ext)
text = ''.join([chr(ord(elem)^r and(256)) for elem in text])
if reverse:
text = zlib.decompress (text)
return text

def strToHex(aStrin g):
hexlist = ["%02X" % ord(x) for x in aString]
return ''.join(hexlist )

def HexTostr(hStrin g):
res = ""
for i in range(len(hStri ng)/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.st rftime("%Y%m%d" , time.localtime( ))

print "String:", testStr
etestStr = tinycode(keyStr , testStr)
print "Encrypted string:", etestStr
hex=strToHex(et estStr)
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 'supercalifragi listicexpialido cius'
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(k ey).randrange
if not reverse:
text = zlib.compress(t ext)
text = ''.join([chr(ord(elem)^r and(256)) for elem in text])
if reverse:
text = zlib.decompress (text)
return text

def strToHex(aStrin g):
hexlist = ["%02X" % ord(x) for x in aString]
return ''.join(hexlist )

def HexTostr(hStrin g):
res = ""
for i in range(len(hStri ng)/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.st rftime("%Y%m%d" , time.localtime( ))

print "String:", testStr
etestStr = tinycode(keyStr , testStr)
print "Encrypted string:", etestStr
hex=strToHex(et estStr)
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...@y ahoo.comwrote:
Hi...

I would like to take a string like 'supercalifragi listicexpialido cius'
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_bin ary.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_bin ary.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(in t(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**********@y ahoo.comwrote:
>Try opening your file in the 'wb' mode.
I tried doing this:

text = 'supercalifragi listicexpialido cius'

open('sambleb.c onf', 'wb').write(tex t)

Afterwards, I was able to successfully open the file with a text
editor and it showed:
'supercalifragi listicexpialido cius'
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**********@y ahoo.comwrites:
I tried doing this:
text = 'supercalifragi listicexpialido cius'
open('sambleb.c onf', 'wb').write(tex t)
Afterwards, I was able to successfully open the file with a text
editor and it showed:
'supercalifragi listicexpialido cius'

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 = 'supercalifragi listicexpialido cius'
open('sambleb.c onf', 'w').write(base 64.encodestring (text))

print base64.decodest ring(open('samb leb.conf', 'r').read())

Ganesan

--
Ganesan Rajagopal

Feb 22 '07 #10

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

Similar topics

4
6110
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 like this: $buf = array(0x41, 0x42, 0x43); Anyone know how? I haven't been able to find a way.
13
41817
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
2848
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. I have the calling side working and am capturing the return value into a MemoryStream. Now I'm breaking up the MemoryStream into structures. Some of the values coming back are character arrays which I want to turn into strings. They are not...
2
3411
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 file, convert the FileStream into a string using Unicode encoding, then do a replace, then convert the string back to a byte using Unicode encoding which i then Response.WriteBinary(bytes) to the browser. This works fine although the actual...
13
22112
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 code so that i can process it. i googled many times and tried many of the answers out there, no luck so far. is there a way to convert a string into its binary representation of the
4
5545
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 converting the binary blocks to strings first, then converting the resulting string to base64. This seems highly inefficient and I'd like to just go straight from binary to a base64 string. Here is the conversion we're using from object to...
5
12939
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 password=CAST(@password as binary) However when I go to sql server and convert that binary field to varchar, all I get is the first letter of the password that I typed in. How do I
10
4966
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
5276
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 Convert.FromBase64String seem like the closest thing I can find to what I'm looking for baked into the base class library. Can anyone suggest a better way to do this? TIA - Bob
0
9449
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9310
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9236
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
1
6735
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6031
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4550
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
1
3261
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2724
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2180
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.