Bez popisu
Jose Ortiz a89ba5ab39 Final initial commit před 9 roky
doc Final initial commit před 9 roky
images Final initial commit před 9 roky
style Final initial commit před 9 roky
PasswordStrength.pro Final initial commit před 9 roky
README.md Final initial commit před 9 roky
images.qrc Final initial commit před 9 roky
main.cpp Final initial commit před 9 roky
mainwindow.cpp Final initial commit před 9 roky
mainwindow.h Final initial commit před 9 roky
mainwindow.ui Final initial commit před 9 roky
psfunctions.cpp Final initial commit před 9 roky
psfunctions.h Final initial commit před 9 roky
readpassword.cpp Final initial commit před 9 roky
style.qrc Final initial commit před 9 roky

README.md

English | Español

Estructuras de decisión - Fortaleza de contraseñas

main1.png main2.png main3.png

En casi todas las instancias en que queremos resolver un problema hay una o más opciones que dependen de si se cumplen o no ciertas condiciones. Los programas de computadoras se construyen para resolver problemas y, por lo tanto, deben tener una estructura que permita tomar decisiones. En C++ las instrucciones de decisión (o condicionales) se estructuran utilizando if, else, else if o switch. Muchas veces el uso de estas estructuras también envuelve el uso de expresiones de relación y operadores lógicos. En la experiencia de laboratorio de hoy practicarás el uso de algunas estructuras de decisión completando el diseño de una aplicación que determina la fortaleza de una contraseña de acceso (“password”).

Objetivos:

  1. Utilizar expresiones relacionales y seleccionar operadores lógicos adecuados para la toma de decisiones.
  2. Aplicar estructuras de decisión.

Pre-Lab:

Antes de llegar al laboratorio debes:

  1. Haber repasado los siguientes conceptos:

operadores lógicos. if, else, else if.

  1. Haber repasado el uso de objetos de la clase string y su método length().

  2. Haber estudiado los conceptos e instrucciones para la sesión de laboratorio.

  3. haber tomado el quiz Pre-Lab que se encuentra en Moodle.



Fortaleza de contraseñas de acceso

Utilizar contraseñas de acceso resistentes es esencial para mantener los datos seguros en los sistemas de información. Una contraseña se considera resistente o fuerte (“strong”) si resulta costo-inefectivo para el “pirata informático” (“hacker”) emplear tiempo tratando de adivinarla usando contraseñas ingenuas o fuerza bruta. Por ejemplo, una contraseña que consiste de una palabra simple del diccionario, sin números, símbolos o letras mayúsculas, es tan fácil de descifrar que hasta “un cavernícola puede hacerlo”.

Como no existe un sistema oficial para medir las contraseñas, utilizaremos fórmulas creadas por el “passwordmeter” para evaluar la fortaleza general de una contraseña dada [1]. Te recomendamos que juegues un poco con la aplicación en http://passwordmeter.com para que entiendas cómo debe comportarse la aplicación que estarás implementando en esta experiencia de laboratorio. La fortaleza de la contraseña se cuantificará otorgando puntos por utilizar “buenas” técnicas de selección de contraseñas (como utilizar mezclas de símbolos y letras) y restando puntos por utilizar “malos” hábitos en las contraseñas (como utilizar solo letras minúsculas o símbolos consecutivos de un mismo tipo).

Las siguientes tablas resumen los valores añadidos y sustraídos para varias características en las contraseñas.

Asignando puntuación a las contraseñas

Sumando puntos


Categoría Puntos Notas
1. Número de caracteres $4\left(len\right)$ $len$ es el largo de la contraseña
2. Letras mayúsculas sumaMayus.png
$n$ es el número de letras mayúsculas
3. Letras minúsculas sumaMin.png
$n$ es el número de letras minúsculas
4. Dígitos sumaDigitos.png
$n$ es el número de dígitos
5. Símbolos $6n$ $n$ es el número de símbolos
6. Dígitos o símbolos en el medio $2n$ $n$ es el número de dígitos y símbolos en el medio
7. Requisitos criterios.png $n$ es el número de criterios que se cumplen

Tabla 1. Criterios positivos para la fortaleza de la contraseña.


