Nemok wrote:
Hi,
I am trying to write an additive encryption algorithm in C++ that will
encrypt a text by adding a random numer to each character in a string.
The code looks similar to this:
for(int i=0;i<=tlength-1;i++)///tlength is the length of the string to
encrypt
{
ctext[i]+=x+i;/////x is a random number and ctext is a char*
ctext[i]+=cpass[i%plength]+tlength;///////cpass is the key
(password)
ctext[tlength-1-i]+=x-i;
}
The problem is that while adding to the values of each char that char
might be 0 which will be interpreted like the ending NULL character of
the string. So what I need is a reversable method of
elliminating\replacing all 0 values with other values and then on
decryption of the encrypted string restore them. I can't just replace
the 0 values with another value because that value might also be
encountered in another char on decryption and will be wrongfully
transformed to 0. Please help.
Thanks.
The easiest solution would be to ignore the 0 bytes in the output, and
consider the ciphertext as binary data rather than a string. Your
encryption algorithm treats the input as binary data, so there's no
simple way of converting the output to anything else.
One work-around would be to convert your algorithm to be aware of the
size of the character set used by your strings. If, for instance, you
are only concerned with the characters on a standard US keyboard, then
you could perform all operations modulo the size of your character set
and encode each plaintext and ciphertext byte to an index into your
character set. This would be a lot more complicated than the simple
loop you just described, however.
If your output must be a string and you can't change the algorithm,
consider running a second pass on the output to escape all 0 bytes. To
do that, pick another byte value, for instance 1, and use it as an
escape character. Run through the ciphertext, replacing all 1 bytes
with two 1 bytes, and replacing all 0 bytes with a 1 byte followed by a
2 byte. Then, before decrypting, run through the string replacing all
double 1 bytes with single 1 bytes, and all 1,2 byte patterns with 0
bytes. Any other 1,x byte pattern would be invalid.
Bear in mind that the cryptosystem you described can be broken with
pencil and paper within minutes, so don't use it for anything real.
Rennie deGraaf