Wikipedia's algorithm is this:
http://en.wikipedia.org/wiki/Vigen%C3%A8re_cipher#Algebraic_description
Encryption:
Ci = (Mi + Ki) modulo 26
Decryption:
Mi = (Ci - Ki) modulo 26
Where:
M is the Message array.
C is the Ciphertext array and
K is the Key array.
i is the current index of the arrays.
Firstly, be advised the cipher, in this form, only encrypts letters. No punctuation marks or digits.
Secondly, you have to represent your letters as numbers:
A = 0, B = 1, C = 2, ..., Y = 24, Z = 25
Thirdly, your Key array must be the exact same size as the Message array. This means trimming it down if it's longer, or duplicating it if it's shorter.
The
modulo operator in C++ is
%.
Here's a sample implementation of the encryption and decryption functions.
It's
untested, and it's still up to you to convert the letters to numbers, store them, and making sure the
key
and
message
arrays are the same size.
(I used
std::vector instead of plain arrays, because this is C++, not C.)
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
|
#include <stdexcept>
#include <vector>
std::vector<unsigned int> encrypt(const std::vector<unsigned int> &message, const std::vector<unsigned int> &key)
{
if (message.size() != key.size())
throw std::length_error("message and key aren't the same size");
std::vector<unsigned int> ciphertext;
for (std::vector<unsigned int>::size_type i = 0; i < message.size(); ++i)
ciphertext.push_back((message[i] + key[i]) % 26);
return ciphertext;
}
std::vector<unsigned int> decrypt(const std::vector<unsigned int> &ciphertext, const std::vector<unsigned int> &key)
{
if (ciphertext.size() != key.size())
throw std::length_error("ciphertext and key aren't the same size");
std::vector<unsigned int> message;
for (std::vector<unsigned int>::size_type i = 0; i < ciphertext.size(); ++i)
message.push_back((ciphertext[i] - key[i]) % 26);
return message;
}
|
Edit: hmm. Maybe you should use
int instead of
unsigned int.