Lo que sigue son algunos detalles adicionales y ejemplos de los criterios para sumas.

  1. Número de caracteres: este es el criterio más simple. La puntuación es $4$ veces el largo de la contraseña. Por ejemplo, "ab453" tiene un conteo de $5$ y puntuación de $4 \cdot 5= 20$.

  2. Letras mayúsculas La puntuación es $2 \left(len - n \right)$ si la contraseña consiste de una mezcla de letras mayúsculas Y al menos otro tipo de caracter (minúscula, dígitos, símbolos). De lo contrario, la puntuación es $0$. Por ejemplo,

    a. la puntuación para "ab453" sería $0$ ya que no tiene letras mayúsculas (el conteo también es $0$)

    b. la puntuación para "ALGO" sería $0$ porque solo contiene letras mayúsculas (el conteo es $4$).

    c. la puntuación para "SANC8in" sería $2 \left(7-4\right) = 6$ porque la contraseña es de largo $7$, contiene $4$ letras mayúsculas, y contiene caracteres de otro tipo (el conteo es $4$).

  3. Letras minúsculas La puntuación es $2 \left(len - n\right)$ si la contraseña es una mezcla de letras minúsculas Y al menos otro tipo de caracter (mayúscula, dígitos, símbolos). De lo contrario, la puntuación es $0$. Por ejemplo,

    a. la puntuación para "ab453" sería $2 \left(5-2\right) = 6$ porque la contraseña es de largo $5$, contiene $2$ letras minúsculas, y contiene caracteres de otro tipo. El conteo es $2$.

    b. la puntuación para "ALGO" sería $0$ porque no contiene letras minúsculas. El conteo es $0$.

    c. la puntuación para "sancochin" sería $0$ porque contiene solo letras minúsculas. El conteo es $9$.

  4. Dígitos La puntuación es $4n$ si la contraseña consiste de una mezcla de dígitos Y al menos otro tipo de caracter (minúscula, mayúscula, símbolos). De otro modo la puntuación es $0$. Por ejemplo,

a. la puntuación para "ab453" sería $4 \cdot3 = 12$ porque la contraseña contiene $3$ dígitos y contiene caracteres de otro tipo.

b. la puntuación para "ALGO" sería $0$ porque no tiene dígitos.

c. la puntuación para 801145555 sería $0$ porque contiene solo dígitos.

  1. Símbolos La puntuación es $6n$ si la contraseña contiene $n$ símbolos. De otro modo la puntuación es $0$. Por ejemplo,

a. la puntuación para "ab453" sería $0$ porque no contiene símbolos.

b. la puntuación para "ALGO!!" sería $6 \cdot 2$ porque contiene $2$ símbolos y contiene otros tipos de caracteres.

c. la puntuación para ”---><&&” sería $6 \cdot 7 = 42$ porque contiene $7$ símbolos. Nota que en el caso de símbolos, se otorga puntuación incluso cuando no hay otro tipo de caracteres.

  1. Dígitos o símbolos en el medio La puntuación es $2n$ si la contraseña contiene símbolos o dígitos que no están en la primera o última posición. Por ejemplo,

a. la puntuación para "ab453" sería $2 \cdot2 = 4$ porque contiene dos dígitos que no están en la primera o última posición, estos son 4 y 5.

b. la puntuación para "ALGO!" sería $0$ porque no contiene dígitos ni símbolos en el medio, el único símbolo está al final.

