9 Replies - 5381 Views - Last Post: 18 February 2011 - 04:45 PM Rate Topic: -----

#1 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Python Challenge: Can you break my code?

Post icon  Posted 14 February 2011 - 02:16 PM

Ever wanted to build your own cipher/encryption method? I did, I actually built a pretty nice one using Java a few years ago. I think it could have caused some pause for professional code breakers, especially because of how unconventional it was. Here's my challenge to you, build a funky encryption or ciphering method. The only rule is that you CAN NOT import anything except the random module :) No hashlib for you guys.

Make it as weird or complex as you want. Extra cool points are awarded if you also supply a decipher function. I'll provide an extremely trivial ciphering program as an example:

def cipher(givenString): 
    retString = "" 
    for letter in givenString: 
        if letter.isalpha(): #skip non a-z characters 
            if letter == 'z': 
                retString += 'a' 
            elif letter == 'Z': 
                retString += 'A' 
            else: 
                retString += chr(ord(letter)+1) 
        else: 
            retString += letter 
    return retString

def deCipher(givenString): 
    retString = "" 
    for letter in givenString: 
        if letter.isalpha(): #skip non a-z characters 
            if letter == 'a': 
                retString += 'z' 
            elif letter == 'A': 
                retString += 'Z' 
            else: 
                retString += chr(ord(letter)-1) 
        else: 
            retString += letter 
    return retString


I'm looking for creativity! Let's see what you got!

UPDATE:
Posting some ciphered output might be a good idea.

This post has been edited by atraub: 14 February 2011 - 02:49 PM


Is This A Good Question/Topic? 2
  • +

Replies To: Python Challenge: Can you break my code?

#2 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon

Reputation: 5901
  • View blog
  • Posts: 12,805
  • Joined: 16-October 07

Re: Python Challenge: Can you break my code?

Posted 14 February 2011 - 06:15 PM

Here's my encrypted value: 813707434989510265676533922101041

I actually don't know if this puppy is 100% decrypting. It takes advantage of Python's implicit bigints. Fun fact, many, if not most, encryption algorithms are really just math functions. They don't work on byte data so much as one huge number.

Other fun fact, to be truly cryptographically sound, you should be able to have the code and the value and still not be able to get the answers. That's why big keys are better. Nothing is unbreakable; it's just a function of time. If it takes hundreds of years rather than hundreds of seconds, it's "safe."

def enc(s):
	n=0
	for c in s:
		n = (n<<1)+random.randint(0,1)
		n = (n<<8)+ord(c)
	return -1 * (~(n<<4))


def dec(n):
	n = (~(-1 * n))>>4
	s=''
	while n>0:
		s = chr(n&0xff) + s
		n >>= 9
	return s

def test(s):
	n = enc(s)
	print(s, n, dec(n))



Still, if you didn't have the code, those random bits could really ruin your day. :P
Was This Post Helpful? 1
  • +
  • -

#3 yarvin  Icon User is offline

  • New D.I.C Head

Reputation: 1
  • View blog
  • Posts: 2
  • Joined: 23-April 09

Re: Python Challenge: Can you break my code?

Posted 14 February 2011 - 08:12 PM

This is a simple encryption/decryption class I wrote a few years ago just for fun. I took the idea from Dan Brown's Digital Fortress.
The code basically takes a given string and movies each letter over by 1 in the alphabet.

import sys

class LetterBack:
    '''Class for Encrypting a string of letters'''
   
    def __init__(self):
        self.alphabet = 'abcdefghijklmnopqrstuvwxyz'
       
    def encrypt(self, aSentance):
        '''Encrypts a given string by replacing each letter
        with the letter before it in the alphabet.'''
        aSentance = aSentance.lower()
        output = ''
        for element in aSentance:
            if element == " ":
                output += element
                continue
            for i in range(26):
                if element == self.alphabet[i]:
                    output += self.alphabet[i-1]
        output = output.capitalize()
        print output

    def decrypt(self, aSentance):
        '''Decrypts a given string encoded by the encrypt
         function.'''
        aSentance = aSentance.lower()
        output = ''
        for element in aSentance:
            if element == " ":
                output += element
                continue
            #print element + ' this is 1'
            for i in range(26):
                if element == self.alphabet[i-1]:
                    output += self.alphabet[i]
        output = output.capitalize()
        print output

