(Func yeah, comp sci!)
OC   ACRONYMS   ASK   SUBMIT   RSS   ARCHIVE   SEARCH

================================================================================

Func yeah, comp sci!

================================================================================

 

Sierpinski Triangle

Explanations, dissertations, rants, how-tos, and so on for those interested in computer science. My goal is to make a field seen as excessively complex and "nerdy" more accessible to everyone. AKA Comp Sci For Dummies.

This blog is ideal for high school students and college freshmen who are interested in math, programming, and computer science, but are intimidated by the learning curve. There will be code, don't be scared! I comment my code.

I will also reblog amusing, interesting, or edifying posts from other users within my demographic. 

================================================================================

10/04/2011 11:07:00

tigerearings-deactivated2011100 asked: Why did I never realize the extent of your dorkiness? It's soooo awesome.

The fact that you find my dorkiness awesome is in itself awesome. Could this be an example of the Composite Pattern? (Probably not, but I’m still going to give a shout out to design patterns.)

--------------------------------------------------------------------------------

08/26/2011 03:28:23

On Steve Jobs’ Resigning

Recently, news came that Steve Jobs resigned as CEO of Apple. He will stay on board, however, as Chairman of the Board and will continue to play an active role in Apple’s future. However, without him at the helm, Apple’s stock dropped significantly as investors are afraid of Apple without Jobs.

I however think Apple would do a lot better without the guy. He has had some great ideas, but Apple needs something different. Either a more individual path, as they seem to be heading with a strange blending of OS X and iOS, or back onto a more conventional path, away from the OS X Lion.

Apple has never been more successful and I hope that this change will create good changes for both Apple and the industry at large.

(Just my two cents.)

--------------------------------------------------------------------------------

06/22/2011 00:50:05

Haskell's (lazy, call-by-need) evaluation isn't that hard to understand.

--------------------------------------------------------------------------------

06/20/2011 12:20:04

Sage Math

A student in my Cryptography class recommended this package to me. I looked at it and it seems pretty cool. I encourage anyone with some free time to noodle with it.

Sage Math

Sage is a free open-source mathematics software system licensed under the GPL. It combines the power of many existing open-source packages into a common Python-based interface.

Sage is built out of nearly 100 open-source packages and features a unified interface. Sage can be used to study elementary and advanced, pure and applied mathematics. This includes a huge range of mathematics, including basic algebra, calculus, elementary to very advanced number theory, cryptography, numerical computation, commutative algebra, group theory, combinatorics, graph theory, exact linear algebra and much more. It combines various software packages and seamlessly integrates their functionality into a common experience.

There is an overview of Sage Math here in this tour page.

--------------------------------------------------------------------------------

06/16/2011 01:21:00

Crypto homework!

Hey guys, I thought I’d share some work I did for my Crypto homework. The assignment can be viewed here if you are interested, but I’ll go ahead and explain.

Problem 1

Determine the number of keys in an affine cipher over Z_m for m = 29, 99, and 1024. Briefly explain your answers.

Z_m is the set of characters that can be used for members of a cipher key. “m” is the size of the set. The letters of the English alphabet would be Z_26:

{A, B, C, D, E, F, G, H, I, J, K, L, M, N, O, P, Q, R, S, T, U, V, W, X, Y, Z}

An affine cipher has a key like so: (a, b) where both “a” and “b” are characters from Z_m, and “a” must be coprime to “m.” I could explain coprime in a bunch of crazy math, but how about I just show you an algorithm to find all the numbers between 1 and “m” that are coprime to m?

# given m is defined
for a in range(1, m):               # let's find all the possible values for a
    for x in range(1, m):           # the algorithm is that we check all other values up to m
        if (a*x)%m == 1:            # if a and x multiplied together, modulus m, is 1
            print(a)                # then a is coprime to m

The modulus function can be thought of as a remainder function. 7 modulus 4 is 3, because 7/4 is 1, with remainder 3.

So then the way to find the number of keys is to find the number of possible “a” values, times the number of possible “b” values (and that number is the same as “m”).

In Z_26 (English) this number is 312.

Problem 2

Perform cryptanalysis of the following two ciphertexts. The first ciphertext was obtained using an affine cipher, and the second ciphertext was obtained using a substitution cipher. Your goal is to find the plaintexts. Both are in English.