c. la puntuación para S&c8i7o! sería $2 \cdot 3 = 6$ porque contiene $3$ símbolos o dígitos en el medio, estos son &, 8, y7`.

  1. Requisitos: Se otorga $2n$ solo si el criterio del largo Y 3 o 4 de los otros criterios se cumplen, donde $n$ es el número de criterios que se cumplen. Los criterios son:

    a. La contraseña debe tener 8 o más caracteres de largo.

    b. Contener: - Letras mayúsculas

    - Letras minúsculas
    - Números
    - Símbolos
    

    Cada uno de los listados en la parte b. cuenta como un criterio individual. Por ejemplo,

    a. la puntuación para "ab453" sería $0$ porque el criterio del largo no se cumple.

    b. la puntuación para "abABCDEF" sería $0$ debido a que, a pesar de que se cumple el criterio del largo, solo 2 de los 4 otros criterios se cumplen (mayúsculas y minúsculas).

    c. la puntuación para "abAB99!!" sería $2 \cdot 5 = 10$ debido a que cumple la condición del largo y también los otros 4 criterios.

Restando puntos


Categoría Puntos Notas
1. Solo letras resLetras.png $len$ es el largo de la contraseña
2. Solo dígitos resDigitos.png $len$ es el largo de la contraseña
3. Letras mayúsculas consecutivas $-2n$ $n$ es el número de letras mayúsculas que siguen a otra letra mayúscula
4. Letras minúsculas consecutivas $-2n$ $n$ es el número de letras minúsculas que siguen a otra letra minúscula
5. Dígitos consecutivos $-2n$ $n$ es el número de dígitos que siguen a otro dígito

Tabla 2. Criterios negativos para la fortaleza de la contraseña.


Lo que sigue son algunos detalles adicionales y ejemplos de los criterios para restas.

  1. Letras solamente: La puntuación es $-len$ para una contraseña que consista solo de letras, de otro modo obtiene $0$. Por ejemplo,

    a. la puntuación para "ab453" sería $0$ ya que contiene letras y números

    b. la puntuación para "Barrunto" sería $-8$ ya que consiste solo de letras y su largo es $8$.

  2. Dígitos solamente: La puntuación es $-len$ para una contraseña que consista solo de dígitos, de otro modo obtiene $0$. Por ejemplo,

    a. la puntuación para "ab453" sería $0$ ya que contiene solo letras y números

    b. la puntuación para ”987987987” sería $-9$ ya que consiste solo de dígitos y su largo es $9$.

  3. Letras mayúsculas consecutivas: La puntuación es $-2n$ donde $n$ es el número de letras mayúsculas que siguen a otra letra mayúscula. Por ejemplo,

    a. la puntuación para "DB453" sería $-2 \cdot 1 = -2$ ya que solo contiene una letra mayúscula (B) que sigue a otra letra mayúscula.

    b. la puntuación para "TNS1PBMA" sería $-2 \cdot 5 = -10$ ya que contiene 5 letras mayúsculas (N, S, B, M, A) que siguen a otra letra mayúscula.

  4. Letras minúsculas consecutivas: Igual que el criterio #3 pero para letras minúsculas.

  5. Dígitos consecutivos: Igual que el criterio #3 pero para dígitos.



Sesión de laboratorio:

En esta experiencia de laboratorio practicarás el uso de expresiones matemáticas y estructuras condicionales para computar la puntuación de resistencia o fortaleza de una contraseña combinando las puntuaciones de los criterios individuales.

Tu tarea es completar el diseño de una aplicación para medir la fortaleza de las contraseñas de acceso (“password strength”). Al final obtendrás un programa que será una versión simplificada de la aplicación en http://www.passwordmeter.com/. Como no existe un sistema oficial para medir las contraseñas, se utilizarán las fórmulas creadas por el “passwordmeter” para evaluar la fortaleza general de una contraseña dada. La aplicación permitirá al usuario entrar una contraseña y calculará su fortaleza utilizando una serie de reglas.

La fortaleza de la contraseña se cuantificará otorgando puntos por utilizar “buenas” técnicas de selección de contraseñas (como combinar símbolos y letras) y restando puntos por utilizar “malos” hábitos (como utilizar solo letras minúsculas o caracteres consecutivos de un mismo tipo). Tu programa analizará la contraseña dada por el usuario y usará los criterios en las tablas presentadas arriba para computar una puntuación para la fortaleza de la contraseña.

Una vez completada la aplicación, esta mostrará una ventana en donde, según se vayan entrando los caracteres de la contraseña, se desglosará la puntuación parcial obtenida. Esta interface gráfica para el usuario le ofrecerá una manera de mejorar su contraseña y corregir los malos hábitos típicos al formular contraseñas débiles.

Ejercicio 1: Familiarizarte con las funciones pre-definidas

El primer paso en esta experiencia de laboratorio es familiarizarte con las funciones pre-definidas en el código. Invocarás estas funciones en el código que crearás para computar la puntuación de varios de los criterios para fortaleza de contraseñas.

Instrucciones

  1. Carga a Qt el proyecto PassworStrength haciendo doble “click” en el archivo PasswordStrength.pro en el directorio Documents/eip/Conditionals-PasswordStrength de tu computadora. También puedes ir a http://bitbucket.org/eip-uprrp/conditionals-passwordstrength para descargar la carpeta Conditionals-PasswordStrength a tu computadora.

  2. Configura el proyecto. El proyecto consiste de varios archivos. Solo escribirás código en el archivo readpassword.cpp. No debes cambiar nada en los demás archivos. Sin embargo, debes familiarizarte con las funciones que ya están definidas en ellos, ya que usarás algunas de ellas para crear tu código.

    • psfunctions.cpp : contiene las implementaciones de algunas de las funciones que tu programa va a invocar para calcular la puntuación de la fortaleza total de la contraseña. No tienes que cambiar nada del código en este archivo ni en el archivo psfunctions.h. Simplemente invocarás desde la función readPass en el archivo readpassword.cpp las funciones contenidas en ellos, según sea necesario. Hay funciones que no necesitarás invocar. Nota que el nombre de las funciones te dice lo que la función hace.
    • psfunctions.h : contiene los prototipos de las funciones definidas en psfunctions.cpp.

Ejercicio 2: Conocer las funciones para actualizar la interface gráfica de usuarios.

En el ejercicio de laboratorio crearás el código para calcular la puntuación asociada a cada uno de los criterios de las tablas de sumas y deducciones mostradas arriba. Estas puntuaciones deben ser actualizadas en la interface gráfica de usuarios que se muestra en la Figura 1.


interfaceGrafica.png

Figura 1. Interface gráfica de usuarios del proyecto Fortaleza de contraseñas


Hay funciones pre-definidas que actualizan la interface gráfica. Para que la aplicación funcione como esperada, cada vez que tu código compute la puntuación que se adjudica para un criterio debes invocar la función que actualiza ese criterio en el interface gráfico. Las funciones para actualizar los criterios tienen la siguiente sintaxis:

  void setCRITERIO(int count, int score) ;

donde CRITERIO debe reemplazarse por el criterio evaluado. Observa que la función requiere dos argumentos: el conteo que es la cantidad de caracteres que cumple con el criterio y la puntuación que es el cálculo que tu implementarás siguiendo las tablas de arriba. Por ejemplo,

count = pass.length() ;
score = 4 * count ;
setNumberOfCharacters(count, score);
totalScore += score ;

En el código de arriba count contiene el número de caracteres en la contraseña, score contiene el cómputo de la puntuación del criterio de número de caracteres y setNumberOfCharacters(count, score); invoca la función para que se actualice la información correspondiente al criterio “Number of characters” en la interface gráfica.

Las funciones para actualizar la interface gráfica son:

    // Para actualizar el largo de  la contraseña.
    void setNumberOfCharacters(int count, int score) ;  

    // Para las sumas

    // Para actualizar los caracteres en mayúscula.
    void setUpperCharacters(int count, int score) ;

    // Para actualizar los caracteres en minúscula.
    void setLowerCharacters(int count, int score) ;

    // Para actualizar los caracteres que son dígitos.
    void setDigits(int count, int score) ;

    // Para actualizar los caracteres que son símbolos.
    void setSymbols(int count, int score) ;

    // Para actualizar digitos o simbolos en el medio
    void setMiddleDigitsOrSymbols(int count, int score) ;

    // Para actualizar el criterio de  los requisitos
    void setRequirements(int count, int score) ;

    // Para las restas

    // Para actualizar el criterio de letras solamente.
    void setLettersOnly(int count, int score) ;

    // Para actualizar el criterio de dígitos solamente.
    void setDigitsOnly(int count, int score) ;

    // Para actualizar el criterio de mayúsculas consecutivas.
    void setConsecutiveUpper(int count, int score) ;

    // Para actualizar el criterio de minúsculas consecutivas.
    void setConsecutiveLower(int count, int score) ;

    // Para actualizar el criterio de dígitos consecutivos.
    void setConsecutiveDigits(int count, int score) ; 

Ejercicio 3: Calcular la puntuación de los criterios y la puntuación total de la contraseña

El código que te proveemos contiene las funciones que computan el conteo para la mayoría de los criterios y cuyos nombres reflejan lo que hace y devuelve la función. Por ejemplo, countUppercase, devuelve el número de caracteres que son letras mayúsculas. Aquí hay una lista y descripción de las funciones.

Tu tarea es utilizar expresiones matemáticas y estructuras condicionales para las puntuaciones de los criterios individuales y combinarlas para computar la puntuación total de fortaleza de una contraseña.

Ejemplo 1:


ventanaCaba77o.png

Figura 2. Ventana con el informe de la contraseña caba77o


Ejemplo 2:


Figura 3. Ventana con el informe de la contraseña S1nf@nia!


En el Ejemplo 2, el conteo de los requisitos es 5 porque "S1nf@nia!" cumple con el criterio de largo y también contiene mayúsculas, minúsculas, números y símbolos. Por lo tanto, la puntuación del número de requisitos es $2 \cdot 5 =10$.

En el código del proyecto vas a encontrar ejemplos de cómo calcular los primeros dos criterios positivos: el número de caracteres en la contraseña y el número de letras mayúsculas. Puedes compilar y ejecutar el ejemplo para que veas la interfase funcionando con esos dos criterios. Parte de tu tarea es añadir el código para computar las puntuaciones de los demás criterios. Recuerda que debes ir acumulando el resultado de la puntuación total y hacer invocaciones para actualizar la interface gráfica.

Ejercicio 4: Determinar y desplegar la fortaleza de la contraseña

En la parte superior de la interface gráfica se ingresa la contraseña.  El usuario ingresará la contraseña en la parte superior de la interface gráfica. Debajo aparece un *informe* que contiene los distintos criterios, el conteo para cada criterio, y la puntuación individual para los criterios. Este informe se va actualizando según el usuario va ingresando los caracteres de la contraseña.  La puntuación total será la suma de todas los puntos (sumas y restas) de los criterios individuales.

Basado en la puntuación total, el programa debe clasificar la fortaleza de la contraseña como sigue:
Puntación total Fortaleza
[0,20) Bien débil
[20,40) Débil
[40,60) Buena
[60,80) Fuerte
[80,100] Bien fuerte

El código provisto ya invoca la función strengthDisplay con la fortaleza calculada y la puntuación final para actualizar la clasificación y la barra que indica la fortaleza en la interface gráfica.



Entregas

Utiliza “Entrega” en Moodle para entregar el archivo readpassword.cpp que contiene el código con el cómputo de las puntuaciones de los criterios individuales, la puntuación final, las invocaciones para actualizar la interface gráfica, la clasificación de la fortaleza y se despliegue. Recuerda utilizar buenas prácticas de programación, incluir el nombre de los programadores y documentar tu programa.



Referencias

[1] Passwordmeter, http://www.passwordmeter.com/




English | Español

Decision Structures - Password Strength

main1.png main2.png main3.png

Commonly, when solving a problem, there are one or more steps that depend on whether certain conditions are met. Computer programs are built to solve problems, so they should have a structure that allows them to make decisions. In C++ the decision instructions (or conditionals) are structured using if, else, else if or switch. In today’s laboratory experience you will practice the use of some of these structures by completing the design of an application that determines the strength of a password.

Objectives:

  1. Use relational expressions and select adequate logical operators to make decisions.
  2. Apply decision structures.

Pre-Lab:

Before you get to the laboratory you should have:

  1. Reviewed the following concepts:

    a. Logical operators b. if, else, else if.

  2. Reviewed the use of objects of the string class and its length() method.

  3. Studied the concepts and instructions for this laboratory session.

  4. Taken the Pre-Lab quiz 6].



Password strength

Using strong passwords is essential to securing information. A password is considered strong if it is not cost-effective for a hacker to try and guess it using different methods or brute force. For example, a password that consists of a simple dictionary word, without digits, symbols or uppercase letters, is so easy to decipher that even a caveman could do it.

Since an official system to measure password strength doesn’t exist, we will use formulas created by the passwordmeter to evaluate the general strength of a given password [1]. We recommend that you play around a bit with the application in http://passwordmeter.com so that you understand how the application you will be implementing should behave. The strength of the password will be quantified by adding points for using good techniques of password selection (like using symbols and letters), and subtracting points for using bad habits (like only using lowercase letters or consecutive symbols of the same type).

The following tables review the added and subtracted values for various criteria in passwords:

Assigning points to a password

Adding Points:


Category Points Notes
1. Number of characters $4\left(len\right)$ $len$ is the length of the password
2. Uppercase letters addUpper.png
$n$ is the number of uppercase letters
3. Lowercase letters addLower.png
$n$ is the number of lowercase letters
4. Digits addDigits.png
$n$ is the number of digits
5. Symbols $6n$ $n$ is the number of symbols
6. Digits or symbols in the middle $2n$ $n$ is the number of digits or symbols in the middle
7. Requisites criteria.png $n$ is the number of criteria that are met

Table 1. Positive criteria for password strength.


What follows are some additional details and examples for the criteria of adding points.

  1. Number of characters: this is the simplestcriteria. The score will be $4$ times the length of the password. For example, "ab453" has a count of $5$ and a score of $4 \cdot 5 = 20$.

  2. Uppercase letters: the score is $2 \left(len - n \right)$ if the password consists of a mix of uppercase letters AND at least another type of character (lowercase, digits, symbols). If not, the score is $0$. For example,

a. the score for "ab453" would be $0$ since it doesn’t have uppercase letters (the count is also $0$).

b. the score for "ALGO" would be $0$ since it only has uppercase letters (the count is $4$).

c. the score for "SANC8in" would be $2 \left(7-4\right) = 6$ since the password has a length of $7$, has $4$ uppercase letters, and contains characters of another type (the count is $4$).

  1. Lowercase letters: the score is $2 \left(len - n\right)$ if the password is a mix of lowercase letters AND at least another type of character (uppercase, digits, symbols). If not, the score is $0$. For example,

a. the score for "ab453" would be $2 \left(5-2\right) = 6$ because the password has a length of $5$, contains $2$ lowercase letters, and contains characters of another type. The count is $2$.

b. the score for "ALGO" would be $0$ because it doesn’t have lowercase letters. The count is $0$.

c. the score for "sancochin" would be $0$ because it contains only lowercase letters. The count is $9$.

  1. Digits: the score is $4n$ if the password consists of a mix of digits AND at least another type of character (lowercase, uppercase, symbols). If not, the score is $0$. For example,

a. the score for "ab453" would be $4 \cdot 3 = 12$ because the password contains $3$ digits and contains characters of another type.

b. the score for "ALGO" would be $0$ because it doesn’t have digits.

c. the score for 801145555 would be $0$ because it contains only digits.

  1. Symbols The score is $6n$ if the password contains $n$ symbols. Otherwise, the score is $0$. For example,

a. the score for "ab453" would be $0$ because it does not contain symbols.

b. the score for "ALGO!!" would be $6 \cdot 2$ because it contains $2$ symbols and contains other types of characters.

c. the score for ”---><&&” would be $6 \cdot 7 = 42$ because it contains $7$ symbols. Note that in the case of symbols, points are given even when there aren’t other types of characters.

  1. Digits or symbols in the middle The score is $2n$ if the password contains symbols or digits that are not in the first or last position. For example,

a. the score for "ab453" would be $2 \cdot2 = 4$ because it contains 2 digits that are not in the first or last position, these are 4 and 5.

b. the score for "ALGO!" would be $0$ because it does not contain digits or symbols in the middle, the only symbol is in the last position.

c. the score for S&c8i7o! would be $2 \cdot 3 = 6$ because it contains $3$ symbols or digits in the middle, these are &, 8, and7`.

  1. Requisites: The score is $2n$ only if the length criteria AND 3 or 4 of the other criteria are met, where $n$ is the number of criteria that are met. The criteria are:

