Lucky i remembered this was in my bookmarks!
well I needed a refresh in C, so here's mine
(if i can be bothered i will make it compile with -ansi -Wall -pedantic)
PHP Code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
// prototypes
int encypt(char *input, char *key);
int decrypt(char *EncString, char *key);
int getString(char *string, unsigned length, char *prompt);
void usage();
// end
#define FAILURE 0
#define SUCCESS 1
#define INPUT_LENGTH 20
#define PROMPT_LENGTH 30
#define ENCRYPT 100
#define DECRYPT 200
int main(int argc, char **argv) {
char input[INPUT_LENGTH];
char key[INPUT_LENGTH];
char prompt[PROMPT_LENGTH];
int option = 0;
if(argc == 2) {
if(strcmp("encrypt",argv[1]) == 0) option = ENCRYPT;
else if(strcmp("decrypt",argv[1]) == 0) option = DECRYPT;
else { usage(); return EXIT_FAILURE; }
}else{
usage();
return EXIT_FAILURE;
}
sprintf(prompt,"Enter text :", PROMPT_LENGTH);
getString(input, INPUT_LENGTH, prompt);
sprintf(prompt,"Enter Key :", PROMPT_LENGTH);
getString(key, INPUT_LENGTH, prompt);
printf("\n");
switch(option){
case ENCRYPT: encrypt(input,key); break;
case DECRYPT: decrypt(input,key); break;
}
return EXIT_SUCCESS;
}
int encrypt(char *input, char *key) {
int i = 0, keyOffset = 0;
char p = '\0';
for(; i < strlen(input); i++){
if(isalpha(input[i]) && isalpha(key[keyOffset])) {
//p = (c + k) % 26
p = ((input[i] - 'A') + (key[keyOffset] - 'A')) % 26;
p += 'A';
}else p = input[i];
// print char as it comes out
printf("%c", p);
if((keyOffset ++) > strlen(key)) keyOffset = 0;
}
printf("\n");
return SUCCESS;
}
int decrypt(char *encString, char *key){
int i = 0, keyOffset = 0;
char c = '\0';
for(; i < strlen(encString); i++){
if(isalpha(encString[i]) && isalpha(key[keyOffset])) {
//c = (p - k) % 26
c = ((encString[i] - 'A') - (key[keyOffset] - 'A')) % 26;
if(c < 0) c += 26;
c += 'A';
}else c = encString[i];
printf("%c", c);
if((keyOffset ++) > strlen(key)) keyOffset = 0;
}
printf("\n");
return SUCCESS;
}
int getString (char *string, unsigned length, char *prompt){
char temp[INPUT_LENGTH + 2];
printf("%s", prompt);
fgets(temp, (length + 2), stdin); // add 2 for '\n' and '\0'
// can do ALL types of input validation here.
// for this example, didnt worry about...
temp[strlen(temp) -1] = '\0'; // override \n with \0
strcpy(string, temp); // make result available to calling function
return SUCCESS;
}
void usage() {
printf("Usage, ./a.out <encrypt | decrypt>\n");
}
Its probably way bigger than it has to be, but nevertheless
Bookmarks