Here are the ciphertexts:

Affine Cipher:

XGKTRDCSSVWRKTGHGVWSCRGHRDGTGYKCXSWFWXGODWVWSSGSSGHJGKQRMOCR
DWQRPKXCRMSRTGXERDOCRDWQRCXSWZGXIGIWQTKEGOCRDWQRFGTWSCRMKXHK
ZZRDGPCTRQGSWFYKXOCRDWQRDCSPCIGSRDCSVTKCSGODCIDOWQZHJGQXYGKX
CXEFZKRRGTMCFCXSITCJGHWPGTDQYKXKSDGSCSJQRKBQSRRTCJQRGRWRDGYG
YWTMWFJWKRSOKCXKHWE

Substitution Cipher:

ELNQYGEVQKYREMBEELVBHVJNMRBNDYBERMJZMQMDYRNWMGELMEWLNBMKNRGY
BDVNGLNYBJFMKKNMRGEYDVNLNVGGEVJJINRFQTCLMJVINVBELNKMGEGYVEVG
INRFGVJJFZYRKNYKJNEYCRFMELVGZTBNRMJMJJQYQNBEGKMGEKRNGNBEMBDZ
TETRNMJWMFGLMINNPVGENDMJWMFGWVJJNPVGEELNERMJZMQMDYRVMBGCMBJY
YXMEMJJELNDVZZNRNBEQYQNBEGSTGEELMEWMFWNCMBJYYXMEMGERNECLYZEL
NRYCXFQYTBEMVBGZYRVBGEMBCNELNFCMBGNNLYWKNRQMBNBEMJJELNQYQNBE
GVYBWNLMINLNRNYBNMRELELMEYBNQYQNBEZYJJYWGMBYELNRYBNJVXNANMDG
YBMGERVBHMBDELMEYBCNMQYQNBEVGHYBNVEVGHYBNZYRNINRWLNBMERMJZMQ
MDYRVMBGNNGMCYRKGNMJJLNELVBXGVGELMEELNDNMDKNRGYBVGVBAMDCYBDV
EVYBVBELNKMREVCTJMRQYQNBEATEELMEELNGMQNKNRGYBVGSTGEZVBNVBKJN
BEFYZYELNRQYQNBEGBYWWLNBVQFGNJZLNMRELMEGYQNAYDFVGDNMDVGVQKJF
GLRTHMBDGMFWLMEELNERMJZMQMDYRVMBGGMFMAYTEDNMDKNYKJNWLVCLVGGY
VEHYNG

The idea was to decrypt the messages. Shannon’s maxim, which says that anyone trying to decrypt a secret message is assumed to know the cryptographic method used, was assumed. Otherwise, I had no other knowledge about the messages!

The following is the (very large) program I used to toy around with the ciphers. You are free to use it!

# The following code is subject to the GNU GPL version 3, which can be found here: http://www.gnu.org/licenses/gpl-3.0.txt
# With the exception of the ciphertexts and their respective plaintexts, and included libraries, which are property of their respective owners.
# Code written by Andrew Garrett

import string
import itertools
import copy