a. The password must contain 8 or more characters of length.

b. Contain:

- Uppercase letters
- Lowercase letters
- Numbers
- Symbols

Each of the items listed in part b. count as one individual criteria. For example,

a. the score for "ab453" would be $0$ because the criteria for length is not met.

b. the score for "abABCDEF" would be $0$ because, despite the fact that the length criteria is met, only 2 of the 4 other criteria are met (uppercase and lowercase letters).

c. the score for "abAB99!!" would be $2 \cdot 5 = 10$ because the length criteria and the other 4 criteria are met.

Subtracting points


Category Points Notes
1. Only letters subsLetters.png $len$ is the length of the password
2. Only digits subsDigits.png $len$ is the length of the password
3. Consecutive uppercase letters $-2n$ $n$ is the number of uppercase letters that follow another uppercase letter
4. Consecutive lowercase letters $-2n$ $n$ is the number of lowercase letters that follow another lowercase letter
5. Consecutive digits $-2n$ $n$ is the number of digits that follow another digit

Table 2. Negative criteria for password strength.


The following are additional details and examples of the criteria for subtracting points.

  1. Only letters: The score is $-len$ for a password that consists of letters only, otherwise it is $0$. For example,

a. the score for "ab453" would be $0$ since it contains letters and numbers.

b. the score for "Barrunto" would be $-8$ since it only contains letters and its length is $8$.

  1. Only digits: The score is $-len$ for a password that consists of digits only, otherwise it is $0$. For example,

a. the score for "ab453" would be $0$ since it contains only letters and numbers.

b. the score for ”987987987” would be $-9$ since it contains only digits and its length is $9$.

  1. Consecutive uppercase letters: The score is $-2n$ where $n$ is the number of uppercase letters that follow another uppercase letter. For example,

a. the score for "DB453" would be $-2 \cdot 1 = -2$ since it only contains one uppercase letter (B) that follows another uppercase letter.

b. the score for "TNS1PBMA" would be $-2 \cdot 5 = -10$ since it contains 5 uppercase letters (N, S, B, M, A) that follow another uppercase letter.

  1. Consecutive lowercase letters: The same as for criteria #3 but for lowercase letters.

  2. Consecutive digits: The same as for criteria #3 but for digits.



Laboratory session:

In this laboratory session you will practice the use of mathematical expressions and conditional structures to compute the score for the strength of a password combining the points for the individual criteria.

Your task is to complete the design of the application to measure the strength of a password. When done, you will obtain a simplified version of the application in http://www.passwordmeter.com/. Since there isn’t an official system to measure passwords, the formulas created by “passwordmeter” will be used to evaluate the general strength of a given password. The application will allow users to enter a password and calculate its strength using a series of rules.

The strength of the password will be quantified by adding points for using good password selection techniques (like combining symbols and letters) and subtracting points for using bad habits (like using only uppercase letters or consecutive symbols of the same type). Your program will analyze the password given by the user and use the criteria in the tables presented above to compute a score for the password’s strength.

