C++: Caesar Cipher

Bjarne-stroustrup
 

Implement a Caesar cipher, both encoding and decoding.
The key is an integer from 1 to 25.

This cipher rotates (either towards left or right) the letters of the alphabet (A to Z).

The encoding replaces each letter with the 1st to 25th next letter in the alphabet (wrapping Z to A). So key 2 encrypts “HI” to “JK”, but key 20 encrypts “HI” to “BC”.

This simple “monoalphabetic substitution cipher” provides almost no security, because an attacker who has the encoded message can either use frequency analysis to guess the key, or just try all 25 keys.

Caesar cipher is identical to Vigenère cipher with a key of length 1.
Also, Rot-13 is identical to Caesar cipher with key 13.

#include <string>
#include <iostream>
#include <algorithm>
#include <cctype>

class MyTransform {
	private : 
	int shift ;
	public :
	MyTransform( int s ) : shift( s ) { } 

	char operator( )( char c ) {
		if ( isspace( c ) ) 
		return ' ' ;
		else {
			static std::string letters( "abcdefghijklmnopqrstuvwxyz" ) ;
			std::string::size_type found = letters.find(tolower( c )) ;
			int shiftedpos = ( static_cast<int>( found ) + shift ) % 26 ;
			if ( shiftedpos < 0 ) //in case of decryption possibly
			shiftedpos = 26 + shiftedpos ;
			char shifted = letters[shiftedpos] ;
			return shifted ;
		}
	}
} ;

int main( ) {
	std::string input ;
	std::cout << "Which text is to be encrypted ?\n" ;
	getline( std::cin , input ) ;
	std::cout << "shift ?\n" ;
	int myshift = 0 ;
	std::cin >> myshift ;
	std::cout << "Before encryption:\n" << input << std::endl ;
	std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,
	MyTransform( myshift ) ) ;
	std::cout << "encrypted:\n" ;
	std::cout << input << std::endl ;
	myshift *= -1 ; //decrypting again
	std::transform ( input.begin( ) , input.end( ) , input.begin( ) ,
	MyTransform( myshift ) ) ;
	std::cout << "Decrypted again:\n" ;
	std::cout << input << std::endl ;
	return 0 ;
}
Output:
Which text is to be encrypted ?
this is an interesting text
shift ?
3
Before encryption:
this is an interesting text
encrypted:
wklv lv dq lqwhuhvwlqj whaw
Decrypted again:
this is an interesting text

SOURCE

Content is available under GNU Free Documentation License 1.2.

Subscribe to TFE Times

Enter your email address to become a member of TFE Times today!