Browse Source

Splitted READMEs

root 8 years ago
parent
commit
4fdd1bd9ed
3 changed files with 471 additions and 471 deletions
  1. 232
    0
      README-en.md
  2. 237
    0
      README-es.md
  3. 2
    471
      README.md

+ 232
- 0
README-en.md View File

@@ -0,0 +1,232 @@
1
+
2
+# Repetition Structures - Vigenere Cipher
3
+
4
+![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/DYSdjlN.png)
5
+![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/TEk9bMp.png)
6
+![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/3PV1IiK.png)
7
+
8
+
9
+
10
+One of the advantages of using computer programs is that we can easily implement repetitive tasks. Structures such as the `for`, `while`, and `do-while` allow us to repeat a block of instructions as many times as needed. In this lab experience you will use `for` loops to complete a simple ciphering application.
11
+
12
+##Objectives:
13
+
14
+1. Apply repetition structures to cipher a plain-text message.
15
+2. Practice character arithmetic.
16
+
17
+
18
+##Pre-Lab:
19
+
20
+Before coming to the lab session you should have:
21
+
22
+1. Reviewed basic concepts related to repetition structures.
23
+
24
+2. Reviewed the string class in C++. In particular, how to create string objects and the `length`, `toupper` and `push_back` methods.  Also review the `isalpha` function and character arithmetic.
25
+
26
+3. Watched Khan Academy’s "Ceasar Cypher" video at https://www.youtube.com/watch?v=sMOZf4GN3oc .
27
+
28
+4. Watched Khan Academy’s "Vigenere Cypher" video at https://www.youtube.com/watch?v=9zASwVoshiM .
29
+
30
+5. Studied the concepts and instructions for the laboratory session.
31
+
32
+
33
+
34
+---
35
+
36
+---
37
+
38
+##Criptography
39
+
40
+Cryptography is the area of knowledge that studies the theory and methods that are used for protecting information so that non-authorized persons cannot understand it. A *cryptographic system* is a system that transforms a *cleartext message* (a message that is understandable to humans) to a *cyphered* text (text that is unintelligible to unauthorized persons).  Authorized persons can *decypher* the *cyphered* text to obtain the original cleartext.
41
+
42
+###The Ceasar Cypher
43
+
44
+The Caesar Cypher is a substitution encryption technique that is said to have been used by Julius Caesar (100 BC - 44 BC), the Roman political and military leader, to communicate with his generals. To encrypt a message using the Caesar Cipher each letter of the cleartext message is substituted by the letter found a given number of positions ahead in the alphabet. You may think of this as a shift of the letter in the alphabet. Figure 1 illustrates a shift of 3 spaces within the alphabet. For instance, letter ‘B’ would be substituted by letter ‘E’.
45
+
46
+---
47
+
48
+![figure1.png](images/figure1.png)
49
+
50
+**Figure 1.** Caesar Cypher with shift of three.
51
+
52
+---
53
+
54
+**Example 1.** With a shift of three, the word “ARROZ” is ciphered as “DUURC”. Observe that, with the shift of 3, letter ‘Z’ is ciphered as letter ‘C’. Any shift that takes us beyond letter ‘Z’ starts again at letter ‘A’. This is called cyclic shift. Figure 2 illustrates a circular shift of eight positions.
55
+
56
+---
57
+
58
+![figure2.png](images/figure2.png)
59
+
60
+**Figure 2.** A Caesar cipher disk showing a shift of 8 positions.
61
+
62
+---
63
+
64
+###Using the modulo operator
65
+
66
+Modular addition is essential for implementing ciphering systems in programming. Let’s say that you map every letter of the (English) alphabet to a number between 0 to 25 (‘A’ is 0, ‘B’ is 1, .., ‘Z’ is 25). To Caesar cipher a letter we convert the letter to its corresponding number in the range [0,25], then add the displacement. We then apply the modulo 26 operation to the total. The letter that corresponds to the result after the modulo is the ciphered letter. The effect of the circular shift is achieved by using the modulo 26 operation because it converts the result of the addition to an integer in the range [0,25]. For instance, if we were to shift the letter ‘Z’ by three positions, this would be performed by adding ( 25 + 3 ) % 26 which equals 2, whose corresponding letter is ‘C’.  
67
+
68
+To convert an uppercase letter to a number in the [0,25] range we can apply our knowledge of the ASCII code. The code for the uppercase letters is in the range [65,90]  (‘A’ is 65, ‘Z’ is 90). Thus, to convert an uppercase case to a number in the range [0,25], a simple subtraction by 65 does the trick (i.e. `’A’ - 65 = 0`, `’Z’ - 65 = 25`).  Observe that to go from the [0,25] range to the ASCII code of its corresponding uppercase character we simply add 65 to the number. For instance, number 3 corresponds to the letter whose ASCII code is $3 + 65 = 68$, i.e. letter ‘D’.  
69
+
70
+Figure 3 shows the pseudocode of an algorithm for the Caesar cipher. Each letter ‘c’ in the cleartext message is converted to a number in the range [0,25]  (by subtracting ‘A’). The displacement d is then added to the number (modulo 26) . Lastly, the result of the modular addition is converted back to its corresponding letter by adding the ASCII code of ‘A’. 
71
+
72
+---
73
+
74
+```cpp
75
+    Input: msg: a string of the cleartext message, d: the displacement
76
+    Output: Caesar ciphered message 
77
+
78
+    1. cypheredText = ""
79
+    2. for each character c in msg:
80
+           c = ascii(c) - ascii('A')  # map c from [‘A’,’Z’] to [0,25]
81
+           c = ( c + d ) % 26         # circular shift c by d positions
82
+           c = ascii(c) + ascii('A')  # map c from [0,25] to [‘A’,’Z’]
83
+           cypheredText.append(c) 
84
+    3. return cypheredText 
85
+```
86
+
87
+**Figure 3.** Pseudocode for a Caesar cipher algorithm.
88
+
89
+---
90
+
91
+The Caesar cipher is considered a weak encryption mechanism because it can easily be deciphered by using frequency analysis on the ciphered message. For example, we can use the fact that letter ‘e’ is the most frequent letter in most texts. If we find the most frequent letter in a ciphered text it very probably corresponds to the letter that was substituted by ‘e’. With this information we can compute the displacement that was used and decipher the rest of the message.
92
+
93
+PONER PREGUNTAS DIAGNOSTICAS AQUí
94
+
95
+###The Vigenere Cypher 
96
+
97
+A main weakness of the Caesar cipher is that every letter in the cleartext message is shifted by the same number of positions. The Vignere cipher is a somewhat stronger encryption method because the shift used on each letter is not constant. Whereas the Caesar cipher receives as input a cleartext message and a displacement, the Vignere receives the cleartext message and **keyword**. For now, lets assume that the keyword and the cleartext message have the same length. The Vignere cipher uses the keyword to determine the shift that will be applied to each letter of the cleartext message, i.e. the first letter of the keyword determines the shift number for the first letter of the message and so forth. 
98
+
99
+**Example 2.** Suppose that the cleartext is “PET” and the keyword is “BED”. Each letter in the **keyword** determines the shift amount of the corresponding letter in the cleartext: letter ‘A’ specifies a shift of 0, ‘B’ is a shift of 1, and so on.  Thus, the ‘B’ in the keyword “BED” states that we shall shift the first letter of the cleartext by 1, the ‘E’ states that we will shift second the letter by 4 and the ‘D’ states that we will shift the last letter by 3.
100
+
101
+---
102
+
103
+| cleartext       | P | E | T |
104
+|-----------------|---|---|---|
105
+| keyword         | B | E | D |
106
+|-----------------|---|---|---|
107
+| ciphered text  | Q | I | X |
108
+
109
+**Figure 4.** Letter ‘P’ in the cleartext is shifted by 1 to ‘Q’  as indicated by the corresponding letter in the keyword (B).   Letter ‘E’ in the cleartext is shifted by 4 to ‘I’  as indicated by the corresponding letter in the keyword (E).   Letter ‘T’ in the cleartext is shifted by 3 to ‘X’  as indicated by the corresponding letter in the keyword (D).  
110
+
111
+
112
+---
113
+
114
+Figure 5 shows a table that can be used to determine the Vigenere-ciphered letter, given the cleartext and keyword letter.  Notice that each row contains the entire alphabet shifted by the amount specified by the letter at the beginning of the row.
115
+ 
116
+---
117
+
118
+![figure6.png](images/figure6.png)
119
+
120
+**Figure 5.** Table for the Vigenere-cipher. The shaded row and column illustrate how to cipher the letter ‘R’ with key letter ‘M’.
121
+
122
+---
123
+
124
+If the keyword is shorter than the cleartext, the Vigenere cipher simply repeats the keyword as many times as needed to account for all the letters of the cleartext. Figure 6, illustrates the keyword and cleartext pairing for an example. 
125
+
126
+---
127
+
128
+| cleartext       | P | R | O | G | R | A | M |   | T | H | I | S |
129
+|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
130
+| keyword         | S | H | O | R | T | S | H | O | R | T | S | H |
131
+|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
132
+| ciphered text   | H | Y | C | X | K | S | T |   | K | A | A | Z |
133
+
134
+
135
+**Figure 6.** Alignment of a cleartext with a shorter keyword and the resulting cipher.
136
+
137
+---
138
+
139
+##Functions that will be used in this laboratory experience: 
140
+
141
+The program that you will be modifying in today’s experience uses the following methods of the `string` class:
142
+
143
+* `length`: Returns the length of a `string` object, i.e. the number of characters in the string (including invisible characters such as the space and end-line).  To invoke the `length` method of string object write `.length()` after the object’s name, e.g. `msg.length()`.
144
+
145
+* `push_back(char c)`: adds the character passed as argument to the end of the string. For example, the instruction `msg.push_back(‘a’)` adds character `a` to the end of an object called `msg`. 
146
+
147
+We will also use the following functions:
148
+
149
+* `char toupper(char c)`: given a character as an argument, this function returns the character in uppercase. For example, `toupper(‘b’)` returns `B`. 
150
+
151
+* `int isalpha(char c)`: Given a character as an argument, this function returns a non-zero value when the character is a letter. Otherwise it returns 0. As you know, C++ interprets non-zero values as `true` and zero as `false`. Thus, for example, the call `isalpha(‘3’)` returns `false`. The call returns `isalpha(‘f’)` returns `true`.
152
+
153
+
154
+
155
+---
156
+
157
+---
158
+
159
+
160
+!INCLUDE "../../eip-diagnostic/vigenere/en/diag-vigenere-01.html"
161
+
162
+!INCLUDE "../../eip-diagnostic/vigenere/en/diag-vigenere-02.html"
163
+
164
+!INCLUDE "../../eip-diagnostic/vigenere/en/diag-vigenere-03.html"
165
+
166
+---
167
+
168
+---
169
+
170
+
171
+##Laboratory session:
172
+
173
+You will be completing an application to cipher a message using the Vigenere technique. To simplify coding, the keyword and cleartext must consist exclusively of letters. Furthermore, your program must change both the cleartext and keyword to uppercase before ciphering. 
174
+
175
+###Exercise 1: Keyword and cleartext of the same length
176
+
177
+In this exercise you will implement a function that given a cleartext and keyword of equal length returns the cipher message. 
178
+
179
+####Instructions
180
+
181
+1. Load the Qt project called `VigenereCypher` by double-clicking on the `VigenereCypher.pro` file in the `Documents/eip/Repetitions-VigenereCypher` folder of your computer. Alternatively you may clone the git repository `http://bitbucket.org/eip-uprrp/repetitions-vigenerecypher` to download the `Repetitions-VigenereCypher` folder to your computer.
182
+ 
183
+2. You will be writing your code in the `cypher.cpp` file. In this file, the `cypher` function receives a message and a keyword of equal length and that consist exclusively of letters, and returns the Vigenere-ciphered message. Your task is to finish the implementation of the `cypher` function.
184
+     
185
+    Using the methods and functions discussed earlier, your implementation must verify if the message and keyword consist exclusively of letters and are of equal length. If that is not the case, the ciphered message must be (literally) `"MENSAJE O CLAVE INVALIDO"`. Remember that your program must change both the cleartext and keyword to upper-case letters before ciphering.
186
+
187
+3. After you implement the `cypher` function, go to the `main` function and uncomment the line that invokes `test_cypher1`. The `test_cypher1` function is a unit test for the `cypher` function. It calls the `cypher` function with various arguments to verify if it returns correct results. If any of the results is incorrect the program stops and reports the test case that failed. You will not see the application’s graphical user interface until the unit test passes all validations.  Once you see the graphical user interface you may continue onto the next part of this lab experience.
188
+
189
+
190
+###Exercise 2: Keyword and cleartext of arbitrary lengths
191
+
192
+In this exercise you will modify the code for the cypher function from Exercise 1 so that the application can now cipher a message using a keyword of arbitrary length. 
193
+
194
+####Instructions
195
+
196
+1. Modify the implementation of the `cypher` function so that it can cipher a message with a keyword of any (non-zero) length. For this exercise the message may contain any character (including non alphabetical characters). The keyword must consist exclusively of letters. 
197
+
198
+    Whenever the character in the cleartext is not a letter it will not be ciphered, as seen in Figure 7. If any character in the keyword is not a letter, the ciphered message will be (literally) `”CLAVE INVALIDA”`. 
199
+
200
+    ---
201
+
202
+| cleartext       | P | R | @ | G | R | * | M |   | T | 8 | I | S |
203
+|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
204
+| keyword         | S | H | O | R | T | S | H | O | R | T | S | H |
205
+|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
206
+| ciphered text   | H | Y | @ | X | K | * | T |   | K | 8 | A | Z |
207
+
208
+
209
+    **Figure 7.** Example Vignere cipher of the cleartext `“PR@GR*M T8IS”` using the keyword `SHORT”`. 
210
+
211
+    ---
212
+
213
+
214
+2. After you implement the `cypher` function, modify the `main` function so that the line that invokes `test_cypher2` is uncommented, and the line that invokes `test_cyper1` is commented. Once again, you will not see the app’s graphical user interface until the `test_cypher2` verifications.
215
+ 
216
+---
217
+
218
+---
219
+
220
+##Deliverables
221
+
222
+
223
+Use "Deliverables" in Moodle to upload the `cypher.cpp` file that contains the `cypher` function that you created in Exercise 2.  Remember to use good programming techniques, include the names of the programmers involved, and to document your program.
224
+
225
+
226
+---
227
+
228
+---
229
+
230
+##References
231
+
232
+http://www.nctm.org/uploadedImages/Classroom_Resources/Lesson_Plans/