Once the application is complete, it will show a window where, as the password characters are entered, the partial score will be displayed. This graphical interface will offer the user a way to improve his password and correct typical weak password habits.

Exercise 1: Familiarize yourself with the pre-defined functions

The first step in this laboratory experience is to familiarize yourself with the functions that are pre-defined in the code. You will call these functions as part of your own code to compute the score of the various password strength criteria.

Instructions

  1. Load the project PassworStrength onto Qt by double clicking the file PasswordStrength.pro in the directory Documents/eip/Conditionals-PasswordStrength of your computer. You can also go to http://bitbucket.org/eip-uprrp/conditionals-passwordstrength to download the folder Conditionals-PasswordStrength to your computer.

  2. Configure the project. The project consists of several files. You will only write code in the file readpassword.cpp. You should not make any changes in the other files. Despite this, you should familiarize yourself with the functions that are already defined in them, since you will be using some of them to create your code.

    • psfunctions.cpp : contains the implementations of some of the functions that will invoke in your program to calculate the score for the password’s strength. You do not have to change anything in this file or in the file psfunctions.h. Simply invoke the functions as necessary from the readPass function in the readpassword.cpp file. Note that the function names tell you what the functions do.

    • psfunctions.h : contains the prototypes for the functions defined in psfunctions.cpp.

