Demonstration of Encryption
Program ASM_Encrypt encrypts an entire text file, line by line. It uses 8 keys in rotation. The most significant bit (msb) of each key is 1. When this is XORed with the usual characters (which have a msb of 0) the resulting character must have a msb of 1. This prevents the generation of control codes (such as 10, 13 and 26), which can cause problems.
We used the code from Matt's program DelphiManager to test the encryption but you can change the value of the INPUT_FILE constant for your own tests.
program ASM_Encrypt; {$APPTYPE CONSOLE} {$ASMMODE INTEL} //Delete this line in Delphi uses SysUtils; const KEYS : array [0..7] of byte = ($85, $A8, $FA, $D3, $C7, $8B, $E2, $9B); INPUT_FILE = 'DelphiManager.txt'; ENCRYPTED = 'Encrypted.txt'; var InFile, EncryptedFile : textFile; CurrentString : shortString; StringLength, CharCount: integer; begin CharCount := 0; assignFile(InFile, INPUT_FILE); assignFile(EncryptedFile, ENCRYPTED); reset(InFile); rewrite(EncryptedFile); while not eof(InFile) do begin readln(InFile, CurrentString); StringLength := Length(CurrentString); asm MOV ECX, StringLength //ECX will count down CMP ECX, 0 //Check for empty string JE @Finish //If zero flag set, do not encrypt @Start: ADD CharCount, 1 MOV EDX, CharCount //Move into EDX the character count AND EDX, 7 //get an offset 0 to 7 MOV AL, [ECX+CurrentString] //Load AL with code of current char XOR AL, [EDX+KEYS] //Encrypt MOV [ECX+CurrentString], AL //Replace original in CurrentString Loop @Start //Go to start of loop is ECX is not 0 @Finish: end; writeln(EncryptedFile, CurrentString); end; closeFile(InFile); closeFile(EncryptedFile); writeln('Encryption complete'); readln; end.
As usual, the version using AT&T syntax follows.
program ASM_EncryptA; {$mode objfpc}{$H+} {$ASMMODE ATT} uses SysUtils; const KEYS : array [0..7] of byte = ($85, $A8, $FA, $D3, $C7, $8B, $E2, $9B); INPUT_FILE = 'DelphiManager.txt'; ENCRYPTED = 'Encrypted.txt'; var InFile, EncryptedFile : textFile; CurrentString : shortString; StringLength, CharCount: integer; begin CharCount := 0; assignFile(InFile, INPUT_FILE); assignFile(EncryptedFile, ENCRYPTED); reset(InFile); rewrite(EncryptedFile); while not eof(InFile) do begin readln(InFile, CurrentString); StringLength := Length(CurrentString); asm MOV StringLength, %ECX //ECX will count down CMP $0, %ECX //Check for empty string JE .LFinish //If zero flag set, do not encrypt .LStart: ADD $1, CharCount MOV CharCount, %EDX //Move into EDX the character count AND $7, %EDX //get an offset 0 to 7 //Load AL with code of current char MOV CurrentString (%ECX), %AL XOR KEYS (%EDX), %AL //Encrypt //Replace original in CurrentString MOV %AL, CurrentString (%ECX) Loop .LStart //Go to start of loop is ECX <> 0 .LFinish: end; writeln(EncryptedFile, CurrentString); end; closeFile(InFile); closeFile(EncryptedFile); writeln('Encryption complete'); readln; end.