miércoles, 29 de agosto de 2012

Statistical test homework

Statistical test

Hi, in this homework i made a statistical test to my keys generated in the past homework, this is the link to my past homework (http://triana-integrador-cripto.blogspot.mx/2012/08/one-time-pad.html).

Ok, this is an example of 10 keys generated in mi program.


A numeric sequence is said to be statistically random when it contains no recognizable patterns or regularities.

Any method to generate random numbers must satisfy next conditions:

- Uniformly distributed
- Without constant repetition in a specified length (often not repeatable)
- Numbers must be independent of each other
- The series should be reproducible
- Numbers must be generated quickly
Well, there are many ways or methods to determine if a sequence of number are random.
I will use the method called: Media Test (Prueba de medias)


Media Test

Ok, media test method consists in verify that generated numbers have a statics media between upper and lower limits.


The 3 important elements to work with media test are the next:


* R = Is the summation of all numbers in the test, multiplied by (1/ total of numbers)
This number will be compared whit  the lower and upper limits. If the R value is in the range of the limits, the numbers are random, if R is out of range with the limits, the numbers are not random.
R is calculated:

 

  

* Lower limit = Is the lowest limit to compare with the "r"
Lower limit is calculated:


Za = Z value of alfa (not acceptance level). You must use the normal distribution table
* Upper limit = Is the highest limit to compare with the "r"
Upper limit is calculated:



We are going to set an alfa, alfa value is the number of error probabilities. Assuming we want a 95 percent of acceptance level, alfa will be 5 percent of not acceptance, so alfa = 0.05.

I'll create the keys like in the one time pad homework, like this:




Then i created a code to count all 0 and 1 in the text file, and the total of numbers.
zAlfa = 0.5199, because alfa = 0.05, here is the table were i got "z" value: http://www.tuveras.com/estadistica/normal/tabla.htm






And finally with all the number added, i calculated the value of "r". And too calculated the values of lower and upper limits.

Like this:

This is the entire code (if you want to copy it):

#!/usr/bin/python
#Carlos Triana
import random
import math
from numpy import *
def createKeys():
file1 = open('keys1.txt', 'w')#Creating file1
i = 0
j = 0
while i<10:
while j<7:
number = random.randint(0,2)
file1.write(str(number))#Filling file texts with random numbers
j = j +1
file1.write('\n') #To separate keys
j = 0
i = i + 1
file1.close()
mediaTest()
def mediaTest():
file1 = open('keys1.txt', 'r')#Reading key
x = 0
r = 0.0
zero = 0.0 #To count the total of zero
one = 1.0 #To count the total of one
upperLimit = 0.0 #Upper limit value
lowerLimit = 0.0 #Lower limit value
zAlfa = 0.5199 #Value of Z whit alfa = 0.05
for i in file1.xreadlines(): #To read each line of numbers
size = len(i)
while x < size:
if i[x] == "0":
zero = zero + 1.0 #If number = 0, increase counter(zero)
elif i[x] == "1": #If number = 1, increase counter(one)
one = one + 1.0
x = x + 1
x = 0
file1.close()
one = one - 1.0
total = 0.0
total = zero + one #Total of numbers
r = (1/total)*(one) #'r' is the number to compare whit limits(upper,lower)
lowerLimit = (0.5) - ((zAlfa/2)*(1/math.sqrt(12*(total)))) #Calculating lowerLimit
upperLimit = (0.5) + ((zAlfa/2)*(1/math.sqrt(12*(total)))) #Calculating upperLimit
if (r >= lowerLimit and r <= upperLimit):
print "\nGenerated numbers are random :)\n"
#If 'r' is between lowerLimit and upperLimim, numbers are random
else:
print "\nGenerated numbers are not random at all :(\n"
#If 'r' is out of the limits, numbers are not random
print "zero = " + str(zero) #Printing total of 0 in the txt
print "one = " + str(one) #Printing total of 1 in the txt
print "total = " + str(total) #Printing total of numbers
print "r = " + str(r) #Printing R
print "lowerLimit = " + str(lowerLimit) #Printing Lower and upper limits
print "upperLimit = " + str(upperLimit)
print
def main():
createKeys()
main()
view raw MediaTest.py hosted with ❤ by GitHub

These are some screen shots of my program running: 

TEST:

Generated keys                                                                              Results



Bibliography:


If you have any doubt you can leave it in comments. 
Sorry for my bad english. Thank you! 


martes, 28 de agosto de 2012

One time pad

One Time Pad

Hi everyone, this is the homework of one time pad. Firstly one time pad is a concept  of cryptography, is a type of encryption algorithms by which the plain text is combined with a random key same length as the plain text and used only once. It was invented in 1917. If the key is truly random, never reused and, of course, is kept secret, it can be shown that the method of the one-time pad is unbreakable. 

So, for this homework i created a one time pad encryption using Python, i'll resume all my work in few steps. 

1 - I created the text files ("keys1.txt", and "keys2.txt")






These are all the keys generated(in both files: "keys1.txt", and "keys2.txt"). 10 different keys, but it doesn't matter because each message crypted and decrypted will generate different keys. The length of each key is 7  because this is the length of ASCII values (in binary).





2 - I requested to user for a string 




3 - Each character of the string gave by the user goes to the encrypt function.






4 - Then each character goes to the decrypt function





5 - Finally i printed out the binary value of the character, key used,  xor result, xor decrypted (using xor method again), ASCII value and the character decrypted.





Now, this is all my code...

#!/usr/bin/python
#Carlos Triana
import random
from numpy import *
def createKeys():
file1 = open('keys1.txt', 'w') #Creating file1
file2 = open('keys2.txt', 'w') #Creating file2
i = 0
j = 0
while i<10:
while j<7:
number = random.randint(0,2)
file1.write(str(number)) #Filling file texts with
file2.write(str(number)) #random numbers(binary)
j = j +1
file1.write("\n")
file2.write("\n")
j = 0
i = i + 1
file1.close()
#crypt()
def crypt(binary, size, i):
st = ""
st2 = ""
xor = []
file1 = open('keys1.txt', 'r') #Reading key
st = file1.readline()
key = list(st)
j = 0
while j < 7:
if(binary[j] == key[j]): #Crypting character
xor.append(0)
else:
xor.append(1)
j = j+1
decrypt(xor,binary, i, size)
file1.close()
if(i == size-1):
createKeys()
def decrypt(xor,binary, i, size):
st2 = ""
dec = []
file2 = open('keys2.txt', 'r') #Reading keys
st2 = file2.readline()
key2 = list(st2)
k = 0
PreDecrypt = []
while k < 7:
number = 4
number = int(key2[k])
if(xor[k] == number): #Decrypting character(xor)
dec.append(0)
else:
dec.append(1)
k = k + 1
file2.close()
print "binary = " + str(binary) #This is the binary of the character
print "key used = " + str(key2) #This is the key saved in the "keys2.txt" file
print "xor or crypted = "+str(xor) #This is the key crypted (by xor)
print "decrypted(binary) = "+str(dec)#This is the binary decrypted
numero = "bla"
numero = str(dec).strip('[]')
numero = numero[::3] #Removing characters("," and " ")
baseDiez = int(numero, 2)
print "ASCII decrypted = "+str(baseDiez) #This is the ASCII value of the binary(character)
decoder = chr(baseDiez)
if (decoder == "@"): #For the "backspace" values
decoder = " "
if (baseDiez == 16): #For the "backspace" values
decoder = " "
print "Character decrypted = " + str(decoder) #This is the character decrypted
print
if(i == size-1): #If the character is the last one,
createKeys() #create keys again(one time pad)
def string2Binary():
myInput = "" #Requesting a string
myInput = raw_input('Get in a string to crypt it: ')
newInput = list(myInput)
size = len(myInput)
binary = []
i = 0
while i < size:
if (newInput[i] == " "):
st = "001000000"
else:
st = bin(ord(newInput[i])) #Converting to binary
st = st[2:] #I dont care first 2 values("0b")
binary.append(st)
crypt(binary[i], size, i) #Crypting the binary(previously character)
i = i+1
def main():
createKeys()
while True:
number = input('Get in 1 to continue or 2 to exit: ') #1 to crypt/decrypt
if (number == 1): #2 to exit
string2Binary()
else:
break
main()
view raw OneTimePad.py hosted with ❤ by GitHub


Finally this is mi program running (The message is: its)


If you want to write more messages you must to type 1 (if you type 2, program will close), and new messages will be crypted with other new key.



Leave your comment if you have any doubt


Thank you