fork(2) download
  1. #include <string.h>
  2. #include <stdlib.h>
  3. #include <stdio.h>
  4. #include <time.h>
  5.  
  6. int main()
  7. {
  8. int longitud = 10;
  9.  
  10. int mayusculas = 1;
  11. int minusculas = 1;
  12. int digitos = 1;
  13. int especiales = 1;
  14.  
  15. #define CARACTERES_ESPECIALES "!@#$^&*?"
  16.  
  17. int tam_alfabeto = 0;
  18. if (mayusculas) tam_alfabeto += 'Z' - 'A' + 1;
  19. if (minusculas) tam_alfabeto += 'z' - 'a' + 1;
  20. if (digitos) tam_alfabeto += 10;
  21. if (especiales) tam_alfabeto += strlen(CARACTERES_ESPECIALES);
  22.  
  23. char * alfabeto = (char*)malloc((tam_alfabeto + 1) * sizeof(char));
  24. int index = 0;
  25.  
  26. for (char c='A'; c<='Z' && mayusculas; c++)
  27. alfabeto[index++] = c;
  28.  
  29. for (char c='a'; c<='z' && minusculas; c++)
  30. alfabeto[index++] = c;
  31.  
  32. for (char c='0'; c<='9' && digitos; c++)
  33. alfabeto[index++] = c;
  34.  
  35. for (int i=0; i<(int)strlen(CARACTERES_ESPECIALES); i++)
  36. alfabeto[index++] = CARACTERES_ESPECIALES[i];
  37.  
  38. alfabeto[index] = 0; // Solo para fines de depuraciĆ³n
  39.  
  40. printf("Alfabeto: %s\n", alfabeto);
  41.  
  42. srand(time(NULL));
  43.  
  44. int clave_ok;
  45. char*clave = (char*)malloc((longitud+1)*sizeof(char));
  46. clave[longitud] = 0; // Finalizamos la cadena
  47.  
  48. do
  49. {
  50. for( int i=0; i<longitud; i++)
  51. {
  52. clave[i] = alfabeto[rand()%tam_alfabeto];
  53. }
  54.  
  55. int hay_mayusculas = 0;
  56. int hay_minusculas = 0;
  57. int hay_digitos = 0;
  58. int hay_especiales = 0;
  59.  
  60. for (int i=0; i<longitud; i++)
  61. {
  62. hay_mayusculas |= (clave[i] >= 'A' && clave[i] <= 'Z');
  63. hay_minusculas |= (clave[i] >= 'a' && clave[i] <= 'z');
  64. hay_digitos |= (clave[i] >= '0' && clave[i] <= '9');
  65. hay_especiales |= (strchr(CARACTERES_ESPECIALES, clave[i]) != NULL);
  66. }
  67.  
  68. clave_ok = 1;
  69. if (mayusculas) clave_ok &= hay_mayusculas;
  70. if (minusculas) clave_ok &= hay_minusculas;
  71. if (digitos) clave_ok &= hay_digitos;
  72. if (especiales) clave_ok &= hay_especiales;
  73.  
  74. if (!clave_ok)
  75. {
  76. printf("Clave no valida: %s\n", clave);
  77. }
  78. } while (!clave_ok);
  79.  
  80. printf("Clave generada: %s\n", clave);
  81. free(clave);
  82. }
Success #stdin #stdout 0s 5660KB
stdin
Standard input is empty
stdout
Alfabeto: ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789!@#$^&*?
Clave no valida: xCJGrlRi!D
Clave no valida: Bkv0hZfNfH
Clave generada: zQmQaP*EZ1