Skip to content

Instantly share code, notes, and snippets.

@artem78
Created September 12, 2024 11:08
Show Gist options
  • Save artem78/3d6b02314cd1a85f5036fa05aa7c00a7 to your computer and use it in GitHub Desktop.
Save artem78/3d6b02314cd1a85f5036fa05aa7c00a7 to your computer and use it in GitHub Desktop.
Store encrypted values in INI file
program EncryptedIni;
{$mode objfpc}{$H+}
uses
Classes, SysUtils, IniFiles, BlowFish, base64;
type
{ TIniFileEx }
TIniFileEx = class(TIniFile)
private
function EncryptString(aString: string): string;
function DecryptString(aString: string): string;
public
EncryptionKey: String;
function ReadEncryptedString(const Section, Ident, Default: string): string;
procedure WriteEncryptedString(const Section, Ident, Value: String);
end;
var
Ini: TIniFileEx;
{ TIniFileEx }
// Source: https://www.tweaking4all.com/forum/delphi-lazarus-free-pascal/lazarus-how-to-quick-and-easy-encrypt-and-decrypt-text-with-blowfish/
function TIniFileEx.EncryptString(aString: string): string;
var
EncrytpStream:TBlowFishEncryptStream;
StringStream:TStringStream;
EncryptedString:string;
begin
StringStream := TStringStream.Create('');
EncrytpStream := TBlowFishEncryptStream.Create(EncryptionKey, StringStream);
EncrytpStream.WriteAnsiString(aString);
EncrytpStream.Free;
EncryptedString := StringStream.DataString;
StringStream.Free;
EncryptString := EncodeStringBase64(EncryptedString);
end;
// Source: https://www.tweaking4all.com/forum/delphi-lazarus-free-pascal/lazarus-how-to-quick-and-easy-encrypt-and-decrypt-text-with-blowfish/
function TIniFileEx.DecryptString(aString: string): string;
var
DecrytpStream:TBlowFishDeCryptStream;
StringStream:TStringStream;
DecryptedString:string;
begin
StringStream := TStringStream.Create(DecodeStringBase64(aString));
DecrytpStream := TBlowFishDeCryptStream.Create(EncryptionKey, StringStream);
DecryptedString := DecrytpStream.ReadAnsiString;
DecrytpStream.Free;
StringStream.Free;
DecryptString := DecryptedString;
end;
function TIniFileEx.ReadEncryptedString(const Section, Ident, Default: string
): string;
begin
Result := DecryptString(ReadString(Section, Ident, Default));
end;
procedure TIniFileEx.WriteEncryptedString(const Section, Ident, Value: String);
begin
WriteString(Section, Ident, EncryptString(Value));
end;
const
Sect = 'general';
begin
Ini := TIniFileEx.Create('config.ini');
Ini.EncryptionKey := 'MY_SECRET_KEY';
Ini.WriteEncryptedString(Sect, 'password', '123456');
WriteLn('password: ', Ini.ReadEncryptedString(Sect, 'password', ''));
WriteLn('password stored in INI: ', Ini.ReadString(Sect, 'password', ''));
FreeAndNil(Ini);
readln;
end.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment