HiveBrain v1.2.0
Get Started
← Back to all entries
patterncppMinor

Simple encryption algorithm

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
encryptionsimplealgorithm

Problem

I originally made this as a way to use character strings as a base-256 number, but then realized that I could turn it into a method for encryption instead. The only thing is that since I'm using a basic addition algorithm for the encryption process, I'm iterating through a string by one character at a time (which seems kind of slow). Are there any other ways to improve the performance of this process or am I pretty much stuck with simple iteration?

Here's the encryption code:

void encodeStr(string encryptKey, string& inputToEncrypt) {
    assert(minVal  maxVal) ? 1 : 0;
        ++count;
        ++keyPos;
        if (keyPos == encryptKey.size()) keyPos = 0;

        //add 1 to the count if there is a remainder at the end of keyNum
        if (count == countEnd && remainder != 0) {
            inputToEncrypt.push_back('\0');
            ++countEnd; //variables used to avoid integer overflow
        }
    }
}


And the decryption function:

void decodeStr(string decryptKey, string& inputToDecrypt) {
    assert(minVal  maxVal) ? 1 : 0;
        ++count;
        ++keyPos;
        if (keyPos == decryptKey.size()) keyPos = 0;
    }
}

Solution

Since you key is const it would be nice to mark it as such (and avoid accidents of changing your key):

void encodeStr(string const& encryptKey, string& inputToEncrypt) {
//                    ^^^^^


To save the cost of the copy I would also make it a reference.

No idea what these are:

assert(minVal < maxVal);


The extra set of variables seems like a good idea but actually makes the code harder to read as you need to understand what the variable represents:

size_t countEnd = inputToEncrypt.length();
while (count < countEnd) {

// Simpler to

while (count < inputToEncrypt.length()) {


When is this condition every going to fail and give you 0?

keyCount = (count < inputToEncrypt.length()) ? inputToEncrypt[count] : 0;


If it was going to fail then you should have the same precautions on this:

inputToEncrypt[count] = remainder;


This is also bound to result in truncation of reminder. As inputToEncrypt as a string and thus each position is a char while remainder is the sum of 2 integers both greater than minval.

inputToEncrypt[count] = remainder;

Code Snippets

void encodeStr(string const& encryptKey, string& inputToEncrypt) {
//                    ^^^^^
assert(minVal < maxVal);
size_t countEnd = inputToEncrypt.length();
while (count < countEnd) {

// Simpler to

while (count < inputToEncrypt.length()) {
keyCount = (count < inputToEncrypt.length()) ? inputToEncrypt[count] : 0;
inputToEncrypt[count] = remainder;

Context

StackExchange Code Review Q#12233, answer score: 6

Revisions (0)

No revisions yet.