出自HUBDOG的葵花宝典
program Crypt;
uses WinCRT;
const
C1 = 52845;
C2 = 22719;
function Encrypt(const S: String;
Key: Word): String;
var
I: byte;
begin
Result[0] := S[0];
for I := 1 to Length(S)do
begin
Result := char(byte(S) xor (Key shr 8));
Key := (byte(Result) + Key) * C1 + C2;
end;
end;
function Decrypt(const S: String;
Key: Word): String;
var
I: byte;
begin
Result[0] := S[0];
for I := 1 to Length(S)do
begin
Result := char(byte(S) xor (Key shr 8));
Key := (byte(S) + Key) * C1 + C2;
end;
end;
var
S: string;
begin
Write('>');
ReadLn(S);
S := Encrypt(S,12345);
WriteLn(S);
S := Decrypt(S,12345);
WriteLn(S);
end.
//////////////////////////////////////////////////////
unit Unit2;
interface
Const Allchar: string = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz0123456789';
procedure Encrypt( var ss: string );
implementation
procedure Encrypt( var ss: string );
var l, lac, // string length
sp, // ss char pointer
cp: integer;
// allchar pointer
begin
l := Length(ss);
lac := Length( Allchar );
sp := 1;
while sp <= ldo
begin
cp := 1;
while (allchar[cp] <> ss[sp]) and ( cp <= lac )do
inc( cp );
{ match char and find the encrypted counterpart in the reverse
order in position }
if cp > lac then
ss[sp]:= '*'
{ Mark illegal char - use only char not in allchar }
else
begin
{ Un-remark next line will further enhance security...
such that same character will appear as
different after encrypt }
// cp := (( cp + sp*2 ) mod lac) + 1;
ss[sp] := allchar[ lac - cp + 1 ];
//first char result in the last
end;
inc(sp);
end;
end;
end.
{ Specail about this procedure:
1. Same procedure to encrypt and decrypt.
( less code to maintain. )
2. Every Allchar set produce a different encryption.
{ a set of 62 char produce 3.147E85 combinations )
3. Full control over character set of encrypted string.
( good for 7-bit fields, barcoding, passwords, magstripe and filenames etc )
4. One table lookup. ( easy to ensure no duplication possible
for every possible allchar. So as a need to remove/add chars )
5. Automatic marking of illegal characters.
( simplified coding needs. )
--------------------------------------------------------------------------------
以下介绍的加密算法强度不高,我编写它是因为我需要既保持文本是由可打印字符组成的,同时又无法直接看到,也许一个孩子花上十分钟就可以破解这个算法......也许吧,这我不清楚,而且也不关心,因为我只要它能达到我的目的就行。
密钥(Key)的长度可以设置为任意长度。在这个函数中,将每个字符的低四位和密钥中字符的低四位进行XOR运算,这样加密后的字符仍然是7位的字符同时也是可打印的。
{注意 :- Key如果为空,则使用缺省密钥}
function DenCrypt(Str : string;
Key : string): string;
var
X, Y : Integer;
A : Byte;
begin
if Key = '' then
Key := 'd1duOsy3n6qrPr2eF9u';
Y := 1;
for X := 1 to length(Str)do
begin
A := (ord(Str[X]) and $0f) xor (ord(Key[Y]) and $0f);
Str[X] := char((ord(Str[X]) and $f0) + A);
inc(Y);
if Y > length(Key) then
Y := 1;
end;
Result := Str;
end;
由于函数使用的是简单的XOR运算,因此你可以再次以相同的密钥调用此函数就可以解密字符串。