mirror of https://github.com/me50/kukemuna.git
This commit is contained in:
commit
b7839725fe
|
|
@ -0,0 +1,78 @@
|
|||
#include <cs50.h>
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
int validate_key(string key); // NQXPOMAFTRHLZGECYJIUWSKDVB
|
||||
void substitute(string plaintext, string key);
|
||||
|
||||
int main(int argc, string argv[])
|
||||
{
|
||||
// Print usage and exit if argc is not 2 or key is not integer
|
||||
if (argc != 2 || validate_key(argv[1]) > 0)
|
||||
{
|
||||
printf("Usage: ./substitution key\n");
|
||||
return 1;
|
||||
}
|
||||
else
|
||||
{
|
||||
string key = argv[1];
|
||||
string plaintext = get_string("plaintext: ");
|
||||
substitute(plaintext, key);
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
// Convert a string of numbers to integer
|
||||
int validate_key(string key)
|
||||
{
|
||||
// Sum of consecutive numbers: (b + a) x (b - a + 1) / 2
|
||||
// If key length is 26 then iterate each string element
|
||||
if (strlen(key) == 26)
|
||||
{
|
||||
int sum = 0;
|
||||
|
||||
for (char c = 'A'; c <= 'Z'; c++)
|
||||
{
|
||||
for (int i = 0; i < 26; i++)
|
||||
{
|
||||
if (toupper(key[i]) == c)
|
||||
{
|
||||
sum++;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (sum == 26) // Sum of 26 unique uppercase characters, but also MMCcEFGHIJKLMNOPQRqTUVWXeZ
|
||||
{
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
void substitute(string plaintext, string key)
|
||||
{
|
||||
printf("ciphertext: ");
|
||||
|
||||
for (int i = 0; i < strlen(plaintext); i++)
|
||||
{
|
||||
if (isalpha(plaintext[i]))
|
||||
{
|
||||
if (isupper(plaintext[i]))
|
||||
{
|
||||
printf("%c", toupper(key[plaintext[i] - 65]));
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("%c", tolower(key[plaintext[i] - 97]));
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
printf("%c", plaintext[i]);
|
||||
}
|
||||
}
|
||||
printf("\n");
|
||||
}
|
||||
Loading…
Reference in New Issue