這通常是運用在資料庫內有密碼的時候,不希望顯示的是明碼,所以要透過加密解密的動作來實現這個需求,這邊使用的是AES加密功能。
DELPHI 用的 AES 檔案 下載
此範例程式(D7)已含AES檔案:下載
程式執行:
將 28295_AESDemo.zip 解壓縮後三個檔案
ElAES.dcu
ElAES.pas
ElAES.txt
COPY 欲撰寫程式的同一目錄下面
將(ElAES, Math) USES進程式
unit hoststatus;
interface
uses
……….ElAES, Math;
//AES加解密用到的 Function ===========================
function Tform1.StringToHex(S: string): string;
var
i: integer;
begin
Result := ”;
// Go throught every single characters, and convert them
// to hexadecimal…
for i := 1 to Length( S ) do
Result := Result + IntToHex( Ord( S[i] ), 2 );
end;
function Tform1.HexToString(S: string): string;
var
i: integer;
begin
Result := ”;
// Go throught every single hexadecimal characters, and convert
// them to ASCII characters…
for i := 1 to Length( S ) do
begin
// Only process chunk of 2 digit Hexadecimal…
if ((i mod 2) = 1) then
Result := Result + Chr( StrToInt( ‘0x’ + Copy( S, i, 2 )));
end;
end;
//AES加密Function
function Tform1.Encrypt(Passwd: String): String;
var
Source: TStringStream;
Dest: TStringStream;
Start, Stop: cardinal;
Size: integer;
Key: TAESKey128;
PWD: String;
begin
//設定加密密碼;
PWD := ‘/.,mnbvcxz’;
Source := TStringStream.Create( Passwd );
Dest := TStringStream.Create( ” );
try
// Save data to memory stream…
Size := Source.Size;
Dest.WriteBuffer( Size, SizeOf(Size) );
// Prepare key…
FillChar( Key, SizeOf(Key), 0 );
Move( PChar(PWD)^, Key, Min( SizeOf( Key ), Length( PWD )));
// Start encryption…
Start := GetTickCount;
EncryptAESStreamECB( Source, 0, Key, Dest );
Stop := GetTickCount;
// Display encrypted text using hexadecimals…
Result := StringToHex( Dest.DataString );
finally
Source.Free;
Dest.Free;
end;
end;
//AES解密Function
function Tform1.Decypt(Passwd: String): String;
var
Source: TStringStream;
Dest: TStringStream;
Start, Stop: cardinal;
Size: integer;
Key: TAESKey128;
EncryptedText: TStrings;
S: string;
PWD: String;
begin
//設定加密密碼;
PWD := ‘/.,mnbvcxz’;
// Convert hexadecimal to a strings before decrypting…
Source := TStringStream.Create( HexToString( Passwd ));
Dest := TStringStream.Create( ” );
try
// Start decryption…
Size := Source.Size;
Start := GetTickCount;
Source.ReadBuffer(Size, SizeOf(Size));
// Prepare key…
FillChar(Key, SizeOf(Key), 0);
Move(PChar(PWD)^, Key, Min(SizeOf(Key), Length(PWD)));
// Decrypt now…
DecryptAESStreamECB(Source, Source.Size – Source.Position, Key, Dest);
Stop := GetTickCount;
// Display unencrypted text…
Result := Dest.DataString;
finally
Source.Free;
Dest.Free;
end;
end;
//AES加解密用到的 Function ===========================
procedure TForm1.Button1Click(Sender: TObject);
begin
//showmessage(Encrypt(Edit1.Text));
Memo1.Text:= Encrypt(Edit1.Text);
Memo2.Text:=”;
end;
procedure TForm1.Button2Click(Sender: TObject);
begin
if Trim(Memo1.Text) <> ” then
begin
//showmessage(Decypt(Memo1.Text));
Memo2.Text:= Decypt(Memo1.Text);
end else
MessageDlg(‘沒有已加密資料可供解密!’, mtError, [mbOk], 0);
end;
procedure TForm1.FormCreate(Sender: TObject);
begin
Memo1.Enabled := false;
Memo2.Enabled := false;
end;
近期留言