Einzelnen Beitrag anzeigen

randy_dom

Registriert seit: 28. Apr 2008
17 Beiträge
 
#1

AES encryption with Header

  Alt 2. Jul 2009, 16:41
I use the following the Code to encrypt my file using EAS algo :

I use this Interface to the AES functions written by Brian Gladman :AES Interface by Brian Gladman

Delphi-Quellcode:
 const HeadSig = 'mee'; // Header Sig
type
  TMyFileHead = packed record
    Signature : array [0..2] of char; // header sig
    flVer : String [4];// File Version
  end;
type
{ * encryption routine *}
function Enc(inStream, outStream :TStream; Header: TMyFileHead; const PWD :String='') : boolean;
begin
  inStream.Seek(0,soFromBeginning);
  outStream.Write(Header,SizeOf(TMyFileHead));// Write my Header Info to the Stream
 outStream.Seek(SizeOf(Header),soFromBeginning);
// Start the AES encryption routine
  with TEncryption.Create(PWD,defCryptBufSize) do begin
  if EncryptStream(inStream,outStream) then
  result:=true
  else
  result:=false;
   Free;
    end;
end;
// example Of use
procedure TForm1.Button3Click(Sender: TObject);
var
   H : TMyFileHead;
   F : TMemoryStream;
   F1 : TMemoryStream;
begin
   H.Signature:=HeadSig;// write my header Signature "mee"
   F := TMemoryStream.Create;
   F1 := TMemoryStream.Create;
   F.LoadFromFile('myfile.txt');
   // encrypt myfile.txt
   if Enc(F,F1,H)then
   F1.SaveToFile(ChangeFileExt('myfile.txt','.enc'));
   F.Free;
   F1.Free;
end;

{ * decryption routine *}
function Dec(inStream, outStream :TStream; var Header: TMyFileHead; const PWD :String=''):boolean;
begin
 inStream.Seek(0,soFromBeginning);
  inStream.Read(Header,SizeOf(TMyFileHead));
// file header<>'mee'
  if Header.Signature <> HeadSig then
  begin
  // invalid File Signature so Stop the Decryption Operation .
    Result := False;
    Exit;
  end;
  inStream.Seek(0,SizeOf(TMyFileHead));
  outStream.Seek(0,soFromBeginning);
 with TEncryption.Create(PWD,defCryptBufSize) do begin
 if DecryptStream(inStream,outStream,instream.Size) then
 result:=true
  else
  result:=false;
   Free;
  end;

// example of use
procedure TForm1.Button4Click(Sender: TObject);
var
  F : TMemoryStream;
  F1 : TMemoryStream;
  h : TMyFileHead;
begin
  F := TMemoryStream.Create;
  F1 := TMemoryStream.Create;
// load the encrypted file
  F.LoadFromFile('myfile.enc');
  if Dec(F,F1,H) then
  // save the decrypted file
  f1.SaveToFile(ChangeFileExt('myfile.enc','.dec'));
  F.Free;
  F1.Free;

end;

end;
the encryption Routine works well but the decryption is not working and no file is being saved .

What's incorrect with my Decryption Routine please ??
  Mit Zitat antworten Zitat