Published by
Jan 21, 2012 (last update: Jan 21, 2012)

ROT13 cypher

Score: 3.7/5 (48 votes)
*****
NB: the ROT13 cypher should not be used for real security, as it is incredibly simple to reverse (simply re-apply the cypher to the output text).

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
#include <cctype>
#include <iostream>
#include <string>

/**
 * \brief	Apply the ROT13 algorithm to a string.
 * \param source Source text to apply the algorithm to.
 * \return	The transformed text is returned.
 */
std::string ROT13(std::string source)
{
	std::string transformed;
	for (size_t i = 0; i < source.size(); ++i) {
		if (isalpha(source[i])) {
			if ((tolower(source[i]) - 'a') < 14)
				transformed.append(1, source[i] + 13);
			else
				transformed.append(1, source[i] - 13);
		} else {
			transformed.append(1, source[i]);
		}
	}
	return transformed;
}

int main()
{
	std::string source;
	std::cout << "Enter the source text: " << std::flush;
	std::getline(std::cin, source);
	std::cout << "Result: " << ROT13(source) << std::endl;
	return 0;
}