+ 237
- 0
README-es.md View File

@@ -0,0 +1,237 @@
1
+
2
+# Estructuras de repetición - Cifrado Vigenere
3
+
4
+![main1.png](images/main1.png)
5
+![main2.png](images/main2.png)
6
+![main3.png](images/main3.png)
7
+
8
+[version 2016.05.04]
9
+
10
+Una de las ventajas de utilizar programas de computadoras es que podemos realizar tareas repetitivas fácilmente. Los ciclos como `for`, `while`, y `do-while` son  estructuras de control que nos permiten repetir un conjunto de instrucciones. A estas estructuras también se les llama *estructuras de repetición*. En la experiencia de laboratorio de hoy utilizarás ciclos `for`  para completar una aplicación de cifrado.
11
+
12
+##Objetivos:
13
+
14
+1. Aplicar estructuras de repetición para cifrar un mensaje.
15
+2. Practicar operaciones aritméticas con caracteres.
16
+
17
+##Pre-Lab:
18
+
19
+Antes de llegar al laboratorio debes:
20
+
21
+1. Haber repasado los conceptos básicos relacionados a estructuras de repetición.
22
+
23
+2. Haber repasado conceptos básicos de la clase `string` de C++,las funciones `length`, `toupper` y `push_back`, `isalpha` y las operaciones aritméticas con caracteres.
24
+
25
+3. Haber visto el video sobre el "Ceasar Cypher" del Khan Academy, colocado en <https://www.youtube.com/watch?v=sMOZf4GN3oc>.
26
+
27
+4. Haber visto el video sobre el "Vigenere Cypher", colocado en <https://www.youtube.com/watch?v=9zASwVoshiM>.
28
+
29
+5. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.
30
+
31
+
32
+---
33
+
34
+---
35
+
36
+##Criptografía 
37
+
38
+La *criptografía* es un área que estudia la teoría y los métodos utilizados para proteger información de modo que personas que no estén autorizadas no puedan tener acceso a ella. Un *sistema criptográfico* es un sistema en el que la información (*mensaje* entendible por humanos)  es tranformada a un texto cifrado inentendible para las personas no autorizadas a verlo. Las personas autorizadas a ver el mensaje usan un *descifrador* para revertir el texto cifrado al mensaje original.  
39
+
40
+###El Cifrado César (Ceasar Cypher)
41
+
42
+El Cifrado César es una técnica muy simple de cifrado por sustitución. Se dice que el sistema se basa en el sistema utilizado por Julio César, líder militar y político de Roma en años antes de Cristo, para comunicarse con sus generales. La técnica cifra un mensaje de texto sustituyendo cada letra del mensaje por la letra que se encuentra a un número dado de posiciones más adelante en el alfabeto. Esto puede pensarse como un desplazamiento ("shift") del alfabeto. El diagrama de la Figura 1 representa un desplazamiento de 3 espacios. La letra ‘B’ es sustituida por la letra ‘E’.
43
+
44
+---
45
+
46
+![figure1.png](images/figure1.png)
47
+
48
+**Figura 1.** Cifrador César con desplazamiento de 3 espacios.
49
+
50
+---
51
+
52
+**Ejemplo 1:** Con un desplazamiento de 3 espacios, la palabra "ARROZ" quedaría cifrada como "DUURC". Nota que, con este desplazamiento de 3 espacios, la letra ‘Z’ es sustituida por la letra ‘C’.  Cuando el desplazamiento se pasa de la letra ‘Z’ comenzamos nuevamente en la letra ‘A’. Esto se llama un desplazamiento cíclico. La Figura 2  muestra un desplazamiento cíclico de 8 espacios.
53
+
54
+---
55
+
56
+![figure2.png](images/figure2.png)
57
+
58
+**Figura 2.** Disco para cifrador César que muestra un desplazamiento de 8 espacios.
59
+
60
+---
61
+
62
+###Utilizando el operador módulo
63
+
64
+La operación de suma modular es esencial para implementar sistemas de cifrado en programación. En la aplicación de cifrado César de arriba podemos pensar que a cada letra del alfabeto (en inglés) le asignamos un número entre 0 y 25 (La `A` es 0, la`B` es 1, …, la `Z` es 25). El cifrador César convierte cada letra al número correspondiente en el intervalo [0, 25] y luego suma el desplazamiento. Para hacer el desplazamiento cíclico, cada vez que nuestro desplazamiento nos dé una letra que corresponda a un número mayor que 25, tomamos el residuo al dividir por 26 y usamos la letra que corresponda a ese residuo. Nota que tomar el residuo al dividir por 26 los resultados estarán entre 0 y 25, que son los valores asociados al alfabeto.
65
+
66
+El residuo al dividir dos números enteros se puede obtener utilizando el operador de *módulo*: `%`.
67
+
68
+Volviendo al Ejemplo 1, en la palabra "ARROZ", a la letra ‘Z’ le corresponde el número 25; al hacer un desplazamiento de 3 espacios, sumamos 3 a 25 y esto nos resulta en 28 que es un número mayor que 25. Si tomamos el residuo al dividir $25 + 3$ por 26, `(25 + 3) % 26`, obtenemos 2, que corresponde a la letra ‘C’. 
69
+
70
+El proceso de arriba funciona si podemos asociar las letras de la ‘A’ a la ‘Z’ con los números del `0` al `25`. Esto se logra utilizando el valor numérico de los caracteres. Como en  el código ASCII el valor de las letras ‘A’ a la ‘Z’ va desde 65 hasta 90,  necesitamos hacer un ajuste en el cómputo de modo que a la `A` se le asigne `0`. Para convertir una letra mayúscula a un número en el intervalo [0, 25] solo tenemos que restar 65 (`’A’ - 65 = 0`, `’Z’ - 65 = 25`). Para cambiar un valor en el intervalo [0, 25] a la letra mayúscula que corresponde en el código ASCII solo tenemos que sumar 65 al número. Por ejemplo, el número 3 corresponde a la letra cuyo código ASCII es $3 + 65 = 68$, la letra ‘D’.
71
+
72
+La Figura 3 muestra el pseudocódigo para una algoritmo para el cifrador César. Cada letra ‘c’ en el mensaje se convierte a un número en el intervalo [0, 25] (restándole ‘A’), luego se hace el desplazamiento de d unidades al número (sumando d módulo 26). Finalmente se convierte el resultado al caracter correspondiente sumando el código ASCII de ‘A’.
73
+
74
+---
75
+
76
+```cpp
77
+    Datos de entrada: un "string" de mensaje, la cantidad de desplazamiento d 
78
+    Datos de salida: el mensaje cifrado usando cifrado César 
79
+
80
+    1. cypheredText = ""
81
+    2. para ("for") cada caracter c in en el mensaje:
82
+           c = ascii(c) - ascii('A')  # mueve c del intervalo [A,Z] al [0,25]
83
+           c = ( c + d ) % 26         # desplaza (cíclicamente) c por d unidades
84
+           c = ascii(c) + ascii('A')  # mueve c del intervalo [0,25] al [A,Z]
85
+           cypheredText.append(c) 
86
+    3. devuelve ("return") cypheredText 
87
+```
88
+
89
+**Figura 3.** Pseudo-código para cifrar utilizando un cifrador César.
90
+
91
+---
92
+
93
+El cifrado César no es muy seguro ya que puede descifrarse fácilmente con un análisis de frecuencia. Por ejemplo, se sabe que en el idioma inglés la letra ‘e’ es la letra más frecuente en un texto. Si buscamos la letra que más se repite en un texto cifrado con un cifrador César, lo más probable es que esa fue la letra que se sustituyó por la ‘e’; con esto podemos deducir cuál fue desplazamiento utilizado y así descifrar el mensaje.
94
+
95
+
96
+
97
+###El Cifrado Vigenere 
98
+
99
+La debilidad principal del cifrador César es que cada letra en el mensaje se desplaza por el mismo número de posiciones. El cifrado Vigenere es un método de cifrado un poco más fuerte porque el desplazamiento en cada letra no es constante. El cifrado César recibe como datos de entrada el mensaje y un desplazamiento, mientras que el cifrado Vigenere recibe como dato de entrada el mensaje y una **clave** que determina el desplazamiento que se le hará a cada letra del mensaje.
100
+
101
+**Ejemplo 2.** Supongamos por el momento que tanto el mensaje como la clave tienen el mismo largo. Por ejemplo, suponga que el mensaje es "COSAS" y la palabra clave es "MENOR". La letra ‘C’ se parea con la letra ‘M’, la letra ‘O’ se parea con la letra ‘E’, la ‘S’ con la ‘N’, etcétera, como en la figura de abajo. Como la letra ‘A’ corresponde a un desplazamiento de 0 espacios, entonces la letra ‘M’ corresponde a un desplazamiento de 12 espacios, la ‘E’ a un desplazamiento de 4 espacios, etc. Utilizando la palabra clave "MENOR", el cifrador Vigenere hará un desplazamiento de 12 espacios a la letra ‘C’, un desplazamiento de 4 espacios a la letra ‘O’, etc., hasta obtener la palabra cifrada "OSFOJ" como se muestra en la Figura 4. 
102
+
103
+---
104
+
105
+| mensaje         | C | O | S | A | S |
106
+|-----------------|---|---|---|---|---|
107
+| clave           | M | E | N | O | R |
108
+| mensaje cifrado | O | S | F | O | J  |
109
+
110
+**Figura 4.** Alineamiento del mensaje con la palabra clave y cifrado.
111
+
112
+---
113
+
114
+Podemos visualizar un cifrador Vigenere utilizando una tabla como la de la Figura 5. Nota que lo que se hace es usar un cifrador César con un desplazamiento diferente para cada letra del mensaje.
115
+
116
+---
117
+
118
+![figure6.png](images/figure6.png)
119
+
120
+**Figura 5.** Tabla para cifrador Vigenere.
121
+
122
+---
123
+
124
+Si la palabra clave es más corta que el mensaje, entonces repetimos la palabra clave tantas veces como haga falta, pareando letras del mensaje con letras de la palabra clave como se hace en la Figura 6.
125
+
126
+---
127
+
128
+|     mensaje     | A | L | G | U | N | A | S |   | C | O | S | A | S |
129
+|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|---|
130
+| clave           | M | E | N | O | R | M | E | N | O | R | M | E | N |
131
+| mensaje cifrado | M | P | T | I | E | M | W |   | Q | F | E | E | F |
132
+
133
+
134
+**Figura 6.** Alineamiento del mensaje con la palabra clave y cifrado.
135
+
136
+---
137
+
138
+##Funciones que se utilizarán en esta experiencia de laboratorio:
139
+
140
+El programa que estarás modificando en la sesión de hoy utiliza los siguientes métodos de la clase `string`:
141
+
142
+* `length`: Devuelve el largo de un objeto de la clase `string`; esto es, `length` devuelve el número de caracteres que tiene el "string". Se utiliza escribiendo `.length()` después del nombre del objeto.
143
+
144
+* `push_back`: Este método recibe un caracter como argumento y lo añade al final del “string”. Se utiliza escribiendo `.push_back(elCaracter)` después del nombre del “string”. Por ejemplo, para añadir el caracter 'a' a  un objeto de la clase `string` llamado  `cadena`, escribimos `cadena.push_back('a')`.
145
+
146
+También utilizaremos las funciones:
147
+
148
+* `toupper`: Esta función recibe como argumento un caracter y devuelve el caracter en mayúscula. Por ejemplo, para cambiar el caracter 'a' a mayúscula se utiliza `toupper('a')`.
149
+
150
+* `isalpha`: Esta función recibe como argumento un caracter y devuelve un valor distinto de cero (`true`) si el caracter es una letra y cero (`false`) si el caracter no es una letra. Por ejemplo, `isalpha(3)` devuelve "false" pero `isalpha(‘F’)` devuelve `true`.
151
+
152
+
153
+---
154
+
155
+---
156
+
157
+
158
+!INCLUDE "../../eip-diagnostic/vigenere/es/diag-vigenere-01.html"
159
+
160
+!INCLUDE "../../eip-diagnostic/vigenere/es/diag-vigenere-02.html"
161
+
162
+!INCLUDE "../../eip-diagnostic/vigenere/es/diag-vigenere-03.html"
163
+
164
+
165
+---
166
+
167
+---
168
+
169
+
170
+##Sesión de laboratorio:
171
+
172
+En esta experiencia de laboratorio completarás una aplicación para cifrar un mensaje de texto utilizando el cifrado Vigenere. Para simplificar el código, la clave y el mensaje deben consistir solo de letras y tu programa debe cambiar todas las letras del mensaje y la clave a mayúsculas.
173
+
174
+###Ejercicio 1: Cifrador con clave y mensaje del mismo largo (solo letras)
175
+
176
+En este ejercicio completarás la aplicación para cifrar un mensaje de texto, 
177
+que solo contiene letras, utilizando una palabra clave que también consiste solo de letras y que tiene el mismo largo del mensaje. 
178
+
179
+####Instrucciones
180
+
181
+1. Descarga la carpeta Repetitions-VigenereCypher de Bitbucket usando un terminal, moviéndote al directorio Documents/eip, y escribiendo el comando git clone http://bitbucket.org/eip-uprrp/repetitions-vigenerecypher.
182
+
183
+2. Carga a Qt Creator el proyecto VigenereCypher haciendo doble "click" en el archivo VigenereCypher.pro que se encuentra en la carpeta Documents/eip/Repetitions-VigenereCypher de tu computadora.
184
+
185
+3. Estarás añadiendo código en el archivo `cypher.cpp`. En este archivo, la función `cypher` recibe un mensaje y una clave del mismo largo y consistentes solo de letras, y devuelve el mensaje cifrado por el cifrador Vigenere. Tu tarea es completar la función de cifrado.
186
+ 
187
+    El código debe verificar si el mensaje y la clave consisten solo de letras y tienen el mismo largo; si esto no ocurre, el mensaje cifrado será (literalmente) `"MENSAJE O CLAVE INVALIDO"`. El programa debe implementar el cifrador Vigenere para ir cifrando cada letra del mensaje utilizando la clave.  Solo debes utilizar las funciones mencionadas en la sección anterior. Para simplificar el código tu programa debe cambiar todas las letras del mensaje y la clave a mayúsculas.
188
+
189
+4. Al terminar tu código, ve a la función `main` y descomenta la invocación a la función de prueba unitaria  `test_cypher1`. Esa función realiza varias invocaciones a la función `cypher` para validar si sus resultados son correctos. Tu función `cypher` debe pasar todas las pruebas antes de continuar con la próxima parte de este laboratorio. 
190
+
191
+
192
+###Ejercicio 2: Cifrador con clave y mensaje de largos arbitrarios 
193
+
194
+En este ejercicio modificarás el código de la función `cypher` que creaste para el Ejercicio 1 de modo que la aplicación ahora pueda cifrar cualquier mensaje  utilizando una palabra clave que consista solo de letras pero que tenga cualquier largo. 
195
+
196
+####Instrucciones
197
+
198
+1. Escribe el código de la función `cypher` para que reciba un mensaje y una clave y devuelva el mensaje cifrado por el cifrador Vigenere. En esta ocasión, el mensaje y la clave pueden tener cualquier largo y el mensaje puede tener cualquier caracter (la clave solo puede tener letras). 
199
+
200
+El programa debe implementar el cifrador Vigenere para ir cifrando cada caracter del mensaje utilizando las letras de la clave.  Para simplificar el código, tu programa debe cambiar todas las letras a mayúsculas. Si alguno de los caracteres del mensaje no es una letra, el cifrador no lo cambia, como se muestra en la Figura 7. Si alguno de los caracteres de la clave no es una letra, el mensaje cifrado será "CLAVE INVALIDA". Solo debes utilizar las funciones mencionadas en la sección anterior.
201
+
202
+    ---
203
+
204
+    |     mensaje     | A | L | & | U | N | A | $ |   | C | O | S | A | S |
205
+    |-----------------|---|---|---|---|---|---|---|---|---|---|---|---|---|
206
+    | clave           | M | E | N | O | R | M | E | N | O | R | M | E | N |
207
+    | mensaje cifrado | M | P | & | I | E | M | $ |   | Q | F | E | E | F |
208
+
209
+
210
+    **Figura 7.** Ejemplo de mensaje y clave con largo distinto y símbolos en el mensaje.
211
+
212
+    ---
213
+
214
+2. Al terminar tu código, ve a la función `main`, comenta la invocación a la función de prueba unitaria `test_cypher1` y descomenta la invocación a la función de prueba unitaria `test_cypher2` para que verifiques tu programa.
215
+
216
+---
217
+
218
+---
219
+
220
+##Entrega
221
+
222
+Utiliza "Entrega" en Moodle para entregar el archivo `cypher.cpp` que contiene la función `cypher` que creaste en el Ejercicio 2. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.
223
+
224
+---
225
+
226
+---
227
+
228
+##Referencias
229
+
230
+http://www.nctm.org/uploadedImages/Classroom_Resources/Lesson_Plans/
231
+
232
+---
233
+
234
+---
235
+
236
+-----
237
+

