Page 1 of 1
Forum

Welcome to the Tweaking4All community forums!
When participating, please keep the Forum Rules in mind!

Topics for particular software or systems: Start your topic link with the name of the application or system.
For example “MacOS X – Your question“, or “MS Word – Your Tip or Trick“.

Please note that switching to another language when reading a post will not bring you to the same post, in Dutch, as there is no translation for that post!



Share:
Notifications
Clear all

[Solved] Lazarus - How to quick and easy Encrypt and Decrypt text with BlowFish

1 Posts
1 Users
0 Reactions
8,059 Views
 Hans
(@hans)
Famed Member Admin
Joined: 12 years ago
Posts: 2859
Topic starter  

Sometimes you'd want to store sensitive info in for example a config file, Windows registry, or an INI file. In those cases you'd want to encrypt for example stored password.

Lazarus comes with a handy little tool for that called "BlowFish" and this is how you can use it.
In this example I created 2 functions, one to encrypt and one to decrypt - but feel free to use it in other ways.

First you will need to add BlowFish to your Uses clause, it's included with Lazarus and it's fast enough to encrypt or decrypt strings:

Uses BlowFish;

Next you can define functions like these, obviously the encryption and decryption keys need to be the same, and ... they need to be "secret".
You can call them like so:

myencryptedstring:=EncryptString('Hello');      // returns unreadable text
mydecryptedstring:=Decrypt(myencryptedstring); // returns 'Hello' function TForm1.EncryptString(aString:string):string;
var Key:string;
    EncrytpStream:TBlowFishEncryptStream;
    StringStream:TStringStream;
    EncryptedString:string;
begin
  Key := 'your_secret_encryption_key';
  StringStream := TStringStream.Create('');
  EncrytpStream := TBlowFishEncryptStream.Create(Key,StringStream);
  EncrytpStream.WriteAnsiString(aString);
  EncrytpStream.Free;
  EncryptedString := StringStream.DataString;
  StringStream.Free;
  EncryptString := EncryptedString;
end;
... function TForm1.DecryptString(aString:string):string;
var Key:string;
    DecrytpStream:TBlowFishDeCryptStream;
    StringStream:TStringStream;
    DecryptedString:string;
begin
  Key := 'your_secret_encryption_key';
  StringStream := TStringStream.Create(aString);
  DecrytpStream := TBlowFishDeCryptStream.Create(Key,StringStream);
  DecryptedString := DecrytpStream.ReadAnsiString;
  DecrytpStream.Free;
  StringStream.Free;
  DecryptString := DecryptedString;
end;                                

   
ReplyQuote
Share: