Hey guys! I thought I would start a little series on cryptography algorithms. I’m going to run out this last hour before Mr. Robot’s season 2 airs.
With that said, let’s get down to business. The Caesar Cipher is named for its alleged use by the Roman Emperor Julius Caesar. In order to “ensure” the confidentiality of certain military-related messages, Caesar would perform an alphabetical shift on his messages.
Here’s an example.
C H E E S E
F K H H V H
Can you guess what the key is? It is… three (3)!
Okay. So all we did was shift each letter over to the “right” by three. Easy enough. What if the letters end up shifting past the alphabet?
X R A Y
A S B Z
All we must do is wrap around – and there is an easy way to tell a computer to do this.
Let’s develop an expression for the shift. Let’s say that the index of “A” is 0
, and the index of “X” is 25
. Our key, or shift-value, is k
.
Our expression would look like this:
character = ( index(character) + k ) % 26 + "A"
Let’s shift “B” over by 3
as an example. The index of “B” is 1
.
1 + 3 = 4
4 % 26 = 4
4 + "A" = "E"
The Code
#include <vector>
#include <string>
#include <iostream>
int main() {
std::string s; std::getline(std::cin, s);
int k; std::cin >> k;
for (auto& c : s) {
if (c >= 'a' && c <= 'z') {
c = ((c - 'a' + k) % 26) + 'a';
} else if (c >= 'A' && c <= 'Z') {
c = ((c - 'A' + k) % 26) + 'A';
}
}
std::cout << s << std::endl;
return 0;
}
You’ll notice that, rather than using some index()
method, I subtract c
from 'a'
to get an index. This is because your computer really just treats characters as special unsigned
, one-byte (usually), int
s.
In the Caesar Cipher, we ignore non-alphabetical characters because we won’t shift those. What happens if you shift a period?
Next, I’ll be doing the vigenere cipher.
Later…
@oaktree
P.S. Nxs’y ymj hfjxfw hnumjw httq?