madCrypt + TStrings

delphi package - madRes, madTools, madStrings, ...
Post Reply
iconic
Site Admin
Posts: 1064
Joined: Wed Jun 08, 2005 5:08 am

madCrypt + TStrings

Post by iconic »

Just wanted to share some simple yet useful code I wrote many years ago and recently had to reuse in a project which allows you to Save/Load any TStrings descendant (i.e> TStringList) string properties to/from an encrypted file. Maybe some of you will find it useful? You can add your own error handling if desired. This is just a basic example without any try/except block for readability purposes

Code: Select all

function CryptSaveToFile(const List: TStrings;
                           FileName: String;
                           Password: AnsiString): Boolean;
var
    Stream: TMemoryStream;
begin
    result := False;
    if (List <> nil) and (List.Count > 0) then
    begin
    Stream := TMemoryStream.Create;
    try
    List.SaveToStream(Stream);
    Encrypt(Stream.Memory, Stream.Size, Password);
    Stream.SaveToFile(FileName);
    result := True;
    finally
    FreeAndNil(Stream);
    end;
   end;
end;


function CryptLoadFromFile(const List: TStrings;
                             FileName: String;
                             Password: AnsiString): Boolean;
var
    Stream: TMemoryStream;
begin
    result := False;
    if (List <> nil) and FileExists(FileName) then
    begin
    Stream := TMemoryStream.Create;
    try
    Stream.LoadFromFile(FileName);
    Decrypt(Stream.Memory, Stream.Size, Password);
    List.LoadFromStream(Stream);
    result := True;
    finally
    FreeAndNil(Stream);
    end;
    end;
end;


const
   Pass = '%$_@^*<$]/.&)!~#>(&!`?^[\,';


procedure PerformTest;
const
    CRLF = sLineBreak;
    FILENAME = '%ALLUSERSPROFILE%\ENCRYPTED';
var
    List: TStringList;
    lpFileName: Array [0..MAX_PATH-1] of Char;
    Ch: Char;
begin
    List := TStringList.Create;
    try
    for Ch := 'X' to 'Z' do
    List.Add(StringOfChar(Ch, 20));
    if ExpandEnvironmentStrings(PChar(FileName), @lpFileName, MAX_PATH) <> 0 then
    // Save some encrypted strings
    if CryptSaveToFile(List, lpFileName, Pass) then
    begin
    // Load it back directly to see if it's encrypted
    List.LoadFromFile(lpFileName);
    ShowMessageFmt('%s%s', ['Encrypted' + CRLF + CRLF, List.Text]);
    // Reload it but decrypt this time
    if CryptLoadFromFile(List, lpFileName, Pass) then
    ShowMessageFmt('%s%s', ['Decrypted' + CRLF + CRLF, List.Text]);
    end;
    finally
    FreeAndNil(List);
    end;
end;

--Iconic
Post Reply