# Setup global vars
SUBCI = "ELNQYGEVQKYREMBEELVBHVJNMRBNDYBERMJZMQMDYRNWMGELMEWLNBMKNRGY + \
BDVNGLNYBJFMKKNMRGEYDVNLNVGGEVJJINRFQTCLMJVINVBELNKMGEGYVEVG + \
INRFGVJJFZYRKNYKJNEYCRFMELVGZTBNRMJMJJQYQNBEGKMGEKRNGNBEMBDZ + \
TETRNMJWMFGLMINNPVGENDMJWMFGWVJJNPVGEELNERMJZMQMDYRVMBGCMBJY + \
YXMEMJJELNDVZZNRNBEQYQNBEGSTGEELMEWMFWNCMBJYYXMEMGERNECLYZEL + \
NRYCXFQYTBEMVBGZYRVBGEMBCNELNFCMBGNNLYWKNRQMBNBEMJJELNQYQNBE + \
GMRNMBDELNFCMBJYYXMEMBFQYQNBEELMEVBENRNGEGELNQVEVGSTGEMBVJJT + \
GVYBWNLMINLNRNYBNMRELELMEYBNQYQNBEZYJJYWGMBYELNRYBNJVXNANMDG + \
YBMGERVBHMBDELMEYBCNMQYQNBEVGHYBNVEVGHYBNZYRNINRWLNBMERMJZMQ + \
MDYRVMBGNNGMCYRKGNMJJLNELVBXGVGELMEELNDNMDKNRGYBVGVBAMDCYBDV + \
EVYBVBELNKMREVCTJMRQYQNBEATEELMEELNGMQNKNRGYBVGSTGEZVBNVBKJN + \
BEFYZYELNRQYQNBEGBYWWLNBVQFGNJZLNMRELMEGYQNAYDFVGDNMDVGVQKJF + \
GLRTHMBDGMFWLMEELNERMJZMQMDYRVMBGGMFMAYTEDNMDKNYKJNWLVCLVGGY + \
VEHYNG"
AFFCI = "XGKTRDCSSVWRKTGHGVWSCRGHRDGTGYKCXSWFWXGODWVWSSGSSGHJGKQRMOCR + \
DWQRPKXCRMSRTGXERDOCRDWQRCXSWZGXIGIWQTKEGOCRDWQRFGTWSCRMKXHK + \
ZZRDGPCTRQGSWFYKXOCRDWQRDCSPCIGSRDCSVTKCSGODCIDOWQZHJGQXYGKX + \
CXEFZKRRGTMCFCXSITCJGHWPGTDQYKXKSDGSCSJQRKBQSRRTCJQRGRWRDGYG + \
YWTMWFJWKRSOKCXKHWE"
SUBKEY = {}
for char in string.ascii_uppercase:
    SUBKEY[char] = '*'
AFFKEY = [1,0]
# Global vars set up

def charFreqInText(key,ctext):
    '''prints the frequency of each character in a ciphertext'''
    freqtable = {}
    for char in string.ascii_lowercase:
        freqtable[char] = 0
    for char in ctext:
        freqtable[char] += 1
    for c in key.keys():
        print( str(c), ":", str(key[c]), ":" , str(freqtable[key[c]]))

def decryptSubCipher(key,ctext):
    '''key: in dict form'''
    newtext = ""
    for char in ctext:
        newtext += key[char]
    return newtext

def decryptAffCipher(key,ctext):
    '''key: in form (a,b)'''
    newtext = ""
    for char in ctext:
        newtext += chr( ( ( ( ord(char) -97 - key[1] ) * computeInverse(key[0]) ) % 26 ) +97 )
    return newtext

def computeInverse(a,m=26):
    '''finds inverse of a in mod m via bruteforce'''
    for x in range(2,m):
    if (a*x)%m == 1:
        return x
    return 1

def manipulateSubKey(cipherchar, plainchar):
    oldplainchar = SUBKEY[cipherchar]
    oldcipherchar = ''
    for cc in SUBKEY:
    if SUBKEY[cc] == plainchar:
        oldcipherchar = cc
    SUBKEY[cipherchar] = plainchar
    if oldcipherchar != '':
        SUBKEY[oldcipherchar] = oldplainchar

