#include #include #include char *encrypt( char *, char * ); char *decrypt( char *, char * ); int main( int argc, char **argv ){ char str[50], *key; int decrypt_on; if( argc < 2 ){ printf( "Encryption key is missing, exiting cowardly!\n" ); exit( 0 ); } key = argv[1]; // set the decrypt_on flag to 1 if user // requested the decryption mode if( argv[2] ){ decrypt_on = 1; } for( ;; ){ if( decrypt_on ){ printf( "Enter string to decrypt:\n" ); } else { printf( "Enter string to encrypt:\n" ); } // read alpha-spaces-newlines only scanf( "%[a-zA-Z \n]", str ); if( decrypt_on ){ printf( "Decrypted string:\n%s\n" , decrypt( str, key ) ); } else { printf( "Encrypted string:\n%s\n" , encrypt( str, key ) ); } } } /** * Encrypts a string using the Vigenère cipher * * @param char* str str to encrypt * @param char* str the cipher key to use * * @return char* str the ciphered text */ char *encrypt( char *str, char *key ){ unsigned char *encrypted, *reset_point; int len = 0; // put aside some space for the encrypted text encrypted = (unsigned char*) malloc( strlen( str ) ); // save the original cipher key address reset_point = key; while( *str ){ // if there are no more cipher key characters start from the // first one again if( !*key ){ key = reset_point; } // don't encrypt newlines and spaces, just save them and go to // the top of the loop if( *str == '\n' || *str == ' ' ){ *(encrypted++) = *(str++); len++; continue; } // simple math for our cipher *encrypted = tolower( *(str++) ) + tolower( *(key++) ) + 1 - 'a'; // sanitize the out-of-range characters if( *encrypted > 'z' ){ *encrypted -= 'z' - 'a' + 1; } len++; encrypted++; } // add a NULL at the end of our string... *encrypted = '\0'; // return the address of the encrypted string return encrypted - len; } /** * Decrypts a string using the Vigenère cipher * * @param char* str str to decrypt * @param char* str the cipher key to use * * @return char* str the deciphered text */ char *decrypt( char *str, char *key ){ unsigned char *decrypted, *reset_point; int len = 0; decrypted = (unsigned char*) malloc( strlen( str ) ); reset_point = key; while( *str ){ if( !*key ){ key = reset_point; } if( *str == '\n' || *str == ' ' ){ *(decrypted++) = *(str++); len++; continue; } *decrypted = tolower( *(str++) ) - tolower( *(key++) ) - 1 + 'a'; if( *decrypted < 'a' ){ *decrypted += 'z' - 'a' + 1; } len++; decrypted++; } *decrypted = '\0'; return decrypted - len; }