Std::String Encryption

I just need a simple way to encrypt and decrypt an std::string, I don't want to download anything, thanks.
Well, how do you want it encrypted?

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
#include <iostream>
#include <string>

std::string encrypt(std::string msg, std::string key)
{
    // Make sure the key is at least as long as the message
    std::string tmp(key);
    while (key.size() < msg.size())
        key += tmp;
    
    // And now for the encryption part
    for (std::string::size_type i = 0; i < msg.size(); ++i)
        msg[i] ^= key[i];
    return msg;
}
std::string decrypt(std::string msg, std::string key)
{
    return encrypt(msg, key); // lol
}

int main()
{
    std::string message = encrypt("Hello world!", "monkey");
    std::cout << "Encrypted: " << message;
    std::cout << "\nDecrypted: " << decrypt(message, "monkey");
}
This works perfectly, however, if you wouldn't mind, how exactly does this part work?

 
msg[i] ^= key[i];


pointing me to a document or reference would be great, thanks!
It's just a simple XOR encryption:
http://en.wikipedia.org/wiki/XOR_cipher

The ^ operator is the bitwise XOR operator.
Suggestion:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
// key is now const&
std::string encrypt(std::string msg, std::string const& key)
{
    // Side effects if the following is not written:
    // In my case, division by 0.
    // In the other case, stuck in an infinite loop.
    if(!key.size())
        return msg;
    
    for (std::string::size_type i = 0; i < msg.size(); ++i)
        msg[i] ^= key[i%key.size()];
    return msg;
}

// Rewritten to use const& on both parameters
std::string decrypt(std::string const& msg, std::string const& key)
{
    return encrypt(msg, key); // lol
}

// No external changes needed. 
Last edited on
Oh yeah, I totally forgot I could just use the modulus operator...

Well, all I have to say about that is that line 3 can become if (key.empty()). :-)
Well, sounds fair.
Topic archived. No new replies allowed.