需要uses两个单元:DCPrc4, DCPsha1。
加密过程:
procedure TForm1.ButtonEnCryptClick(Sender: TObject);
var
Cipher: TDCP_rc4;
Source, Target: TFileStream;
begin
if not FileExists(EditSource.Text) then begin
ShowMessage('出错了: 源文件不存在!');
Exit;
end;
if FileExists(EditTarget.Text) then
RenameFile(EditTarget.Text, EditTarget.Text+'.bak');
try
Source:= TFileStream.Create(EditSource.Text,fmOpenRead);
Target:= TFileStream.Create(EditTarget.Text,fmCreate);
Cipher:= TDCP_rc4.Create(Self);
Cipher.InitStr(KeyStr,TDCP_sha1);
Cipher.EncryptStream(Source,Target,Source.Size);
Cipher.Burn;
Cipher.Free;
Target.Free;
Source.Free;
ShowMessage('搞定!');
except
ShowMessage('错误: 读写文件错误!');
end;
end;
解密过程:
procedure TForm1.ButtonDeCryptClick(Sender: TObject);
var
Cipher: TDCP_rc4;
Source, Target: TFileStream;
begin
if not FileExists(EditTarget.Text) then begin
ShowMessage('出错了: 源文件不存在!');
Exit;
end;
if FileExists(EditSource.Text) then
RenameFile(EditSource.Text, EditSource.Text+'.bak');
try
Source:= TFileStream.Create(EditTarget.Text,fmOpenRead);
Target:= TFileStream.Create(EditSource.Text,fmCreate);
Cipher:= TDCP_rc4.Create(Self);
Cipher.InitStr(KeyStr,TDCP_sha1);
Cipher.DecryptStream(Source,Target,Source.Size);
Cipher.Burn;
Cipher.Free;
Target.Free;
Source.Free;
ShowMessage('加密完成!');
except
ShowMessage('错误: 读写文件错误!');
end;
end;
源文本文件:
加密后: