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 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
|
#include <iostream>
#include <cstring>
#include <algorithm>
// Vigenere Cipher Methods:
// Note: assumes that both strings as arguments have length > 0, and that
// the key only contains letters of the alphabet from [A-Z]
void vigenere_encrypt(std::string& s, std::string key)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std::transform(key.begin(), key.end(), key.begin(), ::toupper);
unsigned int j = 0;
for (int i = 0; i < s.length(); i++)
{
if (isalpha(s[i]))
{
s[i] += key[j] - 'A';
if (s[i] > 'Z') s[i] += -'Z' + 'A' - 1;
}
j = j + 1 == key.length() ? 0 : j + 1;
}
}
void vigenere_decrypt(std::string& s, std::string key)
{
std::transform(s.begin(), s.end(), s.begin(), ::toupper);
std::transform(key.begin(), key.end(), key.begin(), ::toupper);
unsigned int j = 0;
for (int i = 0; i < s.length(); i++)
{
if (isalpha(s[i]))
{
s[i] = s[i] >= key[j] ?
s[i] - key[j] + 'A' :
'A' + ('Z' - key[j] + s[i] - 'A') + 1;
}
j = j + 1 == key.length() ? 0 : j + 1;
}
}
int main(void)
{
std::string s("AceInfinity's Example");
std::string key("Passkey");
vigenere_encrypt(s, key);
std::cout << "Encrypted: " << s << std::endl;
vigenere_decrypt(s, key);
std::cout << "Decrypted: " << s << std::endl;
return 0;
}
|