domingo, 9 de septiembre de 2012

Tarea 5: Lógica Predicativa

Para esta semana, debiamos escoger algun par de proposiciones concretas, propuestas como premisas del libro "Symbolic Logic" por Lewis Carroll.  Entonces esas proposiciones debiamos pasarlas a lógica predicativa(para saber, lo que explicaré a continuación.

Mi par de proposiciones fue el siguiente:
  1. No riddles interest me if they can be solved. (Ningún acertijo me interesa si puede ser resuelto)
  2. All these riddles are insoluble. (Todos estos acertijos son irresolubles)
(Nota: Quiero suponer que por insoluble se refiere a irresoluble, es decir que no se pueden resolver)

Primero, la primer proposición debemos de pasarla a la forma: "No x are y"(Ningún x es y). En este caso, sabiendo que el Universo son los "Riddles" (Acertijos) y que el atributo es "If they can be solved"(Si pueden ser resueltos), podemos expresarlo entonces de la siguiente forma:
  1. No riddles that can be solved are riddles that interest me. (Ningún acertijo que puede ser resuelto es un acertijo que me interesa).
Ahora debemos hacer lo mismo para la segunda proposición para tener la forma: "Some x are y"(Algunos x son y"). Entonces debemos cambiar la primera parte: "All these riddles"(Todos estos acertijos) a "Some riddles"(Algunos acertijos) debido a que solo podemos expresar cuantitativamente mediante \exists \!\,(existen) o \forall \!\,(para todo).

Para la segunda parte podríamos dejar: "are insoluble"(son irresolubles) , aunque es más cómodo cambiarlo para hacerlo semejante a la primera proposición, reemplazándolo por "riddles that cannot be solved"(acertijos que no pueden ser resueltos) .

      2.  Some riddles are riddles that cannot be solved. (Algunos acertijos son acertijos que no pueden ser resueltos)

Lógica Predicativa

Entonces a partir de estas nuevas expresiones, podemos reemplazar términos por otros de lógica predicativa, tomando en cuenta lo siguiente:

SimboloSignificado
\exists \!\, Existen
\forall \!\, Para todo
xRiddles
I(x)Riddles that interest me
S(x)Riddles that can be solved

Sustituyendo entonces por partes quedaría:

1.     No riddles that can be solved are riddles that interest me. (Ningún acertijo que puede ser resuelto es un acertijo que me interesa)

\forall \!\,x  ( ¬ S(x)   →  I(x) )

2.    Some riddles are riddles that cannot be solved. (Algunos acertijos son acertijos que no pueden ser resueltos)

  \exists \!\, x   (¬S(x))

Como conclusión, podríamos agregar una tercera proposición, basándonos en las primeras dos, que podría ser algo así:

3.    Some riddles are riddles that interest me. (Algunos acertijos me interesan)

  \exists \!\, x I(x)


miércoles, 5 de septiembre de 2012

3rd Assignment: Diffie-Hellsman Key Exchange

For the second assignment, we were tasked to do groups of 3 or more, in order to practice the Diffie-Hellsman Key Exchange, with one of the members being Alice, one being Bob, and one Eve, and then changing roles so everyone gets to be Eve one time.

With that said, when my turn to be Eve came, Victor was Alice, and Rene was Bob. They talked in secret generating the values of p and g. Then they made said values, and their respectives X and Y public:
  • p = 17
  • g = 14
  • X = 15
  • Y = 11
With this then I had to start to "hack" to obtain the values of x and y, and therefore the key. So I started first with obtaining x from the X function:
To get x, I just brute-forced my way with every number lower than p. In other cases this may not be really hard(here it is also not hard), but because I was doing it with pencil, without the use of a computer-calculator, this was pretty annoying. 

So what I did, was the following:


As it can be seen, I just multiplied the current power of 14 by 14 again, and then divided by 17, to check the residue(module). If it wasn't equal to 15, the value of X, then I had to multiply again until it did. To see this in a more clean fashioned way, here's a table:

xg^xg^x % p = X
11414 % 17 = 14
214*14 = 196196 % 17 = 9
314*14*14 = 27442744 % 17 = 7
414*14*14*14 = 3841638416 % 17 = 13
514*14*14*14*14 = 537824537824 % 17 = 12
614*14*14*14*14*14 = 75295367529536 % 17 = 15

Now, we can try the same with y. There was a probability that y was already in the previous table, but I didn't get any luck with that, so I continued from where I left. Unfortunately this wasn't any short, as it can be seen:


Another table for better understanding:

yg^yg^y % p = Y
11414 % 17 = 14
2196196 % 17 = 9
327442744 % 17 = 7
4 3841638416 % 17 = 13
5537824537824 % 17 = 12
65295367529536 % 17 = 15
7 105413504105413504 % 17 = 6
814757890561475789056 % 17 = 16 
9 2066104678420661046784 % 17 = 3
10289254654976289254654976 % 17 = 8
1140495651696644049565169664 % 17 = 10
12 5669391237529656693912375296 % 17 = 4
13793714773254144793714773254144 % 17 = 5 
14 1111200682555801611112006825558016 % 17 = 2 
15155568095557812224155568095557812224 % 17 = 11

And that was getting y. With both x and y, now I just had to generate two K's separatedly, one using Y-x, and another one using X-y, with the formulas:
Then: 

K = X^y % p = (15^6) % 17 =  (15*15*15*15*15*15) % 17 = 8
K = Y^x % p = (11^15) % 17 = (11*11*11*11*11*11*11*11*11*11*11*11*11*11*11) % 17 = 8

So I concluded that the Key was 8, wth x = 6, and y = 15. Victor and Rene confirmed this.

sábado, 1 de septiembre de 2012

Tarea 4: Diagramas Binarios de Decisión

Para la Tarea 4 se pidió lo siguiente:
  • Inventen una expresión Booleana.
    • Usando por mínimo 3 variables y 4 conectivos básicos.
  • Construyan y dibujen su BDD.
  • Reduzcan el BDD resultante a un ROBDD.
  • Dibujen el ROBDD resultante.
La expresión booleana que usaré es una sencilla:

(X1 ^  ¬X2)  v   (X3 ^ ¬X1)   ^  (X2 v X3)

Para crear el árbol binario de decisión, primeramente hice la tabla de verdad de dicha expresión, que es la siguiente:


A partir de la tabla de verdad, hice el árbol binario de la siguiente manera:
Éste es un árbol binario de decisión(Binary Decisión Tree) y para reducir éste a un diagrama binario de decisión(Binary Decisión Diagram, BDD), debemos seguir dos reglas:
  • Combinar todos los subgrafos isomórficos(que tengan la misma estructura).
  • Eliminar cualquier nodo cuyos hijos sean isomórficos.

Entonces tomando en cuenta estas reglas, reduje el árbol binario de decisión a un diagrama binario de decisión, que quedo así:

Observando a fondo, la única reducción visible es en el caso de que X1 y X2 sea igual a 1,para cualquier valor de X3 daría 0, por lo tanto se reduce. Lo demás no fue posible reducirlo.

ROBDD

Para reducir el BDD a un ROBDD(Reduce Ordered Binary Decision Diagram), el PDF: "An Introduction to
Binary Decision Diagrams" por Henrik Reif Andersen, menciona tres condiciones para el orden y reducción:
  1. Las variables deben estar ordenadas
  2. Los nodos deben ser únicos
  3. Solo tests no redundantes deben estar presentes


                              (1)                                                                  (2)                                          (3)
Además menciona que el orden de las variables escogidas en la construcción de un ROBDD tiene un gran impacto en el tamaño de el ROBDD, por lo tanto, probaré un orden diferente al del BDD para observar si se reduce el tamaño.

ROBDD para el Orden X1, X3, X2

Utilizando el orden X1<X3<X2, el tamaño del árbol fue reducido de 6 nodos a simplemente 4.

Referencias:

Tarea 2: Transformada de Laplace

Para la Tarea 2, debíamos de escoger un ejercicio para resolver, de el libro: "Ingeniería de
Control Moderna" de Katsuhijo Ogata. Mi ejercicio fue el siguiente:


Entonces, como dice el ejercicio, debía obtener la transformada de Laplace de la función que corresponde a dicha gráfica. No podemos sacar la transformada directamente de una gráfica de ésta manera. Para poder empezar necesitamos obtener la función o funciones que satisfacen ésta gráfica. En este caso son dos, como se puede observar claramente, la función está definida en los intervalos de 0 a T, y de T a infinito, y en ambas es diferente, por lo tanto podemos separar f(t) en dos funciones g(t) y h(t) y obtener la forma algebraica de cada una, entonces quedaría algo así:


Para h(t) no es necesario encontrar la función de alguna forma en específico, basta con ver la gráfica para saber que h(t) siempre será igual a T, desde T hasta infinito. Pero g(t) es diferente(aunque sería fácil deducir también de manera gráfica que g(t) = t, explicaré como obtenerla). Para obtener g(t), utilizamos dos puntos de la gráfica(1) para luego sustituirlos en la ecuación(2):

(1)                                                                                 (2)

Podemos utilizar cualquier par de puntos como (x1, y1), (x2, y2), respectivamente, y obtener la misma función, pero por simplicidad escogí:
Entonces lo restante es sustituir los valores de los puntos en la ecuación, y despejar y. Lo cual se hace así:

Ya que tenemos g(t) y h(t), podemos proceder a encontrar la transformada de Laplace. Para esto utilizamos la fórmula que dice: 

Pero nosotros no tenemos una función directa f(t), tenemos las dos funciones que forman f(t): g(t) y h(t), por lo tanto, partimos los intervalos de ésta fórmula en dos (de 0 a T, y de T a infinito, como g(t) y h(t)). Después sustituimos g(t) y h(t). La fórmula entonces quedaría así:



Entonces para encontrar la Transformada de Laplace de f(t) debemos integrar ambas partes. Para comprender más fácilmente ésto, lo haré por partes, integrando primero (1) y luego (2), al final entonces simplemente las sumaríamos. También ignoraré los intervalos por ahora, más adelante los evaluamos.

Para integrar (1) tenemos que realizarlo por partes; si no sabemos como, se utiliza la fórmula: 
Entonces sustituyendo los valores, e integrando quedaría algo así:
(Nota: no voy a explicar paso a paso las integrales porque es algo tedioso, solo me dedicaré a explicar superficialmente)

Eso es para el primer intervalo, para el segundo, que sería la ecuación (2), la integral es bastante sencilla:

(T es constante, por lo tanto podemos sacarla de la integral)

Ya teniendo ambas integrales, debemos ahora sí evaluarlas en los intervalos correspondientes. 

Con evaluarlas me refiero a sustituir los valores de los extremos de los intervalos superior e inferior, y restarlos respectivamente. Entonces, volvemos a separar ambas en (1) y (2) para entenderlo más fácilmente. Para evaluar (1) y (2) entonces tenemos que:



Ahora estos valores serán los que sumaremos para obtener finalmente la transformada de Laplace, de la siguiente manera:


Pero aún así podemos simplificarla un poco más, agrupando los términos que tienen s^2 de denominador. Quedando definitivamente de la siguiente forma:

Resultado:

Y este fue el ejercicio de la Tarea 2, tengo que decir que no fue sencillo, debido a que no recordaba bien como realizar este tipo de ejercicios(el problema estaba sencillo). 

Referencia:

jueves, 30 de agosto de 2012

2nd Assignment - One Time Pad Analysis

For the second assignment, I was tasked to do some sort of analysis for my one-time-pad program that I did for the previous assignment, and with that hack it. I don't think I can actually hack the program, because even if the random numbers that python's randint function uses aren't totally random(of course they aren't) I can't seem to think of a way to predict them or figure a pattern.

So I will focus on the analysis of the python random generator, doing some tests.

Character Frequency Test

First, I did a simple frequency test, to see which letters were generated the most for the key. I have to say that my keys were generated using randint in a reduced range for all the letters of the alphabet(in lowercase) and also the space character. So it would be something like randint(0, 28).

With that said, I just wanted to get a frequency of the letters, which would also be the frequency of the numbers, to see how many times some characters were repeated. Of course this doesn't tell much, because as we can see on the graphic, the frequency of each number, even though it is different, it is not a huge difference so we can't tell if there's a pattern at all.


Frequency Monobit Test

To test the proportion of ones and zeros in order to find if there are many zeros or many ones, the monobit test is useful. The puropose is to find if the number of zeros and ones is approximately the same, as expected in a random sequence. I already had done this in a previous class, so I just had to adapt a little the code to my current one-time-pad key generator, but a better explanation to the monobit test can be found here(in spanish).

def frequency_test(lista):
  suma = 0
  lista = list(lista)
  n = len(lista)
  for i in range(len(lista)):
    if lista[i] == "0":
      suma += -1
    else:
      suma += 1
  suma_abs = abs(suma)/math.sqrt(n)
  p_value = math.erfc(suma_abs/math.sqrt(2))
  if p_value < 0.01:
    print "Frequency Test: Not passed\n"
  else:
    print "Frequency Test: Passed\n"

The test produced the next results:



The p value, which is used to determine if the test is passed or not, was bellow 0.01, which means the test didn't passed, so our random generator  doesn't generate a good enough proportion of random zeros and ones. I think generating the bits of the key one by one, using an uniform distribution would help in improving this, because the number of ones and zeros would be more proportioal.

Searching for a Graphical Pattern in a Bitmap

An easy way to tell if a random generator is just plain dumb, is to look at the patterns it can generate in a graphical way. For example, this image taken from RANDOM.ORG is a bitmap of the PHP rand function on Windows:

PHP rand in Windows

As we can see, there is a clear graphical pattern, so we can tell that is not really random. Now i tried to do the same with the python random generator, using Tkinter to draw small dots using the line widget. I move between every coordinate in an area, and I draw a dot if a random generated number is 1, or I don't if it is 0. The simple python script I used:

#!/usr/bin/python
from Tkinter import *
from random import randint

master = Tk()

w = Canvas(master, width=700, height=700, background="white")
w.pack()
for i in range(700):
  for j in range(700):
    if randint(0, 1) == 1:
      w.create_line(i, j, i+1, j+1)

mainloop()

 The result was this:

Python's random in Linux

I personally can't see a visual pattern here, so I assume this is a pretty good random generator, so I call this test passed.

Chi2 test

Using the chisquare function of the scipy library, it is possible to do the chisquare test to an array of frequencies. For this, I used the frequencies of the first test, and the simple code is the following:

#!/usr/bin/python
from random import randint
import numpy
import scipy.stats
alphabet = "abcdefghijklmnopqrstuvwxyz "
 
def generate_key(size):
  key = ""
  for i in range(size):
     key += alphabet[randint(0, len(alphabet)-1)]
  return key

def zeros(size):
  array = []
  for i in range(size):
    array.append(0)
  return array

def frequency_test(key):
  freq = zeros(len(key))  
  for i in range(len(key)):
    for j in range(len(key)):
      if key[i] == key[j]:
        freq[i]+=1
  return freq

def expected(size):
  box_size = size/len(alphabet)
  freq_exp = zeros(size)
  for i in range(size):
    freq_exp[i] = box_size
  return freq_exp

freq_obs = frequency_test(generate_key(100))
freq_exp = expected(len(freq_obs))
array_obs = numpy.array(freq_obs)
array_exp = numpy.array(freq_exp)
print "Observable Frequencies(Random Numbers frequencies): %s\n"%array_obs
print "Expected Frequencies: %s"%array_exp

chi_stat, p_value = scipy.stats.chisquare(array_obs, array_exp)
print "Chi2 Statistic: %s"%chi_stat
print "P Value Statistic: %s"%p_value

The function scipy.stats.chisquare(f_obs, f_exp=None, ddof=0) generates two values, the chisquare test statistic, and the p-value, used to check if the test was passed or not.

The parameters are:
  • f_obs : array
    • observed frequencies in each category
  • f_exp : array, optional
    • expected frequencies in each category. By default the categories are assumed to be equally likely.
  • ddof : int, optional
    • adjustment to the degrees of freedom for the p-value

To get the observed frequencies, like I said I use the first frequency test to get which letters, or random numbers are repeated and how much time, and I fill a list of the respective frequencies. For the expected frequencies, I generated a list of frequencies, but these frequencies are as we would expect to be, so I divided the size of the random samples (the size of the alphabet used to generate keys) between the size of the key, so I could fill boxes with the same frequencies, as expected from a uniform random generator. 

Then giving these two parameters to the function, I got a p_value, and a chisquare statistic. The p value just like the monobit test, help us to determine if the test was passed or not. In this case the test never passed:


Things to get my One-Time-Pad better

First of all, I fixed some minor things that my one time pad:
  1. My one-time-pad generated one key per word of the message, which at the end wouldn't be much different from the regular results, but it wasn't the best approach.
  2. My one-time-pad used to skip spaces, not encrypting them. So, now I added the spaces to the alphabet array, so it can be encrypted along with the message.
  3. My one-time-pad wasn't modular. It used to be sequential, doing a lot of things in the same function, so I separated every important part into its own function, like encrypting, deciphering, generating the key, etc.
Now an important thing that I think would make it better is a file, were all the used keys are stored, this is important, because even though python didn't reuse a single key running the program 10000 times, it is still likely that it will, sometime. So using this file, the program can make sure the generated key is totally new. Of course there is the problem with the reading/wrinting to files, but security comes first.

The code, updated:

from sys import argv, stdout
from random import randint
import math

alphabet = "abcdefghijklmnopqrstuvwxyz "
 
def letter_pos(letter):
  for i in range(len(alphabet)):
    if alphabet[i] == letter:
      return i
 
def wiki_cipher(msg, key):
  cipher_msg = ""
  for i in range(len(msg)):
    cipher_msg += alphabet[(letter_pos(msg[i]) + letter_pos(key[i])) % len(alphabet)]
  del key
  print "Cipher: %s"%cipher_msg
  return cipher_msg
 
 
def wiki_decipher(cipher_msg, key):
  msg = ""
  for i in range(len(cipher_msg)):
    msg += alphabet[(letter_pos(cipher_msg[i]) - letter_pos(key[i])) % len(alphabet)]
  del key
  print "Decipher %s"%msg
  return msg

def generate_key(size):
  key = ""
  for i in range(size):
     key += alphabet[randint(0, len(alphabet))]
  key = key[0:size]
  return key

def main():
 try:
   filename = argv[1]
   f = open(filename, "r")
   msg = f.readlines()[0]
   msg.replace("\n", "")
   print "Message:"
   print msg
 except IndexError as err:
   print "File not specified, using default message."
          msg = "testing the one time pad encryption"
 print "Message: %s"%msg.lower()
 key = generate_key(len(msg))
 cipher = wiki_cipher(msg, key)
 wiki_decipher(cipher, key)
main()

References:

martes, 28 de agosto de 2012

Tarea 3: Lógica Proposicional - Aplicaciones

Para la tercera tarea de Verificación y Validación de Software, tenemos que investigar las aplicaciones de la lógica proposicional.

Para esto encontré algunas aplicaciones como: Inteligencia Artificial, Circuitos Lógicos, y Acertijos Lógicos, pero solo explicaré estos dos últimos.

Aplicación - Acertijos Lógicos:

Una aplicación de la lógica proposicional que me pareció interesante, fue la de la creación de acertijos en base a proposiciones lógicas. El uso de la lógica para crear desafios mentales complicados, si bien no es una aplicación profeional, es un enfoque diferente a lo usual que estoy acostumbrado(circuitos, computación lógica, y demás).


Los acertijos que están basados en la lógica proposicional retan a las personas a obtener la respuesta correcta a partir de un conjunto de oraciones, las cuales pueden ser verdaderas o falsas según los condicionantes del propio acertijo.

Ejemplos:

[2]Guardian mentiroso

En una prisión de la que debemos salir, existen dos puertas. Una lleva a la salida. La otra, a la muerte segura. Cada puerta está custodiada por un guardián. Sabemos que uno de ellos dice siempre la verdad y que el otro miente siempre, pero no sabemos cuál es cada uno. La cuestión es: si pudieras hacer sólo una pregunta a uno de los dos, ¿qué pregunta le harías para saber qué puerta es la buena?

Solución: La pregunta que le haría es: "¿Cuál es la puerta que diría tu compañero que es la correcta?". En todo caso, la respuesta será la falsa.

[1]Knights and Knaves

Un visitante encuentra a tres habitantes de la isla de los caballeros y escuderos. Se acerca al primero y le pregunta: "¿Tú eres caballero o escudero?". Éste responde, pero el visitante no le entiende bien. Por su parte, el segundo dice: "Ha dicho que es escudero". Y el tercero apostilla: "Eso es mentira". ¿Qué son los habitantes segundo y tercero? (Tomando en cuenta que los caballeros siempre dicen la verdad, y los escuderos siempre mienten)

Solución: Nadie puede decir de sí mismo que es escudero, puesto que, si es caballero, debe decir la verdad y, si es escudero, dirá igualmente que es caballero porque miente siempre. Por lo tanto, el segundo habitante miente: es escudero. Y, el tercero, dice la verdad, por lo tanto, es caballero.

[2]Acertijo de los Cofres

Tenemos 4 cofres y dentro de uno hay un tesoro. Cada cofre contiene una inscripción y sabemos que 2 dicen la verdad y 2 mienten. ¿Dónde está el tesoro?

Cofre 1: El tesoro no está aquí.
Cofre 2: El cofre 1 dice la verdad.
Cofre 3: El tesoro no está en el cofre 2.
Cofre 4: El cofre 3 está vacío.

Solución: Para que se cumpla que dos digan la verdad y dos mientan, el tesoro debe estar en el cofre 1


Aplicación - Circuitos Lógicos

La aplicación quizás más conocida de la lógica proposicional son los circuitos lógicos.

[3]Un circuito lógico es un dispositivo que tienen una o más entradas y exactamente una salida.  En cada instante cada entrada tiene un valor, 0 o 1; estos datos son procesados por el circuito para dar un valor en su salida, 0 o 1.
Los valores 0 y 1 pueden representar ciertas situaciones físicas como, por ejemplo, un voltaje nulo y no nulo en un conductor.

Los circuitos lógicos se construyen a partir de ciertos circuitos elementales denominados compuertas lógicas, entre las cuales diferenciaremos:
  • Compuertas lógicas básicas:  OR, AND, NOT. 
  • Compuertas lógicas derivadas:  NOR, NAND
Un ejemplo de un circuito lógico, es el siguiente:

Compuerta OR 

En una compuerta OR con entradas A y B, la salida Y resulta: Y = A + B, donde dicha suma esta definida por la siguiente tabla.

ABY = A + B
000
011
101
111

La compuerta OR se representa del siguiente modo(aunque también puede tener más de dos entradas): 

Compuerta AND 

En una compuerta AND con entradas A y B, la salida Y resulta: Y = A * B, donde el producto se define por la siguiente tabla:

ABY = A * B
000
010
100
111


La compuerta AND se representa del siguiente modo(también puede tener más de dos entradas): 
Compuerta NOT 

En una compuerta NOT con entrada A, la salida Y resulta: Y = !A, donde el complemento se define por la siguiente tabla:

A
Y = !A
1
0
0
1

La compuerta NOT se representa del siguiente modo:
Compuertas NOR y NAND 

Las compuertas NOR y NAND no son básicas.  Una  compuerta NOR equivale a una compuerta OR seguida de una compuerta NOT.  Una  compuerta NAND equivale a una compuerta AND seguida de una compuerta NOT.





Por lo tanto, cuando las entradas son A y B, las salidas de estas compuertas resultan: 


Referencias

miércoles, 22 de agosto de 2012

Introductory Assignment: One-time-pad

For the first assignment, we were tasked to do a one time pad program. I chose python as a programming language, and did a simple version of the one-time-pad, which I will explain later.

One-time-pad

One-time-pad is a cipher method invented in 1917 by the Major Joseph Mauborgne and Gilbert Vernam from AT&T. Claude Shannon, 25 years later was in charge of proving with information theory that this cipher was infact a perfect secret, which means that the message content cannot give any useful information to the attacker.


In this cryptographic algorithm, plaintext is combined with a random key. It is the only known method to perform mathematically unbreakable encryption.
We can only talk about one-time pad if some important rules are followed. If these rules are applied correctly, the one-time pad can be proven unbreakable.

Even infinite computational power and infinite time cannot break one-time pad encryption, simply because it is mathematically impossible. However, if only one of these rules is disregarded, the cipher is no longer unbreakable.
  • The key is at least as long as the message or data that must be encrypted.
  • The key is truly random (not generated by a simple computer function or such)
  • Key and plain text are calculated modulo 10 (digits), modulo 26 (letters) or modulo 2 (binary)
  • Each key is used only once, and both sender and receiver must destroy their key after use.
  • There should only be two copies of the key: one for the sender and one for the receiver (some exceptions exist for multiple receivers.

Example:

First, we have or message, HELLO. Now we can get an integer number which would be the position of the letter in the alphabet. H would be 7, E is 4, L is 11, again L with 11, and finally O which is 14. Then we need to generate a random key, combining letters of the alphabet. This key needs to be the same size as our message, so it should be 5 characters long. Having the key, we add the position of the first letter of the message to the same of the key, then the second, third, etc, and save the values. Said values will be then normalized with the operation mod % 26 (26 letters in the alphabet), which will convert any number greater than 26 to a lesser number. Then this number will be the index of the corresponding letter to get a cipher text.

In the example bellow, we can see the process:

      H       E       L       L       O  message
   7 (H)   4 (E)  11 (L)  11 (L)  14 (O) message
+ 23 (X)  12 (M)   2 (C)  10 (K)  11 (L) key
= 30      16      13      21      25     message + key
=  4 (E)  16 (Q)  13 (N)  21 (V)  25 (Z) message + key (mod 26)
      E       Q       N       V       Z  → cipher text

Assuming this message is sent to someone who also knows the key(B), the person who encrypted this message(A) should delete the key. 

Then that B person, should be able to decrypt the message, doing the inverse operation ( substraction) and using the key.

       E       Q       N       V       Z  ciphertext
    4 (E)  16 (Q)  13 (N)  21 (V)  25 (Z) ciphertext
-  23 (X)  12 (M)   2 (C)  10 (K)  11 (L) key
= -19       4      11      11      14     ciphertext — key
=   7 (H)   4 (E)  11 (L)  11 (L)  14 (O) ciphertext — key (mod 26)
       H       E       L       L       O  → message

Code
from sys import argv, stdout
from random import randint

def letter_pos(letter):
  for i in range(len(alphabet)):
    if alphabet[i] == letter:
 return i

def wiki_cipher(msg, key):
  cipher_msg = ""
  #print msg
  for i in range(len(msg)):
    #print letter_pos(msg[i]), letter_pos(key[i])
    cipher_msg += alphabet[(letter_pos(msg[i]) + letter_pos(key[i])) % 25]
  del key
  #print cipher_msg
  return cipher_msg


def wiki_decipher(cipher_msg, key):
  msg = ""
  for i in range(len(cipher_msg)):
    #print letter_pos(cipher_msg[i]), letter_pos(key[i])
    msg += alphabet[(letter_pos(cipher_msg[i]) - letter_pos(key[i])) % 25]
  del key
  #print msg
  return msg

def print_otp(ciphers):
  for cipher in ciphers:
    stdout.write("%s\t"%(cipher))
  print ""

try:
  filename = argv[1]
  f = open(filename, "r")
  msg = f.readlines()[0]
  msg.replace("\n", "")
  print "Message:"
  print msg
except IndexError as err:
  print "File not specified, using default message."
  msg = "Testing the one time pad encryption"
  print "Message: %s"%msg.lower()
alphabet = "abcdefghijklmnopqrstuvwxyz"
forbidden = " .,-!?$%&/()=+{{}}][:;_"
if " " in msg:
  words = [""]
  j = 0
  for i in range(len(msg)):
    if msg[i] in forbidden or msg[i] == "\n":
      words.append("")
      j+=1
    else:
      words[j] += msg[i]
  del msg
  #print_otp(words)
  ciphers = []
  keys = []
  for word in words:
    key = ""
    for letter in word:
     key += alphabet[randint(0, 25)]
    keys.append(key)
    if word != None:
      ciphers.append(wiki_cipher(word.lower(), key))
  print "Encrypted Message:"
  print_otp(ciphers)
  print ""
  msg = ""
  for i in range(len(ciphers)):
    msg += wiki_decipher(ciphers[i], keys[i]) + " "
  print "Decrypted message: %s"%msg

else: 
  cipher_msg = wiki_cipher(msg, key)
  del msg
  wiki_decipher(cipher_msg, key)
The python script bellow applies the previous algorithm to simple words or phrases. If specified, the script reads the message from a file, otherwise it will use a default message as an example.


An example run using a file named "msg" with a message "Hello my name is Emmanuel and this is a simple one-time-pad message" produces the following ouput:




As you can see, the message is changed to lowercase, and some "forbidden" characters are ignored replacing them for a space.

References: