0% found this document useful (0 votes)
36 views2 pages

#Include Stdio.h

Uploaded by

daniel nyamandi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
36 views2 pages

#Include Stdio.h

Uploaded by

daniel nyamandi
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 2

#include <stdio.

h>
#include <string.h>
#include <ctype.h>

#define ALPHABET_SIZE 26

int is_valid_key(const char *key) {


if (strlen(key) != ALPHABET_SIZE) {
return 0; // Key must be 26 characters long
}

int char_count[ALPHABET_SIZE] = {0}; // Initialize character count array

for (size_t i = 0; i < ALPHABET_SIZE; i++) {


if (!isalpha(key[i])) {
return 0; // Key must contain only alphabetic characters
}

int index = toupper(key[i]) - 'A';


if (char_count[index] > 0) {
return 0; // Key must not have repeated characters
}

char_count[index]++;
}

return 1; // Key is valid


}

char* create_substitution_key(const char *key) {


char *substitution_key = (char*)malloc(ALPHABET_SIZE + 1);
if (!substitution_key) {
perror("Memory allocation error");
exit(EXIT_FAILURE);
}

strcpy(substitution_key, key);
return substitution_key;
}

void encrypt_message(const char *message, const char *substitution_key) {


for (size_t i = 0; message[i] != '\0'; i++) {
if (isalpha(message[i])) {
if (isupper(message[i])) {
putchar(substitution_key[message[i] - 'A']);
} else {
putchar(tolower(substitution_key[message[i] - 'a']));
}
} else {
putchar(message[i]);
}
}
printf("\n");
}

int main(int argc, char *argv[]) {


if (argc != 2) {
printf("Usage: %s substitution_key\n", argv[0]);
return EXIT_FAILURE;
}

char *key = argv[1];


if (!is_valid_key(key)) {
printf("Invalid key. Please ensure it's 26 characters long, contains only
alphabetic characters, and has no repeated characters.\n");
return EXIT_FAILURE;
}

char message[1000]; // Adjust the size as needed


printf("Enter the message to encrypt: ");
scanf(" %[^\n]", message);

char *substitution_key = create_substitution_key(key);


encrypt_message(message, substitution_key);

free(substitution_key);
return EXIT_SUCCESS;
}

You might also like