Exercise 2: Understand the functions to update the user’s graphical interface.

In the laboratory exercise you will write code to calculate the score associated to each one of the criteria in the tables for adding and subtracting points shown above. These scores should be updated in the user’s graphical interface that is shown in Figure 1.


interfaceGrafica.png

Figure 1. User graphical interface for Password strength project.


There are predefined functions that update the graphical interface. For the application to work properly, each time that your code computes the score that is given for each criteria you should invoke the function to update that particular criteria in the graphical interface. The functions to update the criteria have the following syntax:

  void setCRITERIA(int count, int score) ;

where CRITERIA should be replaced by the criteria that is being evaluated. Observe that the function requires two arguments: the count that is the amount of characters that meet the criteria and the score that is the calculation that you will implement following the tables presented above. For example,

  count = pass.length() ;
  score = 4 * count ;
  setNumberOfCharacters(count, score);
  totalScore += score ;

In the above code count contains the number of characters in the password, score contains the computation for the score of the criteria for the number of characters, and setNumberOfCharacters(count, score); invokes the function to update the corresponding information for the criteria “Number of characters” in the graphical interface.

The functions to update the graphical interface are:

```
// To update the password's length.
void setNumberOfCharacters(int count, int score) ;  

// For adding points

// To update the uppercase characters.
void setUpperCharacters(int count, int score) ;

// To update the lowercase characters.
void setLowerCharacters(int count, int score) ;

// To update the characters that are digits.
void setDigits(int count, int score) ;

// To update the characters that are symbols.
void setSymbols(int count, int score) ;

// To update the digits or symbols in the middle
void setMiddleDigitsOrSymbols(int count, int score) ;

// To update the criterium of the requisites
void setRequirements(int count, int score) ;

// For subtracting points

// To update the criterium of only letters.
void setLettersOnly(int count, int score) ;

// To update the criterium of only digits.
void setDigitsOnly(int count, int score) ;

// To update the criterium of consecutive uppercase letters.
void setConsecutiveUpper(int count, int score) ;

// To update the criterium of consecutive lowercase letters.
void setConsecutiveLower(int count, int score) ;

// To update the criterium of consecutive digits.
void setConsecutiveDigits(int count, int score) ; 
```

Exercise 3: Compute the score for the criteria and the total score for the password

The code that we’re providing you contains the functions that compute the count for the majority of the criteria and whose names reflect what they do and what the function returns. For example, countUppercase, return the number of characters that are uppercase letters.

Here is a list and description of the functions.

Your task is to use mathematical expressions and decision structures for the individual criteria scores and combine them to compute the total score for the password’s strength.

Example 1:


ventanaCaba77o.png

Figure 2. Window with the report for the password caba77o.


Example 2:


Figure 3. Window with the report for the password S1nf@nia!.


In Example 2, the number of requisites is 5 because "S1nf@nia!" meets the criteria for length and also contains uppercase letters, lowercase letters, numbers and symbols. Therefore, the score for the number of requisites is $2 \cdot 5 =10$.

In the project’s code you will find examples of how to calculate the first two positive criteria: the number of characters in the password and the numbers of uppercase letters. You can compile and execute the example so you can see the working interface with these two criteria. Part of your task is to add the code to compute the score for the remaining criteria. Remember that you should accumulate the total score and invoke the functions to update the graphical interface.

Exercise 4: Determine and display the password’s strength

The password is entered in the top section of the graphical interface. The user will input the password in the top section of the graphical interface. Below appears the report that contains the different criteria, the count for each criteria, and the individual score for the criteria. This report will be updated as the user inputs the password’s characters. The total score will be the sum of all of the points (addition and subtraction) of the individual criteria.

Based on the total score, the program will classify the password’s strength as follows:

Total score Strength
[0,20) Very weak
[20,40) Weak
[40,60) Good
[60,80) Strong
[80,100] Very strong

The provided code already invokes the strengthDisplay function with the strength calculated and the total score to update the classification, and the bar that indicates the password’s strength in the graphical interface.



Deliverables

Use “Deliverables” in Moodle to upload the readpassword.cpp file that contains the code with the computation for the score of the individual criteria, the final score, the function calls to update the graphical interface, the password’s classification and the display functions. Remember to use good programming techniques, include the name of the programmers involved, and to document your program.



References

[1] Passwordmeter, http://www.passwordmeter.com/