Encrypt
and Decrypt Strings
This single function will both encrypt and decrypt strings without the problems of other published routines.
The encrypted string is no longer than the original.
The routine handles strings containing all ASCII codes from 0..255.
The encrypted string does not contain extended character codes 128..255 unless the original does.
The encrypted string does not contain control codes 0..31 unless the original does. Even then, control codes are passed through without encryption, in order to avoid unexpected side-effects when the encrypted string is used elsewhere in an application.
This routine is not intended to provide Fort Knox levels of encryption. Encryption strength is similar to a conventional XOR with a key. However, the mapping of input characters to output characters depends on the high-order bits of the input characters as well as the key, which should provide some added protection against less sophisticated code-breakers.
As with other similar techniques, encryption strength increases with the length and randomness of the key.
For a detailed discussion of this algorithm and an alternative with additional benefits, see
here.
|
function SuperCipher (const S, Key : string) : string;
var
I, Z : integer;
C : char;
Code : byte;
begin
Result:= '';
Z:= length(Key);
if (Z > 0) and (length(S) > 0) then
for I:= 1 to length(S) do begin
Code:= ord(Key[(I - 1) mod Z + 1]);
if S[I] >= #128 then
C:= Chr(ord(S[I]) xor (Code and $7F))
else if S[I] >= #64 then
C:= Chr(ord(S[I]) xor (Code and $3F))
else if S[I] >= #32 then
C:= Chr(ord(S[I]) xor (Code and $1F))
else
C:= S[I];
Result:= Result + C;
end;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
editEncrypted.Text:= SuperCipher(editOriginal.Text,
editKey.Text);
// do something with encrypted string
editDecrypted.Text:= SuperCipher(editEncrypted.Text,
editKey.Text);
end; |
|