Simple Random Password Generator


/ Published in: C
Save to your folder(s)



Copy this code and paste it in your HTML
  1. //
  2. // Author : Keiran "Affix" Smith <Affix_at_Affix_dot_me>
  3. // Website: http://keiran-smith.net
  4. // Description :
  5. // Generate a Simple Random Password
  6. //
  7. // This program is free software; you can redistribute it and/or modify
  8. // it under the terms of the GNU General Public License as published by
  9. // the Free Software Foundation; version 2 of the License.
  10. //
  11. // This program is distributed in the hope that it will be useful,
  12. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. // GNU General Public License for more details.
  15.  
  16. #include <stdio.h>
  17. #include <stdlib.h>
  18. #ifdef DEVRANDOM
  19. #include <fcntl.h>
  20. #endif
  21.  
  22.  
  23. int max;
  24. char *charset = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
  25.  
  26. void seed()
  27. {
  28. int i, j;
  29. #ifdef DEVRANDOM
  30. int fd;
  31. #endif
  32. i = getpid();
  33. j = time(NULL) ^ (i + (i << 15)); /* Thank you the Camel Book */
  34. #ifdef DEVRANDOM
  35. fd = open(DEVRANDOM, O_RDONLY, 0);
  36. if (fd == -1) {
  37. perror(DEVRANDOM);
  38. exit(1);
  39. }
  40. read(fd, &i, sizeof(charset));
  41. j = j ^ i;
  42. close(fd);
  43. #endif
  44. srand(j);
  45. }
  46.  
  47. char *shuffle(char *v, size_t n)
  48. {
  49. int i, j;
  50. char *s;
  51.  
  52. for (i=0; i < n; i++) {
  53. do
  54. j = rand() % n;
  55. while (j < i);
  56. s = v;
  57. v = v;
  58. v = s;
  59. }
  60.  
  61. return v;
  62. }
  63.  
  64.  
  65.  
  66. int main(int argc, char *argv[])
  67. {
  68.  
  69. if(argv[1])
  70. max = atoi(argv[1]);
  71. else
  72. max = 8;
  73. printf("Maximum Password Length is : %d\n\n", max);
  74.  
  75. seed();
  76.  
  77. int i = 0;
  78. while(i < max)
  79. {
  80. charset = shuffle(charset, sizeof(charset));
  81. int rnd_num = rand() % sizeof(charset);
  82. char pchar = charset[rnd_num];
  83. printf("%c", pchar);
  84. i++;
  85. }
  86. printf("\n\n");
  87. return 0;
  88. }
  89.  
  90.  

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.