Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Very basic form of file encryption?

What is a simple and effective way to encrypt a plain text file? I'm not looking for safety, I just want the average user not to be able to tamper with it. Say I have a file with newline separated email addresses. I want it to look like a garbled mess when opened, but easy to decrypt.

like image 727
jmasterx Avatar asked Dec 17 '22 06:12

jmasterx


1 Answers

The simplest practical form is an XOR cipher. Basically you generate an encryption/decryption key of random numbers, of any length. To encrypt or decrypt your data, XOR the data with the key.

It is not very secure; it's mostly just used to do a light obfuscation.

#include <vector>

typedef unsigned __int8 BYTE;

std::vector<BYTE> xor_encryptdecrypt(const std::vector<BYTE>& encryptionKey, const std::vector<BYTE>& input)
{
    std::vector<BYTE> ret;
    ret.reserve(input.size());

    std::vector<BYTE>::const_iterator keyIterator = encryptionKey.begin();

    for(std::vector<BYTE>::const_iterator inputIterator = input.begin(); inputIterator != input.end(); ++ inputIterator)
    {
        ret.push_back(*inputIterator ^ *keyIterator);

        // advance the key iterator, wrapping to begin.
        if(++ keyIterator == encryptionKey.end())
            keyIterator = encryptionKey.begin();
    }
    return ret;
}


int main()
{
    // variable-length key of randomness, used for both encryption and decryption.
    std::vector<BYTE> key;
    key.push_back(0x55);
    key.push_back(0xae);
    key.push_back(0x8c);
    key.push_back(0x14);

    std::vector<BYTE> input;
    input.push_back(0x00);
    input.push_back(0x01);
    input.push_back(0x02);
    input.push_back(0x03);
    input.push_back(0x04);
    input.push_back(0x05);

    // encrypt
    std::vector<BYTE> encrypted = xor_encryptdecrypt(key, input);

    // decrypt
    std::vector<BYTE> decrypted = xor_encryptdecrypt(key, encrypted);

    return 0;
}
like image 97
tenfour Avatar answered Jan 02 '23 12:01

tenfour