MarshallSoft

Delphi Advanced Encryption Standard (AES) Example


function EncryptFile(Pass:AnsiString; FileName:AnsiString):Integer;
var
  Code : Integer;
  Control: AnsiString; // control buffer
  Vector : AnsiString; // initialization vector (not used)
  KeyBuf : AnsiString; // encryption key
  Source : AnsiString; // source pathname
  Target : AnsiString; // target pathname
begin
  {user AES space for control}
  Control := '*';
  {attach AES}
  Code := aesAttach(AES_KEY_CODE, 0);
  if Code < 0 then
  begin
    EncryptFile := -1;
    exit;
  end
  {create encryption key buffer & initialization vector}
  KeyBuf := StringOfChar(Chr(0), AES_KEY_SIZE);
  Vector := StringOfChar(Chr(0), AES_BLOCK_SIZE);
  {process password phrase}
  Code := aesMakeUserKey(@Pass[1], @KeyBuf[1], 0);
  if Code < 0 then
  begin
    EncryptFile := Code;
    exit;
  end;
  {initialize AES for encrypting (ECB mode)}
  Code := aesInitAES(@KeyBuf[1], @Vector[1], AES_ECB_MODE, AES_ENCRYPT, @Control[1]);
  if Code < 0 then
  begin
    {aesInitAES fails}
    EncryptFile := Code;
    exit;
  end;
  {construct file names for encryption}
  Source := FileName + Chr(0);
  Target := FileName + '.aes' + Chr(0);
  {encrypt source file to target file}
  Code := aesEncryptFile(@Control[1], @Source[1], @Target[1]);
  if Code < 0 then
  begin
    {aesEncryptFile fails}
    EncryptFile := Code;
    exit;
  end;
end;

MSC Logo

HOME PAGE
MARSHALLSOFT is a trademark of MarshallSoft Computing, Inc.