http://www.daniweb.com/software-development/cpp/threads/267174/vigenere-cipher

Read that. Was the full, complete code posted? If so, can I get a link or code? I want to refer to this when I get stuck with my project.

Recommended Answers

All 2 Replies

Okay, I'll bite. On the assumption that you won't simply turn in my code as if you wrote it, and because the Vigenere cipher is so shockingly simple, here's some working code:

#include <climits>
#include <cstdlib>
#include <iostream>
#include <string>

using namespace std;

/*
    @description:
        Increments value and wraps around to 0 when limit is reached.
*/
template <typename T, typename U>
T wrapped_increment(T value, U limit) { return ++value >= limit ? 0 : value; }

/*
    @description:
        Encodes 'src' using the key 'key' in a Vigenere cipher
        given an alphabet spanning the whole of the char type.
*/
string sucky_cipher(const string& src, const string& key, int max = CHAR_MAX + 1)
{
    string::size_type i = 0, j = 0;
    string result;

    /*
        Encode with the formula: 'C[i] = (M[i] + K[i]) mod N' where M
        is the plain source, K is the key, and N is the alphabet size
    */
    while (i != src.size()) {
        result.push_back((src[i++] + key[j]) % max);
        j = wrapped_increment(j, key.size());
    }

    return result;
}

/*
    @description:
        Decodes 'src' using the key 'key' in a Vigenere cipher
        given an alphabet spanning the whole of the char type.
*/
string sucky_decipher(const string& src, const string& key, int max = CHAR_MAX + 1)
{
    string::size_type i = 0, j = 0;
    string result;

    /*
        Decode with the formula: 'M[i] = (C[i] - K[i]) mod N' where C
        is the encoded source, K is the key, and N is the alphabet size
    */
    while (i != src.size()) {
        int temp = src[i++] - key[j];

        // C++ modulo doesn't work quite like we want for negative quantities
        while (temp < 0)
            temp = max - abs(temp);

        result.push_back(temp % max);
        j = wrapped_increment(j, key.size());
    }

    return result;
}

int main()
{
    string src = "this is a test", key = "booger";
    string cipher = sucky_cipher(src, key);

    cout << cipher << '\n' << sucky_decipher(cipher, key) << '\n';
}

Reminds me of cyphers I wrote back in the mid-1980's before I was comfortable with public-key encryption using large prime factors. Then I went and wrote a serious prime factorization tool so I could generate/decode Goedel numbers for radom strings... :-)

commented: cool :) +3
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.