// Vigenere.cpp #include #include #include "Vigenere.h" inline char IndexToChar( int aIndex ) { return (char)(aIndex + (int)'A'); } int CharToIndex( char aChar ) { // use alway upper case letters int Result = (int)toupper( aChar ); return Result - (int)'A'; } void Cipher::SetupVigenereSquare() { // start with second character (i.e., column 2) int lColumn = 1; // for each row i for ( int i = 0; i < 26; i++ ) { // set ith row column offset int lIndex = lColumn; // create ith row for ( int j = 0; j < 26; j++ ) { fVigenereSquare[i][j] = IndexToChar( lIndex ); lIndex++; lIndex %= 26; } // increment column offset lColumn++; lColumn %= 26; } } Cipher::Cipher() { SetupVigenereSquare(); } char Cipher::EncodeChar( char aKey, char aChar ) { if ( isalpha( aChar ) ) { // record lower case bool flag = isupper( aChar ); aChar = toupper( aChar ); // aKey selects the alphabet // aChar selects the column aChar = fVigenereSquare[CharToIndex( aKey )][CharToIndex( aChar )]; return flag ? aChar : tolower( aChar ); } else return aChar; } string Cipher::Encode( char aKey[], int& aKeyIndex, string aText ) { string Result(""); int lKeyLength = strlen( aKey ); // encode string for ( unsigned int i = 0; i < aText.size(); i++ ) { Result += EncodeChar( aKey[aKeyIndex], aText[i] ); // increment key index only in case of a letter if ( isalpha( aText[i] ) ) aKeyIndex = ++aKeyIndex % lKeyLength; } return Result; } char Cipher::DecodeChar( char aKey, char aChar ) { if ( isalpha( aChar ) ) { char Result = ' '; // record lower case bool flag = isupper( aChar ); aChar = toupper( aChar ); int lKeyIndex = CharToIndex( aKey ); // aKey selects the alphabet // aChar selects the column for ( int i = 0; i < 26; i++ ) if ( fVigenereSquare[lKeyIndex][i] == aChar ) { Result = IndexToChar( i ); break; } return flag ? Result : tolower( Result ); } else return aChar; } string Cipher::Decode( char aKey[], int& aKeyIndex,string aText ) { string Result(""); int lKeyLength = strlen( aKey ); // encode string for ( unsigned int i = 0; i < aText.size(); i++ ) { Result += DecodeChar( aKey[aKeyIndex], aText[i] ); // increment key index only in case of a letter if ( isalpha( aText[i] ) ) aKeyIndex = ++aKeyIndex % lKeyLength; } return Result; } void Cipher::normalizeKey( char aKey[] ) { char* lPToKey = aKey; char* lCurrent = aKey; while ( *lCurrent ) { if ( isalpha( *lCurrent ) ) { *lPToKey = toupper( *lCurrent ); lPToKey++; } lCurrent++; } *lPToKey = '\0'; }