Programming Forums

Programming Forums (http://www.programmingforums.org/forumindex.php)
-   Show Off Your Open Source Projects (http://www.programmingforums.org/forum52.html)
-   -   [Python] Grid encryptor (http://www.programmingforums.org/showthread.php?t=8410)

Jessehk Feb 14th, 2006 9:02 PM

[Python] Grid encryptor
 
I failed to complete this in C when I was first starting out, but I think this python program does it well enough.

basically, a word is entered, like hello. The word is padded with *'s to make its length a perfect square. Therefore, input of hello is padded to form hello***.

The input is then arranged into a square:

h e l
l o *
* * *

and read in reverse: hl*eo*l**

:

"""grid-encrypt - Encrypt and Decrypt text using a grid"""

import math

class GridEncrypt:
        """Encrypt text

        Encrypt text using the grid method. Whereby text is converted into a square,
        and returned in alternative order."""
        squares = [x ** 2 for x in range(1, 101)]
       
        def encrypt(self, word):
                """Encrypt text

                Encrypt text by using a grid and return the result"""
                if type(word) != type('abc'):
                        raise TypeError("Input string not found.")

                paddedWord = self.__padWord(word)

                #split up into list of lists
                self.grid = []
                seperator = math.sqrt(self.squareSize)
               
                count = 1
                temp = []
               
                for x in paddedWord:
                        if count <= seperator:
                                temp.append(x)
                                count += 1
                               
                        if count > seperator:
                                self.grid.append(temp)
                                temp = []
                                count = 1
       
                self.final = []
                pos = 0
               
                for n in range(int(math.sqrt(self.squareSize))):
                        for row in self.grid:
                                self.final.append(row[n])
                               
                return "".join(self.final)
                       

        def __padWord(self, wrd):
                word = [x for x in wrd]
               
                if len(word) in GridEncrypt.squares:
                        self.squareSize = len(wrd)
                        return word
                else:
                        #pad word with filler to make length a perfect square...
                        for x in GridEncrypt.squares:
                                if len(word) < x:
                                        value = x - len(word)
                                        self.squareSize = x
                                        break
                       
                        word.extend('*' * value) #word is now padded with appropriate values
                        return word
                       
        def decrypt(self, word):
                """Decrypt text

                Decrypt text previously encrypted by the encrypt() function"""
                if not (len(word) in GridEncrypt.squares):
                        raise ValueError("Invalid input given.")
               
                #construct list of lists
                grid, temp = ([], [])
                count = 1
                seperator = int(math.sqrt(len(word)))
               
                for x in word:
                        if count <= seperator:
                                temp.append(x)
                                count += 1
       
                        if count > seperator:
                                grid.append(temp)
                                count = 1
                                temp = []               

                final = []
                for a in range(seperator):
                        for row in grid:
                                final.append(row[a])

                return "".join(final)


def main():
        ge = GridEncrypt()
        encrypted = ge.encrypt(raw_input("Enter message to encrypt: "))
        print "\n\nText Encrypted: %s" % encrypted
        print "\n\nText decrypted: %s" % ge.decrypt(encrypted)

if __name__ == '__main__':
        main()


thechristelegacy Feb 14th, 2006 10:59 PM

Text Encrypted: Nr qel.ioWuli*fgoilk*trrt.e*yake * ms Ii*p. w t*


Text decrypted: Nifty program. Works quite well. I like it.******


Edit: It would be nice in the program if the user had the option of entering encrypted text and having it decrypted. Perhaps read from a file even if the message is large enough.

Jessehk Feb 15th, 2006 7:31 PM

T etg shIe c a' mth:nlaaha)klbkon*s oisg*.sunee*

andro Feb 15th, 2006 9:28 PM

Reminds me of Sandorf's cipher

nnxion Feb 18th, 2006 1:33 PM

Looks nice. Sweet stuff. Got to learn that Python sometime...:rolleyes:

Sane Feb 18th, 2006 3:32 PM

Quote:

Originally Posted by thechristelegacy
It would be nice in the program if the user had the option of entering encrypted text and having it decrypted. Perhaps read from a file even if the message is large enough.

Well it looks like the goal of his script was to make an importable function you could use to those lengths.

He actually set it up so it would work just as it does for sha1, base64, md5 or any other encryption in Python.

:

from base64 import encodestring
print base64.encodestring("code")

:

from GridEncrypt import GridEncrypt
print GridEncrypt.encrypt("code")

Really nice Jessehk. That's a cool encryption.

Jessehk Feb 18th, 2006 4:24 PM

Quote:

Originally Posted by Sane

:

from base64 import encodestring
print base64.encodestring("code")

:

from GridEncrypt import GridEncrypt
print GridEncrypt.encrypt("code")

Really nice Jessehk. That's a cool encryption.


Thanks for the compliments everybody. Currently, the program works like this
eg:

:

g = GridEncrypt()
print g.encrypt("hello, world")


but I'd like to change it the way Sane specified.

Give me about 10 minutes :p

EDIT: How does one create static methods in python
like:

:

class GridEncrypt:
    def encrypt(word):
          #do stuff


So it could be called like this:

GridEncrypt.encrypt("hello")

without creating an object?

Sane Nov 29th, 2007 8:11 PM

Re: [Python] Grid encryptor
 
>>>
Massive Bump Alert!
>>>

I read this thread a year ago when Jessehk made this post, but I never saw his edit. It has taken me almost two full years to find and reply to his edit. Sorry for the delay!! XD

Even if he doesn't need it anymore, I bet someone can make a use of my answer. And Jessehk may find the response entertaining, who knows. This is one way to do what you asked:

GridEncrypt.py
:

class main:
    def __call__(self, word):
        # Do Some Stuff
        return 'Encrypted ' + word
   
class GridEncrypt:
    encrypt = main()


my_script.py
:

from GridEncrypt import GridEncrypt
print GridEncrypt.encrypt("code")


Quote:

>>>
Encrypted code
>>>
Hope this helps. XD

But here's the funny part. There's no real point in doing this, because it's not how the base64 module behaves. I messed up in the snippet I posted before.

:

from base64 import encodestring
print encodestring("code")


That's how it actually is. So you don't need any "static class" to mimic that behaviour. But there you go anyways. Hahaha.


All times are GMT -5. The time now is 9:14 AM.

Powered by vBulletin® Version 3.7.0, Copyright ©2000 - 2008, Jelsoft Enterprises Ltd.
Copyright ©2007 DaniWeb® LLC