RSA algorithm example in Python code
(why this is a good code)

RSA example explained
www.di-mgt.com.au/rsa
même en francais
more links
#RSA algorithm 

import string



def CharCode(l):
    return ord(l) - ord('a')+1



def ModExp(a,e):
    '''calculate a^e mod 3233'''
    
    aa, bb = a % 3233, 1
    for i in range(e):
        bb = aa*bb % 3233
        
    return bb
    
def toCode(phrase):
    '''convert phrase = block of letters
    return a code number < 3233
     '''

    #convert a phrase to a number base 30
    sum = 0
    for x in phrase:
        sum = 30*sum + CharCode(x)

    #do the RSA conversion
    return ModExp(sum,17)

def toLetters(codedNum):
    '''convert codeNum <3233
    return a block of letters
     '''

    #undo the RSA conversion
    num = ModExp(codedNum,2753)

    #convert a number base 30 to a phrase
    ll= []
    while num >0:
        r , num = num % 30, num / 30
        ll.append(string.lowercase[r-1])
    ll.reverse()
    
    return "".join(ll)


def codeText(text):
    '''text = string
    return a list of coded numbers'''

    #pad out to the right length with extra letters
    if len(text) % 2 ==1:
        text += "a"

    #cut into blocks
    blocks = [text[i:i+2] for  i in range(0,len(text),2)]
    
    return [ toCode(ablock ) for ablock in blocks]

    
qq= codeText('helloworld')
print qq
print "".join([toLetters(block) for block in qq])


 

The geometrico/probalistic reason this is a good coding strategy is that the sequence
(n,n^17 mod 3233) is well distributed in the square [0,3233]^2, as you can see below.