PHP Vigenere Cipher (Encode/Decode) Methods

AceInfinity

Emeritus, Contributor
Joined
Feb 21, 2012
Posts
1,728
Location
Canada
Here's a couple methods I wrote for the Vigenere Cipher in C++:

Code:
[NO-PARSE]#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);
	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);
	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;
}[/NO-PARSE]

It's basically a cyclical series of Ceasar Cipher's based on an input key. You could include shifting of digits and other symbols, but I really think this was more designed for letters of the alphabet from A-Z.

Constraints:
  • The key cannot contain any digits; only letters of the alphabet.
  • Obviously the input strings must have a length > 0

Note: Any non alphabet characters in the input string stay the same in the encoded text output. If your entire text is a number, the encoded version will be the same as the original, even after the encoding process with the key for the shifting.
 
Last edited:

Has Sysnative Forums helped you? Please consider donating to help us support the site!

Back
Top