def main():
    selection = -1
    print("Welcome to the Homework 1 cryptanalysis tool.")
    while selection != 0:
        print("Choose an option:")
        print("0. Exit")
        print("1. PRINT the current value of the Substitution ciphertext.")
        print("2. PRINT the current guess of the Substitution cipher key.")
        print("3. MODIFY the Substituion cipher key.")
        print("4. ATTEMPT a bruteforce of the Substitution cipher.")
        print("5. PRINT the current value of the Affine ciphertext.")
        print("6. PRINT the current guess of the Affine cipher key.")
        print("7. MODIFY the Affine cipher key.")
        print("8. ATTEMPT a bruteforce of the Affine cipher.")
        print("9. PRINT the character frequency of both ciphers.")
        print("10. FIND the number of possible Affine keys in Z_m.")
        print("11. LOAD a new Substituition ciphertext.")
        print("12. LOAD a new Affine ciphertext.\n")
        selection = input(">> ")
        print()
        try:
            selection = int(selection)
        except ValueError:
            selection = -1
        if selection == 0:
            return
        elif selection == 1:
            print(decryptSubCipher(SUBKEY,SUBCI),"\n")
        elif selection == 5:
            print(decryptAffCipher(AFFKEY,AFFCI),"\n")
        elif selection == 2:
            print(SUBKEY,"\n")
        elif selection == 6:
            print(AFFKEY,"\n")
        elif selection == 3:
            cipherchar = input("Cipher character: ").upper()
            plainchar = input("Plain character: ").lower()
            manipulateSubKey(cipherchar, plainchar)
            print()
        elif selection == 7:
            a = int(input("a: "))
            b = int(input("b: "))
            AFFKEY[0] = a
            AFFKEY[1] = b
            print()
        elif selection == 4:
            tempKey = SUBKEY.copy()
            unknownKeys = []
            unknownVals = list(string.ascii_lowercase)
            for k in SUBKEY:
                if SUBKEY[k] == '*':
                    unknownKeys += k
            else:
                unknownVals.remove(SUBKEY[k])
            unknownKeys.sort()
            unknownVals.sort()
            allKeyPerms = itertools.permutations(unknownKeys)
            for k in allKeyPerms:
                for x in range(0,len(unknownVals)):
                    tempKey[k[x]] = unknownVals[x]
                decryption = decryptSubCipher(tempKey,SUBCI)
                print("key: " + str(tempKey) + "\n" + decryption + '\n')
        elif selection == 8:
            for a in range(1,26):
                if computeInverse(a) != 1 or a == 1:
                    for b in range(0,26):
                        decryption = decryptAffCipher((a,b),AFFCI)
                        print("key: (" + str(a) +"," + str(b) + ")\n" + decryption + '\n')
        elif selection == 9:
            print("Substituion cipher:\n")
            charFreqInText(SUBKEY,decryptSubCipher(SUBKEY,SUBCI))
            print()
            print("Affine cipher:\n")
            charFreqInText(AFFKEY,decryptAffCipher(AFFKEY,AFFCI))
            print()
        elif selection == 10:
            m = int(input("m: "))
            c = 0
            for a in range(1,m):
                if computeInverse(a,m) != 1 or a == 1:
                    for b in range(0,m):
                        c += 1
            print("The total number of possible keys is:",c,"\n")
        elif selection == 11 or selection == 12:
            fname = input("File name with extension, or type * to type the ciphertext: ")
            buff = ""
            if fname != "*":
                fin = open(fname)
                for line in fin:
                    buff += line.strip().upper()
                if selection == 11:
                    SUBCI = copy.copy(buff)
                elif selection == 12:
                    AFFCI = copy.copy(buff)
            else:
                if selection == 11:
                    SUBCI = input("Type the Substitution ciphertext here. Whitespace will be stripped. > ").strip().upper()
                elif selection == 12:
                    AFFCI = input("Type the Affine ciphertext here. Whitespace will be stripped. > ").strip().upper()
            print()
        else:
            print("That was an invalid selection; I am sorry.","\n")

main()

I would love to break it down for you all but it’s long and messy (quite hacked-together, as most of my Python programs are) so let me just explain it at a high level.

I let you build a key for either cipher and then use the key to decrypt the cipher. If the decryption is right it will look like English. Otherwise it will be gibberish.

You can also at any time attempt a brute-force attack on either cipher. I used to have code that would only print attempts that contained the word “the” in the decryption, but I felt like I didn’t want to include that condition in this code. If you’re feeling adventurous, why not try to find where you should place the following conditional?

if "the" in decryption:

(I love Python. In C that conditional statement is like 10 lines of code, seriously.)

However, the number of possible keys for the substitution cipher is 26!, so it will take any regular computer weeks to brute-force the key from scratch. You have to perform frequency analysis on the text to try to identify common letters, letter pairs, and three-letter words. Needless to say it is really hard to do, and I was up all night solving it. Once you identify several of the letters in the key, you can attempt a brute-force which can be solved in a few hours.

--------------------------------------------------------------------------------

06/13/2011 16:21:00

mineshaft82 asked: Hey you recommended Eclipse as an IDE......I have been reading into it...and it looks like its focus is for Java....but can be used is c/c++ i also noticed a javascript version for web developers.....Can Eclipse be used with any language such as Ruby or Python??

