Convert to binary and convert back to strings

Discussion in 'Python' started by Harlin Seritt, Feb 21, 2007.

  1. 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
     
    Harlin Seritt, Feb 21, 2007
    #1
    1. Advertising

  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.
     
    Colin J. Williams, Feb 22, 2007
    #2
    1. Advertising

  3. 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.
     
    Colin J. Williams, Feb 22, 2007
    #3
  4. On Feb 21, 7:02 pm, "Colin J. Williams" <> 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

    >
    > 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
     
    Harlin Seritt, Feb 22, 2007
    #4
  5. On 2007-02-21, Harlin Seritt <> wrote:

    > 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!
     
    Grant Edwards, Feb 22, 2007
    #5
  6. Harlin Seritt

    Larry Bates Guest

    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
     
    Larry Bates, Feb 22, 2007
    #6
  7. On Feb 21, 7:12 pm, Larry Bates <> 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
     
    Harlin Seritt, Feb 22, 2007
    #7
  8. Harlin Seritt

    Guest

    On Feb 21, 5:50 pm, "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


    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, 2007
    #8
  9. On 2007-02-22, Harlin Seritt <> wrote:

    >> 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!
     
    Grant Edwards, Feb 22, 2007
    #9
  10. >>>>> "Harlin" == Harlin Seritt <> writes:

    > 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
     
    Ganesan Rajagopal, Feb 22, 2007
    #10
  11. On 2007-02-22, Ganesan Rajagopal <> wrote:

    >> 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!!
     
    Grant Edwards, Feb 22, 2007
    #11
  12. >>>>> Grant Edwards <> writes:

    >> 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
     
    Ganesan Rajagopal, Feb 22, 2007
    #12
  13. "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?
    >


    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
     
    Hendrik van Rooyen, Feb 22, 2007
    #13
  14. 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 '!"#¤%%'
    #================
     
    Jussi Salmela, Feb 22, 2007
    #14
  15. Harlin Seritt

    Paul Rubin Guest

    Grant Edwards <> writes:
    > > 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)))
     
    Paul Rubin, Feb 22, 2007
    #15
  16. 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.
     
    Steven D'Aprano, Feb 22, 2007
    #16
  17. 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
     
    Jussi Salmela, Feb 22, 2007
    #17
  18. Harlin Seritt

    Neil Cerutti Guest

    On 2007-02-22, Jussi Salmela <> wrote:
    > 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
     
    Neil Cerutti, Feb 22, 2007
    #18
  19. On 2007-02-22, Grant Edwards <> wrote:
    > On 2007-02-22, Ganesan Rajagopal <> wrote:
    >
    >>> 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??
     
    Grant Edwards, Feb 22, 2007
    #19
  20. 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.
     
    Steven D'Aprano, Feb 22, 2007
    #20
    1. Advertising

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

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Klaus Neuner
    Replies:
    7
    Views:
    505
    Klaus Neuner
    Jul 26, 2004
  2. Ben

    Strings, Strings and Damned Strings

    Ben, Jun 22, 2006, in forum: C Programming
    Replies:
    14
    Views:
    787
    Malcolm
    Jun 24, 2006
  3. ruffiano

    Are C++ strings binary strings?

    ruffiano, Nov 1, 2006, in forum: C++
    Replies:
    9
    Views:
    1,175
  4. Kelsey Bjarnason
    Replies:
    6
    Views:
    365
    Richard Tobin
    Feb 6, 2008
  5. Nebiru
    Replies:
    1
    Views:
    106
    Trans
    Sep 16, 2006
Loading...

Share This Page