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);
if (inputToEncrypt.length() == 0) return;
//preliminary remainder check initialization
int remainder = minVal; //zero value
int keyNumCount = 0;
int keyCount = 0;
//variables used to determine when to stop counting numbers
size_t keyPos = 0;
size_t count = 0;
size_t countEnd = inputToEncrypt.length();
//begin numerical addition. stop once the end of both strings is reached
while (count < countEnd) {
//convert current characters to unsigned chars
keyNumCount = encryptKey[keyPos];
if (keyNumCount < minVal) keyNumCount += minVal;
keyCount = (count < inputToEncrypt.length()) ? inputToEncrypt[count] : 0;
if (keyCount < minVal) keyCount += minVal;
//take advantage of signed-char overflow to calculate current value
remainder += keyNumCount + keyCount;
inputToEncrypt[count] = remainder;
//check if there is a remainder to be tabulated
remainder = (remainder > 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);
if (inputToDecrypt.length() == 0) return;
//preliminary remainder check initialization
int remainder = minVal;
int keyNumCount = 0;
int keyCount = 0;
//variables used to determine when to stop counting numbers
size_t keyPos = 0;
size_t count = 0;
size_t countEnd = inputToDecrypt.length();
//make sure the program exits before the number necomes negative
while (count < countEnd) {
//convert current characters to unsigned chars
keyNumCount = decryptKey[keyPos];
if (keyNumCount < minVal) keyNumCount += minVal;
keyCount = inputToDecrypt[count];
if (keyCount < minVal) keyCount += minVal;
//take advantage of signed-char overflow to calculate current value
remainder += keyCount - keyNumCount;
inputToDecrypt[count] = remainder;
//check if there is a remainder to be tabulated
remainder = (remainder > maxVal) ? 1 : 0;
++count;
++keyPos;
if (keyPos == decryptKey.size()) keyPos = 0;
}
}