Yes, as I mentioned before. I used PyDev for Python. I don’t yet use it for Ruby. Since you mentioned C/C++ you probably already know about the plugins for that! Just make sure that your C/C++ plugin provides a compiler, or a set of instructions for obtaining a compiler. Compiling C/C++ on Windows is absolute hell.

--------------------------------------------------------------------------------

06/12/2011 23:58:00

Acronym of the Day: IDE

Integrated Development Environment.

An integrated development environment is a software application that provides comprehensive facilities to computer programmers for software development. An IDE normally consists of: a source code editor, a compiler and/or an interpreter, build automation tools, a debugger. Sometimes a version control system and various tools are integrated to simplify the construction of a GUI. (Source: Wikipedia)

Programmers almost exclusively write all their code in either a text editor (like Notepad, Vi, or Emacs) or an IDE. IDEs are usually favored because they allow for a lot of nice features that make programming easier, faster, and more effective (usually).

The most common IDEs I know of are Microsoft’s Visual Studio, which can be used for C, C++, C#, VB.Net, and F# (as well as some other programming languages), Apple’s XCode, which can be used for C, C++, Objective-C, and many other languages, and the open source Eclipse (formerly a project of IBM) which is primarily used for Java but can be extended to be used with almost any language, including C, C++, Python, Ruby, Perl, and more.

The nice thing about an IDE is that it gives you organizational tools for your code, quick references to manual pages for the language if they exist, and automatic compiling and syntax error checking. Normally, you would have to write code, save the file, then use the command line to try to compile it. If it failed, you’d have to find your error and fix it. The IDE just points it out - like a spell-checker.

IDEs also contain debuggers, which are really neat tools that help you run through your code to find things that are going wrong, even though they’re valid code. (These are called semantic errors.)

IDEs can add lots of other nice tools such as automatic code generation, code modeling, teamwork functionality, versioning (ever seen software versions?), and often, extensions.

--------------------------------------------------------------------------------

06/12/2011 15:43:55

mahmoudhossam replied to your post: This is how your code appears on my dashboard. http://imageshack.us/photo/my-images/854/capturecqw.png/ Sorry to bother you again, I just had to clarify what I meant.
Chromium 12 on Arch Linux.

The browser (and perhaps even platform) is all that makes the difference! I’m using Firefox 4 on Windows 7. Who knows why it’s different? At any rate, I’m sorry that the text wraps around for you. That is probably the worst thing to see when reading my Python or Java code. ;)

--------------------------------------------------------------------------------

06/12/2011 12:52:00

mahmoudhossam-deactivated201107 asked: This is how your code appears on my dashboard.

http://imageshack.us/photo/my-images/854/capturecqw.png/

Sorry to bother you again, I just had to clarify what I meant.

Well, it is strange that it wraps on your dash instead of being put in a scrollbox. What browser are you using?

--------------------------------------------------------------------------------

06/10/2011 22:33:00

Acronym of the Day: PEBKAC

Problem Exists Between Keyboard And Chair.

A user error is an error made by the human user of a complex system, usually a computer system, in interacting with it. (Source: Wikipedia)

PEBKAC is a funny acronym computer programmers use to refer to a user error, which is when the user of a program or computer experiences a result other than what they wanted, but due to their own fault in using the machine.

For instance, if a user is trying to search something in their browser, but he/she opens his/her start menu (or open finder, or nautilus, or whatever you use) and search for the same thing, he/she will not get the results they wanted. He/she may blame the error on a bug, but in fact, the error is a user error.

If you pursue a career in IT or programming, you will have many frustrations with incompetent or confused users who will blame user error on you. This is a cross we techies have to bear willingly. :)

Tech Support: “Ok, ma’am, I need you to do a ctrl-alt-del.”
Customer: “How do I do that?”
Tech Support: “Push and hold ‘ctrl’ and ‘alt’ at the same time, and then hit ‘delete’.”
Customer: “Where are those?”
Tech Support: (explains the location of the keys)
Customer: “Nothing happened.”
Tech Support: “Try again.”
Customer: “Still nothing.”

A minute or two later….

Customer: “Should I turn my computer on? Would that help?”
Tech Support: “Yeah, it might.”

--------------------------------------------------------------------------------

pg 1 of 8

================================================================================

Designed: Robert Boylan
Powered: Tumblr