Programming Forums
User Name Password Register
 

RSS Feed
FORUM INDEX | TODAY'S POSTS | UNANSWERED THREADS | ADVANCED SEARCH

Reply
 
Thread Tools Display Modes
Old Feb 14th, 2006, 8:02 PM   #1
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
[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()
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Old Feb 14th, 2006, 9:59 PM   #2
thechristelegacy
Expert Programmer
 
thechristelegacy's Avatar
 
Join Date: Jul 2004
Location: Somerset, Pa
Posts: 708
Rep Power: 5 thechristelegacy is on a distinguished road
Send a message via AIM to thechristelegacy Send a message via MSN to thechristelegacy
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.
thechristelegacy is offline   Reply With Quote
Old Feb 15th, 2006, 6:31 PM   #3
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
T etg shIe c a' mth:nlaaha)klbkon*s oisg*.sunee*
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!
Jessehk is offline   Reply With Quote
Old Feb 15th, 2006, 8:28 PM   #4
andro
Professional Programmer
 
Join Date: Oct 2005
Location: California
Posts: 311
Rep Power: 3 andro is on a distinguished road
Send a message via AIM to andro
Reminds me of Sandorf's cipher
andro is offline   Reply With Quote
Old Feb 18th, 2006, 12:33 PM   #5
nnxion
Programming Guru
 
nnxion's Avatar
 
Join Date: Jun 2005
Location: elemental plane
Posts: 1,429
Rep Power: 5 nnxion is on a distinguished road
Looks nice. Sweet stuff. Got to learn that Python sometime...
__________________
"Employ your time in improving yourself by other men's writings, so that you shall gain easily what others have labored hard for."
-- Socrates
nnxion is offline   Reply With Quote
Old Feb 18th, 2006, 2:32 PM   #6
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,885
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
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.
Sane is online now   Reply With Quote
Old Feb 18th, 2006, 3:24 PM   #7
Jessehk
The Oblivious One
 
Jessehk's Avatar
 
Join Date: May 2005
Location: Ontario, Canada
Posts: 644
Rep Power: 4 Jessehk is on a distinguished road
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?
__________________
Dr. Zoidberg: [ecstatic] I'm going to a movie... with FRIENDS!

Last edited by Jessehk; Feb 18th, 2006 at 3:53 PM.
Jessehk is offline   Reply With Quote
Old Nov 29th, 2007, 7:11 PM   #8
Sane
Programming Guru
 
Sane's Avatar
 
Join Date: Apr 2005
Location: Waterloo, Ontario
Posts: 1,885
Rep Power: 5 Sane will become famous soon enough
Send a message via MSN to Sane
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.
Sane is online now   Reply With Quote
Reply

Bookmarks

« Previous Thread in Forum | Next Thread in Forum »

Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump




DaniWeb IT Discussion Community
All times are GMT -5. The time now is 7:58 PM.

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