Convert to binary and convert back to strings

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Harlin Seritt

    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

  • Colin J. Williams

    #2
    Re: Convert to binary and convert back to strings

    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.

    Comment

    • Colin J. Williams

      #3
      Re: Convert to binary and convert back to strings

      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.

      Comment

      • Harlin Seritt

        #4
        Re: Convert to binary and convert back to strings

        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

        Comment

        • Grant Edwards

          #5
          Re: Convert to binary and convert back to strings

          On 2007-02-21, Harlin Seritt <harlinseritt@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!

          Comment

          • Larry Bates

            #6
            Re: Convert to binary and convert back to strings

            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.



            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

            Comment

            • Harlin Seritt

              #7
              Re: Convert to binary and convert back to strings

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

              >
              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

              Comment

              • mensanator@aol.com

                #8
                Re: Convert to binary and convert back to strings

                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.








                Comment

                • Grant Edwards

                  #9
                  Re: Convert to binary and convert back to strings

                  On 2007-02-22, Harlin Seritt <harlinseritt@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.






                  --
                  Grant Edwards grante Yow! Two with FLUFFO,
                  at hold th' BEETS...side of
                  visi.com SOYETTES!

                  Comment

                  • Ganesan Rajagopal

                    #10
                    Re: Convert to binary and convert back to strings

                    >>>>"Harlin" == Harlin Seritt <harlinseritt@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

                    Comment

                    • Grant Edwards

                      #11
                      Re: Convert to binary and convert back to strings

                      On 2007-02-22, Ganesan Rajagopal <rganesan@myrea lbox.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 = 'supercalifragi listicexpialido cius'
                      open('sambleb.c onf', 'w').write(base 64.encodestring (text))
                      >
                      print base64.decodest ring(open('samb leb.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!!

                      Comment

                      • Ganesan Rajagopal

                        #12
                        Re: Convert to binary and convert back to strings

                        >>>>Grant Edwards <grante@visi.co mwrites:
                        >print base64.decodest ring(open('samb leb.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

                        Comment

                        • Hendrik van Rooyen

                          #13
                          Re: Convert to binary and convert back to strings

                          "Harlin Seritt" <harlinseritt@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?
                          >
                          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

                          Comment

                          • Jussi Salmela

                            #14
                            Re: Convert to binary and convert back to strings

                            Harlin Seritt kirjoitti:
                            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
                            >
                            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('se cret.txt', 'wb', 'zlib_codec')
                            f.write(s)
                            f.close()

                            f = codecs.open('se cret.txt', 'rb', 'zlib_codec')
                            s2 = f.read()
                            f.close()
                            print s2
                            if s == s2: print 'OK'
                            else: print '!"#¤%%'
                            #============== ==

                            Comment

                            • Paul Rubin

                              #15
                              Re: Convert to binary and convert back to strings

                              Grant Edwards <grante@visi.co mwrites:
                              print base64.decodest ring(open('samb leb.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)))

                              Comment

                              Working...