Encrypting\Decrypting data in .txt and .dat files

Blitz3D Forums/Blitz3D Beginners Area/Encrypting\Decrypting data in .txt and .dat files

3DFish(Posted 2004) [#1]
I'm trying to encrypt files in my game.
The files are highscores, game save data, etc..

I'm using the XOR method.
Encryption and decryption works fine with one line of text.
But as soon as I try to encrypt\decrypt a complete file with text, some characters are missing.
The characters get thrown away when I decrypt the file again.

Example of encrypting a string:
s$="Try encrypting this"
encrypt_string$=""
key$="a"

For i = 1 to Len(s)
char$=Mid(s,i,1)
encrypt_string=encrypt_string+Chr(Asc(char) + Xor Acs (key))
Next

I open a file, and read one line of text.
Then I call the above encrypt function.
I do this line for line.
I save the encrypted file.

The problem starts when I open the encrypted file and read
it line for line.
I call the above encrypt function.
Now the file is smaller in size & some characters are missing.

Maybe i'm not using the correct encrypt method?


eBusiness(Posted 2004) [#2]
How do you even get that running? You can't have an Xor after a +, they are both operators.


VIP3R(Posted 2004) [#3]
Don't forget the ASCII codes only range 0 to 127, if the Xor'ed number is outside this range, you probably will lose some of the characters in the string.

A better method might be to convert each character into an integer value something like this:

For i = 1 to Len(s$) 
encrypt_integer=Asc(Mid$(s$,i,1)) Xor Asc(key$)
; Save integer to file here
Next


Then save each integer instead of lines of strings. When you decrypt it just reverse the process, something like decrypted$=decrypted$+Chr$(encrypted_integer) Xor Asc(key$). The downside to this is an integer will take up four bytes whereas one ASCII character only takes up one byte, so the resulting file will be four times larger using integers.

Note, you will also have to either save an integer describing the final size of each string, or use a sequence of characters to show the end of each string, if each of the strings are to remain seperate.


eBusiness(Posted 2004) [#4]
That was in the old days, now all 256 are legal ASCIIs.

ÆöêÑ


3DFish(Posted 2004) [#5]
eBusiness
How do you even get that running? You can't have an Xor after a +, they are both operators.

--------
Sorry my mistake.
The + is a typo...

---
Thanks VIP3R
I'll try the interger method this afternoon.


VIP3R(Posted 2004) [#6]

That was in the old days, now all 256 are legal ASCIIs.


I feel old now ;)


eBusiness(Posted 2004) [#7]
'a typo'??? Ever heard about copy/paste?