def main():
    lb = LetterBack()
    if sys.argv[1] == '-e':
        lb.encrypt(sys.argv[2])
    elif sys.argv[1] == '-d':
        lb.decrypt(sys.argv[2])

if __name__ == '__main__':
    main()



$ python letterback.py -e "Yarvin"
Xzquhm
$ python letterback.py -d "Xzquhm"
Yarvin


This post has been edited by yarvin: 14 February 2011 - 08:14 PM

Was This Post Helpful? 1
  • +
  • -

#4 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python Challenge: Can you break my code?

Posted 15 February 2011 - 07:09 AM

Very tricky baavgai.
Was This Post Helpful? 0
  • +
  • -

#5 sean.orear  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 12
  • Joined: 21-December 10

Re: Python Challenge: Can you break my code?

Posted 17 February 2011 - 06:57 AM

Interesting topic ;P

I am working on a solution, but I am going to make one change. Based on the Python docs located at http://docs.python.o...ary/random.html which says:

Quote

Almost all module functions depend on the basic function random(), which generates a random float uniformly in the semi-open range [0.0, 1.0). Python uses the Mersenne Twister as the core generator. It produces 53-bit precision floats and has a period of 2**19937-1. The underlying implementation in C is both fast and threadsafe. The Mersenne Twister is one of the most extensively tested random number generators in existence. However, being completely deterministic, it is not suitable for all purposes, and is completely unsuitable for cryptographic purposes.


I decided to use the os module instead of the random module. It appears to be better for cryptography as per http://docs.python.o...ht=os#module-os, which says:

Quote

os.urandom(n). Return a string of n random bytes suitable for cryptographic use.


I will post my solution when I figure how to do one annoying little thing ;P

Sean
Was This Post Helpful? 0
  • +
  • -

#6 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python Challenge: Can you break my code?

Posted 17 February 2011 - 07:51 AM

Well, this is an academic topic :) But sure, if you'd prefer to use OS for random value generation, that's fine by me. In my encryption algorithm I referenced at the beginning, I used about 10 random number generating algorithms that I created, and then periodically (based on random values) switched which one I was using.

This post has been edited by atraub: 17 February 2011 - 07:54 AM

Was This Post Helpful? 0
  • +
  • -

#7 sean.orear  Icon User is offline

  • New D.I.C Head

Reputation: 6
  • View blog
  • Posts: 12
  • Joined: 21-December 10

Re: Python Challenge: Can you break my code?

Posted 17 February 2011 - 10:16 AM

My approach is to use a known key, known target (data to be encrypted) and a random vector. Generate the vector once and store it with the target. I'll keep working and then let you guys tear it apart ;P
Was This Post Helpful? 0
  • +
  • -

#8 torieLynn  Icon User is offline

  • New D.I.C Head

Reputation: 7
  • View blog
  • Posts: 5
  • Joined: 23-December 10

Re: Python Challenge: Can you break my code?

Posted 17 February 2011 - 07:22 PM

This is what I decided to do:

 
class Cypher:
        
    def __init__(self):
        self.dict = {}
        self.crypt = ""

    def __str__(self):
        return str(self.crypt)
            
        
    def encrypt(self, stuff):
        string = str(stuff)
        cryp = ""
        size = len(string)
        for i in range(size):
            entry = self.cypher(string[i])
            if(entry not in self.dict):
                self.dict[entry] = string[i]
            cryp += entry
        self.crypt = cryp
                
    def decrypt(self, stuff):
        string = str(stuff)
        uncryp = ""
        size = len(string)
        for i in range(size):
            entry = self.dict[stuff[i]]
            uncryp += entry
        self.crypt = uncryp

    def cypher(self, element):
        one = ord(element)
        one = str(one)
        if(len(one) < 1):
            two = ord(one)
        else:
            two = ord(one[0])
        one = int(one)
        three = chr(one+two)
        return three



The output is pretty cool.

c = Cypher()
>>> c.encrypt("Apples")
>>> print(c)
w¡¡–¤
>>> c.decrypt("w¡¡–¤")
>>> print(c)
Apples
>>> c.encrypt(123)
>>> print(c)
egh
>>> c.decrypt("egh")
>>> print(c)
123



I don't know how good of a cipher this is but I had fun :)

This post has been edited by atraub: 17 February 2011 - 07:49 PM

Was This Post Helpful? 1
  • +
  • -

#9 atraub  Icon User is offline

  • Pythoneer
  • member icon

Reputation: 759
  • View blog
  • Posts: 2,010
  • Joined: 23-December 08

Re: Python Challenge: Can you break my code?

Posted 18 February 2011 - 03:03 PM

That's a very cool perspective you have there torieLynn. The code could be refined a little here and there, but it's definitely a unique take on a ciphering algorithm.
Was This Post Helpful? 0
  • +
  • -

#10 Simown  Icon User is offline

  • Blue Sprat
  • member icon

Reputation: 319
  • View blog
  • Posts: 650
  • Joined: 20-May 10

Re: Python Challenge: Can you break my code?

Posted 18 February 2011 - 04:45 PM

Ok, it's not entirely my method but it's kinda cool, implementing it was tough. It could probably do with some better error checking though. I'll update it if I get time :)

class Cipher:
    def __init__(self):
        self.letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
        self.key = 'SECRET'
        self.new_key = ''

    def encrypt(self, value):
        self.encrypted = ''
        self.value = str(value).upper()
        self.new_key = (self.key * (len(value) // len(self.key)) ) + self.key[: len(value) % len(self.key)]
        for i in range(len(value)):
            if self.value[i] in self.letters:
                self.encrypted +=  self.letters[( ((ord(self.new_key[i])) - 65) + ((ord(self.value[i])) - 65) ) % 26]
            elif self.value[i] == " ":
                self.encrypted += " "
        return self.encrypted

    def decrypt(self, value):
        self.decrypted = ''
        self.value = str(value).upper()
        self.new_key = (self.key * (len(value) // len(self.key)) ) + self.key[: len(value) % len(self.key)]
        for i in range(len(self.value)):
            if self.value[i] in self.letters:
                self.decrypted += self.letters[(((ord(self.value[i])) - 65) - ((ord(self.new_key[i])) - 65)) % 26]
            elif self.value[i] == " ":
                self.decrypted += " "
        return self.decrypted


The encryption depends on the key and it can be any length, the key will shrink or grow according to the input length, plus the letters won't map to the same values on each occurrence within the string. I'll just do examples :P

>>> cipher = Cipher()
>>> cipher.encrypt('NICE CHALLENGE ATRAUB')
'FMEV VZENCIGYI RXKSYD'
>>> cipher.new_key
'SECRETSECRETSECRETSEC'
>>> cipher.decrypt('FMEV VZENCIGYI RXKSYD')
'NICE CHALLENGE ATRAUB'
>>> cipher.encrypt('IT')
'AX'
>>> cipher.new_key
'SE'
>>> cipher.decrypt('AX')
'IT'
>>> cipher.decrypt('FMEV VZENCIGYI RXKSYD')
'NICE CHALLENGE ATRAUB'
>>> cipher.new_key
'SECRETSECRETSECRETSEC'

# Changing the key

>>> cipher.key = 'DREAMINCODE'
>>> cipher.encrypt('NICE CHALLENGE ATRAUB')
'QZGE KUCZOIQXI MBECIE'
>>> cipher.decrypt('QZGE KUCZOIQXI MBECIE')
'NICE CHALLENGE ATRAUB'
>>> cipher.new_key
'DREAMINCODEDREAMINCOD'




This post has been edited by Simown: 18 February 2011 - 06:59 PM

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1