+ 2
- 471
README.md View File

@@ -1,471 +1,2 @@
1
-[English](#markdown-header-repetition-structures-vigenere-cipher) | [Español](#markdown-header-estructuras-de-repeticion-cifrado-vigenere)
2
-
3
-# Estructuras de repetición - Cifrado Vigenere
4
-
5
-![main1.png](images/main1.png)
6
-![main2.png](images/main2.png)
7
-![main3.png](images/main3.png)
8
-
9
-[version 2016.05.04]
10
-
11
-Una de las ventajas de utilizar programas de computadoras es que podemos realizar tareas repetitivas fácilmente. Los ciclos como `for`, `while`, y `do-while` son  estructuras de control que nos permiten repetir un conjunto de instrucciones. A estas estructuras también se les llama *estructuras de repetición*. En la experiencia de laboratorio de hoy utilizarás ciclos `for`  para completar una aplicación de cifrado.
12
-
13
-##Objetivos:
14
-
15
-1. Aplicar estructuras de repetición para cifrar un mensaje.
16
-2. Practicar operaciones aritméticas con caracteres.
17
-
18
-##Pre-Lab:
19
-
20
-Antes de llegar al laboratorio debes:
21
-
22
-1. Haber repasado los conceptos básicos relacionados a estructuras de repetición.
23
-
24
-2. Haber repasado conceptos básicos de la clase `string` de C++,las funciones `length`, `toupper` y `push_back`, `isalpha` y las operaciones aritméticas con caracteres.
25
-
26
-3. Haber visto el video sobre el "Ceasar Cypher" del Khan Academy, colocado en <https://www.youtube.com/watch?v=sMOZf4GN3oc>.
27
-
28
-4. Haber visto el video sobre el "Vigenere Cypher", colocado en <https://www.youtube.com/watch?v=9zASwVoshiM>.
29
-
30
-5. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.
31
-
32
-
33
----
34
-
35
----
36
-
37
-##Criptografía 
38
-
39
-La *criptografía* es un área que estudia la teoría y los métodos utilizados para proteger información de modo que personas que no estén autorizadas no puedan tener acceso a ella. Un *sistema criptográfico* es un sistema en el que la información (*mensaje* entendible por humanos)  es tranformada a un texto cifrado inentendible para las personas no autorizadas a verlo. Las personas autorizadas a ver el mensaje usan un *descifrador* para revertir el texto cifrado al mensaje original.  
40
-
41
-###El Cifrado César (Ceasar Cypher)
42
-
43
-El Cifrado César es una técnica muy simple de cifrado por sustitución. Se dice que el sistema se basa en el sistema utilizado por Julio César, líder militar y político de Roma en años antes de Cristo, para comunicarse con sus generales. La técnica cifra un mensaje de texto sustituyendo cada letra del mensaje por la letra que se encuentra a un número dado de posiciones más adelante en el alfabeto. Esto puede pensarse como un desplazamiento ("shift") del alfabeto. El diagrama de la Figura 1 representa un desplazamiento de 3 espacios. La letra ‘B’ es sustituida por la letra ‘E’.
44
-
45
----
46
-
47
-![figure1.png](images/figure1.png)
48
-
49
-**Figura 1.** Cifrador César con desplazamiento de 3 espacios.
50
-
51
----
52
-
53
-**Ejemplo 1:** Con un desplazamiento de 3 espacios, la palabra "ARROZ" quedaría cifrada como "DUURC". Nota que, con este desplazamiento de 3 espacios, la letra ‘Z’ es sustituida por la letra ‘C’.  Cuando el desplazamiento se pasa de la letra ‘Z’ comenzamos nuevamente en la letra ‘A’. Esto se llama un desplazamiento cíclico. La Figura 2  muestra un desplazamiento cíclico de 8 espacios.
54
-
55
----
56
-
57
-![figure2.png](images/figure2.png)
58
-
59
-**Figura 2.** Disco para cifrador César que muestra un desplazamiento de 8 espacios.
60
-
61
----
62
-
63
-###Utilizando el operador módulo
64
-
65
-La operación de suma modular es esencial para implementar sistemas de cifrado en programación. En la aplicación de cifrado César de arriba podemos pensar que a cada letra del alfabeto (en inglés) le asignamos un número entre 0 y 25 (La `A` es 0, la`B` es 1, …, la `Z` es 25). El cifrador César convierte cada letra al número correspondiente en el intervalo [0, 25] y luego suma el desplazamiento. Para hacer el desplazamiento cíclico, cada vez que nuestro desplazamiento nos dé una letra que corresponda a un número mayor que 25, tomamos el residuo al dividir por 26 y usamos la letra que corresponda a ese residuo. Nota que tomar el residuo al dividir por 26 los resultados estarán entre 0 y 25, que son los valores asociados al alfabeto.
66
-
67
-El residuo al dividir dos números enteros se puede obtener utilizando el operador de *módulo*: `%`.
68
-
69
-Volviendo al Ejemplo 1, en la palabra "ARROZ", a la letra ‘Z’ le corresponde el número 25; al hacer un desplazamiento de 3 espacios, sumamos 3 a 25 y esto nos resulta en 28 que es un número mayor que 25. Si tomamos el residuo al dividir $25 + 3$ por 26, `(25 + 3) % 26`, obtenemos 2, que corresponde a la letra ‘C’. 
70
-
71
-El proceso de arriba funciona si podemos asociar las letras de la ‘A’ a la ‘Z’ con los números del `0` al `25`. Esto se logra utilizando el valor numérico de los caracteres. Como en  el código ASCII el valor de las letras ‘A’ a la ‘Z’ va desde 65 hasta 90,  necesitamos hacer un ajuste en el cómputo de modo que a la `A` se le asigne `0`. Para convertir una letra mayúscula a un número en el intervalo [0, 25] solo tenemos que restar 65 (`’A’ - 65 = 0`, `’Z’ - 65 = 25`). Para cambiar un valor en el intervalo [0, 25] a la letra mayúscula que corresponde en el código ASCII solo tenemos que sumar 65 al número. Por ejemplo, el número 3 corresponde a la letra cuyo código ASCII es $3 + 65 = 68$, la letra ‘D’.
72
-
73
-La Figura 3 muestra el pseudocódigo para una algoritmo para el cifrador César. Cada letra ‘c’ en el mensaje se convierte a un número en el intervalo [0, 25] (restándole ‘A’), luego se hace el desplazamiento de d unidades al número (sumando d módulo 26). Finalmente se convierte el resultado al caracter correspondiente sumando el código ASCII de ‘A’.
74
-
75
----
76
-
77
-```cpp
78
-    Datos de entrada: un "string" de mensaje, la cantidad de desplazamiento d 
79
-    Datos de salida: el mensaje cifrado usando cifrado César 
80
-
81
-    1. cypheredText = ""
82
-    2. para ("for") cada caracter c in en el mensaje:
83
-           c = ascii(c) - ascii('A')  # mueve c del intervalo [A,Z] al [0,25]
84
-           c = ( c + d ) % 26         # desplaza (cíclicamente) c por d unidades
85
-           c = ascii(c) + ascii('A')  # mueve c del intervalo [0,25] al [A,Z]
86
-           cypheredText.append(c) 
87
-    3. devuelve ("return") cypheredText 
88
-```
89
-
90
-**Figura 3.** Pseudo-código para cifrar utilizando un cifrador César.
91
-
92
----
93
-
94
-El cifrado César no es muy seguro ya que puede descifrarse fácilmente con un análisis de frecuencia. Por ejemplo, se sabe que en el idioma inglés la letra ‘e’ es la letra más frecuente en un texto. Si buscamos la letra que más se repite en un texto cifrado con un cifrador César, lo más probable es que esa fue la letra que se sustituyó por la ‘e’; con esto podemos deducir cuál fue desplazamiento utilizado y así descifrar el mensaje.
95
-
96
-
97
-
98
-###El Cifrado Vigenere 
99
-
100
-La debilidad principal del cifrador César es que cada letra en el mensaje se desplaza por el mismo número de posiciones. El cifrado Vigenere es un método de cifrado un poco más fuerte porque el desplazamiento en cada letra no es constante. El cifrado César recibe como datos de entrada el mensaje y un desplazamiento, mientras que el cifrado Vigenere recibe como dato de entrada el mensaje y una **clave** que determina el desplazamiento que se le hará a cada letra del mensaje.
101
-
102
-**Ejemplo 2.** Supongamos por el momento que tanto el mensaje como la clave tienen el mismo largo. Por ejemplo, suponga que el mensaje es "COSAS" y la palabra clave es "MENOR". La letra ‘C’ se parea con la letra ‘M’, la letra ‘O’ se parea con la letra ‘E’, la ‘S’ con la ‘N’, etcétera, como en la figura de abajo. Como la letra ‘A’ corresponde a un desplazamiento de 0 espacios, entonces la letra ‘M’ corresponde a un desplazamiento de 12 espacios, la ‘E’ a un desplazamiento de 4 espacios, etc. Utilizando la palabra clave "MENOR", el cifrador Vigenere hará un desplazamiento de 12 espacios a la letra ‘C’, un desplazamiento de 4 espacios a la letra ‘O’, etc., hasta obtener la palabra cifrada "OSFOJ" como se muestra en la Figura 4. 
103
-
104
----
105
-
106
-| mensaje         | C | O | S | A | S |
107
-|-----------------|---|---|---|---|---|
108
-| clave           | M | E | N | O | R |
109
-| mensaje cifrado | O | S | F | O | J  |
110
-
111
-**Figura 4.** Alineamiento del mensaje con la palabra clave y cifrado.
112
-
113
----
114
-
115
-Podemos visualizar un cifrador Vigenere utilizando una tabla como la de la Figura 5. Nota que lo que se hace es usar un cifrador César con un desplazamiento diferente para cada letra del mensaje.
116
-
117
----
118
-
119
-![figure6.png](images/figure6.png)
120
-
121
-**Figura 5.** Tabla para cifrador Vigenere.
122
-
123
----
124
-
125
-Si la palabra clave es más corta que el mensaje, entonces repetimos la palabra clave tantas veces como haga falta, pareando letras del mensaje con letras de la palabra clave como se hace en la Figura 6.
126
-
127
----
128
-
129
-|     mensaje     | A | L | G | U | N | A | S |   | C | O | S | A | S |
130
-|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|---|
131
-| clave           | M | E | N | O | R | M | E | N | O | R | M | E | N |
132
-| mensaje cifrado | M | P | T | I | E | M | W |   | Q | F | E | E | F |
133
-
134
-
135
-**Figura 6.** Alineamiento del mensaje con la palabra clave y cifrado.
136
-
137
----
138
-
139
-##Funciones que se utilizarán en esta experiencia de laboratorio:
140
-
141
-El programa que estarás modificando en la sesión de hoy utiliza los siguientes métodos de la clase `string`:
142
-
143
-* `length`: Devuelve el largo de un objeto de la clase `string`; esto es, `length` devuelve el número de caracteres que tiene el "string". Se utiliza escribiendo `.length()` después del nombre del objeto.
144
-
145
-* `push_back`: Este método recibe un caracter como argumento y lo añade al final del “string”. Se utiliza escribiendo `.push_back(elCaracter)` después del nombre del “string”. Por ejemplo, para añadir el caracter 'a' a  un objeto de la clase `string` llamado  `cadena`, escribimos `cadena.push_back('a')`.
146
-
147
-También utilizaremos las funciones:
148
-
149
-* `toupper`: Esta función recibe como argumento un caracter y devuelve el caracter en mayúscula. Por ejemplo, para cambiar el caracter 'a' a mayúscula se utiliza `toupper('a')`.
150
-
151
-* `isalpha`: Esta función recibe como argumento un caracter y devuelve un valor distinto de cero (`true`) si el caracter es una letra y cero (`false`) si el caracter no es una letra. Por ejemplo, `isalpha(3)` devuelve "false" pero `isalpha(‘F’)` devuelve `true`.
152
-
153
-
154
----
155
-
156
----
157
-
158
-
159
-!INCLUDE "../../eip-diagnostic/vigenere/es/diag-vigenere-01.html"
160
-
161
-!INCLUDE "../../eip-diagnostic/vigenere/es/diag-vigenere-02.html"
162
-
163
-!INCLUDE "../../eip-diagnostic/vigenere/es/diag-vigenere-03.html"
164
-
165
-
166
----
167
-
168
----
169
-
170
-
171
-##Sesión de laboratorio:
172
-
173
-En esta experiencia de laboratorio completarás una aplicación para cifrar un mensaje de texto utilizando el cifrado Vigenere. Para simplificar el código, la clave y el mensaje deben consistir solo de letras y tu programa debe cambiar todas las letras del mensaje y la clave a mayúsculas.
174
-
175
-###Ejercicio 1: Cifrador con clave y mensaje del mismo largo (solo letras)
176
-
177
-En este ejercicio completarás la aplicación para cifrar un mensaje de texto, 
178
-que solo contiene letras, utilizando una palabra clave que también consiste solo de letras y que tiene el mismo largo del mensaje. 
179
-
180
-####Instrucciones
181
-
182
-1. Descarga la carpeta Repetitions-VigenereCypher de Bitbucket usando un terminal, moviéndote al directorio Documents/eip, y escribiendo el comando git clone http://bitbucket.org/eip-uprrp/repetitions-vigenerecypher.
183
-
184
-2. Carga a Qt Creator el proyecto VigenereCypher haciendo doble "click" en el archivo VigenereCypher.pro que se encuentra en la carpeta Documents/eip/Repetitions-VigenereCypher de tu computadora.
185
-
186
-3. Estarás añadiendo código en el archivo `cypher.cpp`. En este archivo, la función `cypher` recibe un mensaje y una clave del mismo largo y consistentes solo de letras, y devuelve el mensaje cifrado por el cifrador Vigenere. Tu tarea es completar la función de cifrado.
187
- 
188
-    El código debe verificar si el mensaje y la clave consisten solo de letras y tienen el mismo largo; si esto no ocurre, el mensaje cifrado será (literalmente) `"MENSAJE O CLAVE INVALIDO"`. El programa debe implementar el cifrador Vigenere para ir cifrando cada letra del mensaje utilizando la clave.  Solo debes utilizar las funciones mencionadas en la sección anterior. Para simplificar el código tu programa debe cambiar todas las letras del mensaje y la clave a mayúsculas.
189
-
190
-4. Al terminar tu código, ve a la función `main` y descomenta la invocación a la función de prueba unitaria  `test_cypher1`. Esa función realiza varias invocaciones a la función `cypher` para validar si sus resultados son correctos. Tu función `cypher` debe pasar todas las pruebas antes de continuar con la próxima parte de este laboratorio. 
191
-
192
-
193
-###Ejercicio 2: Cifrador con clave y mensaje de largos arbitrarios 
194
-
195
-En este ejercicio modificarás el código de la función `cypher` que creaste para el Ejercicio 1 de modo que la aplicación ahora pueda cifrar cualquier mensaje  utilizando una palabra clave que consista solo de letras pero que tenga cualquier largo. 
196
-
197
-####Instrucciones
198
-
199
-1. Escribe el código de la función `cypher` para que reciba un mensaje y una clave y devuelva el mensaje cifrado por el cifrador Vigenere. En esta ocasión, el mensaje y la clave pueden tener cualquier largo y el mensaje puede tener cualquier caracter (la clave solo puede tener letras). 
200
-
201
-El programa debe implementar el cifrador Vigenere para ir cifrando cada caracter del mensaje utilizando las letras de la clave.  Para simplificar el código, tu programa debe cambiar todas las letras a mayúsculas. Si alguno de los caracteres del mensaje no es una letra, el cifrador no lo cambia, como se muestra en la Figura 7. Si alguno de los caracteres de la clave no es una letra, el mensaje cifrado será "CLAVE INVALIDA". Solo debes utilizar las funciones mencionadas en la sección anterior.
202
-
203
-    ---
204
-
205
-    |     mensaje     | A | L | & | U | N | A | $ |   | C | O | S | A | S |
206
-    |-----------------|---|---|---|---|---|---|---|---|---|---|---|---|---|
207
-    | clave           | M | E | N | O | R | M | E | N | O | R | M | E | N |
208
-    | mensaje cifrado | M | P | & | I | E | M | $ |   | Q | F | E | E | F |
209
-
210
-
211
-    **Figura 7.** Ejemplo de mensaje y clave con largo distinto y símbolos en el mensaje.
212
-
213
-    ---
214
-
215
-2. Al terminar tu código, ve a la función `main`, comenta la invocación a la función de prueba unitaria `test_cypher1` y descomenta la invocación a la función de prueba unitaria `test_cypher2` para que verifiques tu programa.
216
-
217
----
218
-
219
----
220
-
221
-##Entrega
222
-
223
-Utiliza "Entrega" en Moodle para entregar el archivo `cypher.cpp` que contiene la función `cypher` que creaste en el Ejercicio 2. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.
224
-
225
----
226
-
227
----
228
-
229
-##Referencias
230
-
231
-http://www.nctm.org/uploadedImages/Classroom_Resources/Lesson_Plans/
232
-
233
----
234
-
235
----
236
-
237
------
238
-
239
-[English](#markdown-header-repetition-structures-vigenere-cipher) | [Español](#markdown-header-estructuras-de-repeticion-cifrado-vigenere)
240
-
241
-# Repetition Structures - Vigenere Cipher
242
-
243
-![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/DYSdjlN.png)
244
-![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/TEk9bMp.png)
245
-![](http://demo05.cloudimage.io/s/resize/215/i.imgur.com/3PV1IiK.png)
246
-
247
-
248
-
249
-One of the advantages of using computer programs is that we can easily implement repetitive tasks. Structures such as the `for`, `while`, and `do-while` allow us to repeat a block of instructions as many times as needed. In this lab experience you will use `for` loops to complete a simple ciphering application.
250
-
251
-##Objectives:
252
-
253
-1. Apply repetition structures to cipher a plain-text message.
254
-2. Practice character arithmetic.
255
-
256
-
257
-##Pre-Lab:
258
-
259
-Before coming to the lab session you should have:
260
-
261
-1. Reviewed basic concepts related to repetition structures.
262
-
263
-2. Reviewed the string class in C++. In particular, how to create string objects and the `length`, `toupper` and `push_back` methods.  Also review the `isalpha` function and character arithmetic.
264
-
265
-3. Watched Khan Academy’s "Ceasar Cypher" video at https://www.youtube.com/watch?v=sMOZf4GN3oc .
266
-
267
-4. Watched Khan Academy’s "Vigenere Cypher" video at https://www.youtube.com/watch?v=9zASwVoshiM .
268
-
269
-5. Studied the concepts and instructions for the laboratory session.
270
-
271
-
272
-
273
----
274
-
275
----
276
-
277
-##Criptography
278
-
279
-Cryptography is the area of knowledge that studies the theory and methods that are used for protecting information so that non-authorized persons cannot understand it. A *cryptographic system* is a system that transforms a *cleartext message* (a message that is understandable to humans) to a *cyphered* text (text that is unintelligible to unauthorized persons).  Authorized persons can *decypher* the *cyphered* text to obtain the original cleartext.
280
-
281
-###The Ceasar Cypher
282
-
283
-The Caesar Cypher is a substitution encryption technique that is said to have been used by Julius Caesar (100 BC - 44 BC), the Roman political and military leader, to communicate with his generals. To encrypt a message using the Caesar Cipher each letter of the cleartext message is substituted by the letter found a given number of positions ahead in the alphabet. You may think of this as a shift of the letter in the alphabet. Figure 1 illustrates a shift of 3 spaces within the alphabet. For instance, letter ‘B’ would be substituted by letter ‘E’.
284
-
285
----
286
-
287
-![figure1.png](images/figure1.png)
288
-
289
-**Figure 1.** Caesar Cypher with shift of three.
290
-
291
----
292
-
293
-**Example 1.** With a shift of three, the word “ARROZ” is ciphered as “DUURC”. Observe that, with the shift of 3, letter ‘Z’ is ciphered as letter ‘C’. Any shift that takes us beyond letter ‘Z’ starts again at letter ‘A’. This is called cyclic shift. Figure 2 illustrates a circular shift of eight positions.
294
-
295
----
296
-
297
-![figure2.png](images/figure2.png)
298
-
299
-**Figure 2.** A Caesar cipher disk showing a shift of 8 positions.
300
-
301
----
302
-
303
-###Using the modulo operator
304
-
305
-Modular addition is essential for implementing ciphering systems in programming. Let’s say that you map every letter of the (English) alphabet to a number between 0 to 25 (‘A’ is 0, ‘B’ is 1, .., ‘Z’ is 25). To Caesar cipher a letter we convert the letter to its corresponding number in the range [0,25], then add the displacement. We then apply the modulo 26 operation to the total. The letter that corresponds to the result after the modulo is the ciphered letter. The effect of the circular shift is achieved by using the modulo 26 operation because it converts the result of the addition to an integer in the range [0,25]. For instance, if we were to shift the letter ‘Z’ by three positions, this would be performed by adding ( 25 + 3 ) % 26 which equals 2, whose corresponding letter is ‘C’.  
306
-
307
-To convert an uppercase letter to a number in the [0,25] range we can apply our knowledge of the ASCII code. The code for the uppercase letters is in the range [65,90]  (‘A’ is 65, ‘Z’ is 90). Thus, to convert an uppercase case to a number in the range [0,25], a simple subtraction by 65 does the trick (i.e. `’A’ - 65 = 0`, `’Z’ - 65 = 25`).  Observe that to go from the [0,25] range to the ASCII code of its corresponding uppercase character we simply add 65 to the number. For instance, number 3 corresponds to the letter whose ASCII code is $3 + 65 = 68$, i.e. letter ‘D’.  
308
-
309
-Figure 3 shows the pseudocode of an algorithm for the Caesar cipher. Each letter ‘c’ in the cleartext message is converted to a number in the range [0,25]  (by subtracting ‘A’). The displacement d is then added to the number (modulo 26) . Lastly, the result of the modular addition is converted back to its corresponding letter by adding the ASCII code of ‘A’. 
310
-
311
----
312
-
313
-```cpp
314
-    Input: msg: a string of the cleartext message, d: the displacement
315
-    Output: Caesar ciphered message 
316
-
317
-    1. cypheredText = ""
318
-    2. for each character c in msg:
319
-           c = ascii(c) - ascii('A')  # map c from [‘A’,’Z’] to [0,25]
320
-           c = ( c + d ) % 26         # circular shift c by d positions
321
-           c = ascii(c) + ascii('A')  # map c from [0,25] to [‘A’,’Z’]
322
-           cypheredText.append(c) 
323
-    3. return cypheredText 
324
-```
325
-
326
-**Figure 3.** Pseudocode for a Caesar cipher algorithm.
327
-
328
----
329
-
330
-The Caesar cipher is considered a weak encryption mechanism because it can easily be deciphered by using frequency analysis on the ciphered message. For example, we can use the fact that letter ‘e’ is the most frequent letter in most texts. If we find the most frequent letter in a ciphered text it very probably corresponds to the letter that was substituted by ‘e’. With this information we can compute the displacement that was used and decipher the rest of the message.
331
-
332
-PONER PREGUNTAS DIAGNOSTICAS AQUí
333
-
334
-###The Vigenere Cypher 
335
-
336
-A main weakness of the Caesar cipher is that every letter in the cleartext message is shifted by the same number of positions. The Vignere cipher is a somewhat stronger encryption method because the shift used on each letter is not constant. Whereas the Caesar cipher receives as input a cleartext message and a displacement, the Vignere receives the cleartext message and **keyword**. For now, lets assume that the keyword and the cleartext message have the same length. The Vignere cipher uses the keyword to determine the shift that will be applied to each letter of the cleartext message, i.e. the first letter of the keyword determines the shift number for the first letter of the message and so forth. 
337
-
338
-**Example 2.** Suppose that the cleartext is “PET” and the keyword is “BED”. Each letter in the **keyword** determines the shift amount of the corresponding letter in the cleartext: letter ‘A’ specifies a shift of 0, ‘B’ is a shift of 1, and so on.  Thus, the ‘B’ in the keyword “BED” states that we shall shift the first letter of the cleartext by 1, the ‘E’ states that we will shift second the letter by 4 and the ‘D’ states that we will shift the last letter by 3.
339
-
340
----
341
-
342
-| cleartext       | P | E | T |
343
-|-----------------|---|---|---|
344
-| keyword         | B | E | D |
345
-|-----------------|---|---|---|
346
-| ciphered text  | Q | I | X |
347
-
348
-**Figure 4.** Letter ‘P’ in the cleartext is shifted by 1 to ‘Q’  as indicated by the corresponding letter in the keyword (B).   Letter ‘E’ in the cleartext is shifted by 4 to ‘I’  as indicated by the corresponding letter in the keyword (E).   Letter ‘T’ in the cleartext is shifted by 3 to ‘X’  as indicated by the corresponding letter in the keyword (D).  
349
-
350
-
351
----
352
-
353
-Figure 5 shows a table that can be used to determine the Vigenere-ciphered letter, given the cleartext and keyword letter.  Notice that each row contains the entire alphabet shifted by the amount specified by the letter at the beginning of the row.
354
- 
355
----
356
-
357
-![figure6.png](images/figure6.png)
358
-
359
-**Figure 5.** Table for the Vigenere-cipher. The shaded row and column illustrate how to cipher the letter ‘R’ with key letter ‘M’.
360
-
361
----
362
-
363
-If the keyword is shorter than the cleartext, the Vigenere cipher simply repeats the keyword as many times as needed to account for all the letters of the cleartext. Figure 6, illustrates the keyword and cleartext pairing for an example. 
364
-
365
----
366
-
367
-| cleartext       | P | R | O | G | R | A | M |   | T | H | I | S |
368
-|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
369
-| keyword         | S | H | O | R | T | S | H | O | R | T | S | H |
370
-|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
371
-| ciphered text   | H | Y | C | X | K | S | T |   | K | A | A | Z |
372
-
373
-
374
-**Figure 6.** Alignment of a cleartext with a shorter keyword and the resulting cipher.
375
-
376
----
377
-
378
-##Functions that will be used in this laboratory experience: 
379
-
380
-The program that you will be modifying in today’s experience uses the following methods of the `string` class:
381
-
382
-* `length`: Returns the length of a `string` object, i.e. the number of characters in the string (including invisible characters such as the space and end-line).  To invoke the `length` method of string object write `.length()` after the object’s name, e.g. `msg.length()`.
383
-
384
-* `push_back(char c)`: adds the character passed as argument to the end of the string. For example, the instruction `msg.push_back(‘a’)` adds character `a` to the end of an object called `msg`. 
385
-
386
-We will also use the following functions:
387
-
388
-* `char toupper(char c)`: given a character as an argument, this function returns the character in uppercase. For example, `toupper(‘b’)` returns `B`. 
389
-
390
-* `int isalpha(char c)`: Given a character as an argument, this function returns a non-zero value when the character is a letter. Otherwise it returns 0. As you know, C++ interprets non-zero values as `true` and zero as `false`. Thus, for example, the call `isalpha(‘3’)` returns `false`. The call returns `isalpha(‘f’)` returns `true`.
391
-
392
-
393
-
394
----
395
-
396
----
397
-
398
-
399
-!INCLUDE "../../eip-diagnostic/vigenere/en/diag-vigenere-01.html"
400
-
401
-!INCLUDE "../../eip-diagnostic/vigenere/en/diag-vigenere-02.html"
402
-
403
-!INCLUDE "../../eip-diagnostic/vigenere/en/diag-vigenere-03.html"
404
-
405
----
406
-
407
----
408
-
409
-
410
-##Laboratory session:
411
-
412
-You will be completing an application to cipher a message using the Vigenere technique. To simplify coding, the keyword and cleartext must consist exclusively of letters. Furthermore, your program must change both the cleartext and keyword to uppercase before ciphering. 
413
-
414
-###Exercise 1: Keyword and cleartext of the same length
415
-
416
-In this exercise you will implement a function that given a cleartext and keyword of equal length returns the cipher message. 
417
-
418
-####Instructions
419
-
420
-1. Load the Qt project called `VigenereCypher` by double-clicking on the `VigenereCypher.pro` file in the `Documents/eip/Repetitions-VigenereCypher` folder of your computer. Alternatively you may clone the git repository `http://bitbucket.org/eip-uprrp/repetitions-vigenerecypher` to download the `Repetitions-VigenereCypher` folder to your computer.
421
- 
422
-2. You will be writing your code in the `cypher.cpp` file. In this file, the `cypher` function receives a message and a keyword of equal length and that consist exclusively of letters, and returns the Vigenere-ciphered message. Your task is to finish the implementation of the `cypher` function.
423
-     
424
-    Using the methods and functions discussed earlier, your implementation must verify if the message and keyword consist exclusively of letters and are of equal length. If that is not the case, the ciphered message must be (literally) `"MENSAJE O CLAVE INVALIDO"`. Remember that your program must change both the cleartext and keyword to upper-case letters before ciphering.
425
-
426
-3. After you implement the `cypher` function, go to the `main` function and uncomment the line that invokes `test_cypher1`. The `test_cypher1` function is a unit test for the `cypher` function. It calls the `cypher` function with various arguments to verify if it returns correct results. If any of the results is incorrect the program stops and reports the test case that failed. You will not see the application’s graphical user interface until the unit test passes all validations.  Once you see the graphical user interface you may continue onto the next part of this lab experience.
427
-
428
-
429
-###Exercise 2: Keyword and cleartext of arbitrary lengths
430
-
431
-In this exercise you will modify the code for the cypher function from Exercise 1 so that the application can now cipher a message using a keyword of arbitrary length. 
432
-
433
-####Instructions
434
-
435
-1. Modify the implementation of the `cypher` function so that it can cipher a message with a keyword of any (non-zero) length. For this exercise the message may contain any character (including non alphabetical characters). The keyword must consist exclusively of letters. 
436
-
437
-    Whenever the character in the cleartext is not a letter it will not be ciphered, as seen in Figure 7. If any character in the keyword is not a letter, the ciphered message will be (literally) `”CLAVE INVALIDA”`. 
438
-
439
-    ---
440
-
441
-| cleartext       | P | R | @ | G | R | * | M |   | T | 8 | I | S |
442
-|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
443
-| keyword         | S | H | O | R | T | S | H | O | R | T | S | H |
444
-|-----------------|---|---|---|---|---|---|---|---|---|---|---|---|
445
-| ciphered text   | H | Y | @ | X | K | * | T |   | K | 8 | A | Z |
446
-
447
-
448
-    **Figure 7.** Example Vignere cipher of the cleartext `“PR@GR*M T8IS”` using the keyword `SHORT”`. 
449
-
450
-    ---
451
-
452
-
453
-2. After you implement the `cypher` function, modify the `main` function so that the line that invokes `test_cypher2` is uncommented, and the line that invokes `test_cyper1` is commented. Once again, you will not see the app’s graphical user interface until the `test_cypher2` verifications.
454
- 
455
----
456
-
457
----
458
-
459
-##Deliverables
460
-
461
-
462
-Use "Deliverables" in Moodle to upload the `cypher.cpp` file that contains the `cypher` function that you created in Exercise 2.  Remember to use good programming techniques, include the names of the programmers involved, and to document your program.
463
-
464
-
465
----
466
-
467
----
468
-
469
-##References
470
-
471
-http://www.nctm.org/uploadedImages/Classroom_Resources/Lesson_Plans/
1
+## [\[English\]](README-en.md) - for README in English
2
+## [\[Spanish\]](README-es.md) - for README in Spanish