Created
August 31, 2023 05:42
-
-
Save gabrieleromanato/d4cbc14eee4f19c59b40ac73814bc4a8 to your computer and use it in GitHub Desktop.
C: random password generator
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <time.h> | |
#include <stdbool.h> | |
// Function to generate a random password | |
void generateRandomPassword(int length, bool includeSymbols) { | |
const char charset[] = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789!@#$%^&*()_+{}[]<>,.?/"; // Characters to choose from | |
int charsetSize = sizeof(charset) - 1; | |
// Seed the random number generator | |
srand(time(NULL)); | |
printf("Generated password: "); | |
for (int i = 0; i < length; i++) { | |
if(includeSymbols) { | |
char randomChar = charset[rand() % charsetSize]; | |
printf("%c", randomChar); | |
} else { | |
char randomChar = charset[rand() % (charsetSize - 32)]; | |
printf("%c", randomChar); | |
} | |
} | |
printf("\n"); | |
} | |
int main() { | |
int passwordLength; | |
bool includeSymbols; | |
printf("Enter the length of the password: "); | |
scanf("%d", &passwordLength); | |
if (passwordLength <= 0) { | |
printf("Password length must be a positive integer.\n"); | |
return 1; // Error exit code | |
} | |
printf("Include symbols? (y/n): "); | |
char input; | |
scanf(" %c", &input); | |
if(input == 'y' || input == 'Y') { | |
includeSymbols = true; | |
} else if(input == 'n' || input == 'N') { | |
includeSymbols = false; | |
} else { | |
printf("Invalid input.\n"); | |
return 1; // Error exit code | |
} | |
generateRandomPassword(passwordLength, includeSymbols); | |
return 0; // Successful exit code | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment