Recent

Author Topic: <solved>Easy encryption of text files... Code added 16052024  (Read 6425 times)

Sprek Skik

  • New Member
  • *
  • Posts: 21
  • Beginner Lazarus & Free Pascal
Re: Easy encryption of text files... Code added 16052024
« Reply #30 on: May 16, 2024, 08:24:27 pm »
Hi,
Compress and Decompress are optional, just for add complexity to the cryptage :)

You can also use:

Code: Pascal  [Select][+][-]
  1.  Memo1.Iines.Text := Encrypt(Memo1.Lines.Text, MyKey);
  2.  Memo1.Iines.Text := Decrypt(Memo1.Lines.Text, MyKey);
  3.  

B->

I tried to compile but error : notebewerker14.pas(468,9) Error: identifier idents no member "Iines"
Something inmy setup?

dsiders

  • Hero Member
  • *****
  • Posts: 1336
Re: Easy encryption of text files... Code added 16052024
« Reply #31 on: May 16, 2024, 08:26:59 pm »
Hi,
Compress and Decompress are optional, just for add complexity to the cryptage :)

You can also use:

Code: Pascal  [Select][+][-]
  1.  Memo1.Iines.Text := Encrypt(Memo1.Lines.Text, MyKey);
  2.  Memo1.Iines.Text := Decrypt(Memo1.Lines.Text, MyKey);
  3.  

B->

I tried to compile but error : notebewerker14.pas(468,9) Error: identifier idents no member "Iines"
Something inmy setup?

Do you know the difference between the letter "I" and the letter "L"?
Preview the next Lazarus documentation release at: https://dsiders.gitlab.io/lazdocsnext

Sprek Skik

  • New Member
  • *
  • Posts: 21
  • Beginner Lazarus & Free Pascal
Re: Easy encryption of text files... Code added 16052024
« Reply #32 on: May 16, 2024, 09:06:04 pm »
Hi,
Compress and Decompress are optional, just for add complexity to the cryptage :)

You can also use:

Code: Pascal  [Select][+][-]
  1.  Memo1.Iines.Text := Encrypt(Memo1.Lines.Text, MyKey);
  2.  Memo1.Iines.Text := Decrypt(Memo1.Lines.Text, MyKey);
  3.  

B->

I tried to compile but error : notebewerker14.pas(468,9) Error: identifier idents no member "Iines"
Something inmy setup?

Do you know the difference between the letter "I" and the letter "L"?

You are right I didn't look .....
But what is more important it works!!!
Thanks for the correct remark about I!

Sprek Skik

  • New Member
  • *
  • Posts: 21
  • Beginner Lazarus & Free Pascal
Re: Easy encryption of text files... Code added 16052024
« Reply #33 on: May 16, 2024, 10:40:52 pm »
Hi,
Compress and Decompress are optional, just for add complexity to the cryptage :)

You can also use:

Code: Pascal  [Select][+][-]
  1.  Memo1.Iines.Text := Encrypt(Memo1.Lines.Text, MyKey);
  2.  Memo1.Iines.Text := Decrypt(Memo1.Lines.Text, MyKey);
  3.  

B->

Thanks for your code I used the simple solution without compression.
My project is almost finished...
grtz Sprek Skik

Dzandaa

  • Sr. Member
  • ****
  • Posts: 407
  • From C# to Lazarus
Re: <solved>Easy encryption of text files... Code added 16052024
« Reply #34 on: May 17, 2024, 09:56:47 am »
Hi
@Sprek Skik

Thank you too.

B->
Regards,
Dzandaa

Sprek Skik

  • New Member
  • *
  • Posts: 21
  • Beginner Lazarus & Free Pascal
Re: <solved>Easy encryption of text files... Code added 16052024
« Reply #35 on: May 19, 2024, 02:08:14 pm »
Hi
@Sprek Skik

Thank you too.

B->

In another program I used your code with compress. This also works perfect! Thanks for your help with encryption.
I don't know very much of Lazarus so I am very happy with the result. It's difficult to find specific code when something doesn't work. I also make use of Google's Gemini but this AI program has some troubles with Lazarus.

grtz Sprek

Dzandaa

  • Sr. Member
  • ****
  • Posts: 407
  • From C# to Lazarus
Re: <solved>Easy encryption of text files... Code added 16052024
« Reply #36 on: May 19, 2024, 04:13:13 pm »
Hi

@Sprek Skik

I'm glad my code was helpful.

This forum is very dynamic and there is almost always someone to find a solution :)

I've programmed in a lot of languages, unfortunately,
I've only known Lazarus for two years,
I naively thought that Pascal was just a teaching language.

But no, it's a solid, cross-platform windowed language.

The documentation is a bit lacking, but the forum is very responsive.

To try it is to adopt it:)

Have a nice day.

B->
Regards,
Dzandaa

Thaddy

  • Hero Member
  • *****
  • Posts: 16516
  • Kallstadt seems a good place to evict Trump to.
Re: <solved>Easy encryption of text files... Code added 16052024
« Reply #37 on: June 07, 2024, 09:43:31 am »
I have expanded my previous replies somewhat with a simple class where you can override the encryption algorithm to taste.
it works with any stream. About the simplest I could achieve with binary compatibility between platforms Win and Lin:
Code: Pascal  [Select][+][-]
  1. unit cryptstreams;
  2. { A simple encryption/decryption stream based on a pseudo random
  3.   number generator, PRNG for short.
  4.   We use a Linear Congruential Generator, LCG for short.
  5.   This makes use of the deterministic nature of PRNG's, meaning that,
  6.   given a known seed, the sequence is always the same, while
  7.   approaching equi-distribution in its outcome. The possibility to
  8.   use cycles, strongly improves the crypt quality: i.e, five cycles is
  9.   mathematically almost unbreakable without knowledge of:
  10.   - Key, which is the random seed in the range of a Cardinal.
  11.   - Cycles, how many times the crypt is run over the same data.
  12.   - The algorithm used to crypt/decrypt.
  13.  
  14.   Here I have used a very simple and fast PRNG, but the encryption
  15.   function can be overriden with your algorithm of choice without
  16.   affecting the functionality of the the class.
  17.  
  18.   Encryption is limited to memory size, but you can also implement this
  19.   using a class derived from TFileStream instead without many changes.
  20.   The most important part is just the WriteByte function and that works
  21.   with any stream.
  22.  
  23.   There is some more explanation in the sourcecode below.
  24.  
  25.   Enjoy,
  26.  
  27.   Thaddy de Koning.
  28.  
  29.   NO license, use as you like.
  30.   (C)1998-2024 Thaddy de Koning
  31.   (I used the idea first in 1998, not as a class,
  32.    but as a function )}
  33.  
  34.  
  35.  
  36. {$mode objfpc}{$H+}
  37. interface
  38. uses
  39.   classes;
  40.  
  41. type
  42. {$if not declared(Tbytes)}
  43.   TBytes = array of byte;
  44. {$ifend}
  45.  
  46.   TSimpleStreamCrypter = class(TMemoryStream)
  47.   strict private
  48.     FKey,
  49.     FCycles:Cardinal;
  50.     FInStream:TStream;
  51.     FLoaded:Boolean;
  52.     function GetBytes:TBytes;inline;
  53.   strict protected
  54.     { Writes a byte, encrypts immediately on write.
  55.       You can override this with a different encryption algorithm }
  56.     procedure WriteByte(aByte:Byte);virtual;
  57.     procedure LoadFromStream(Stream:TStream);
  58.   public
  59.     constructor Create(InStream:TStream;Key:Cardinal;Cycles:cardinal = 5);virtual;overload;
  60.     property Bytes:TBytes read GetBytes;
  61.   end;
  62.  
  63. implementation
  64.  
  65.   constructor TSimpleStreamCrypter.Create(InStream:TStream;Key:Cardinal;Cycles:cardinal);
  66.   begin
  67.     inherited create;
  68.     FLoaded := False;
  69.     FInStream := InStream;
  70.     FKey := Key;
  71.     FCycles := Cycles;
  72.     Size:=InStream.Size;
  73.     LoadFromStream(InStream);
  74.   end;
  75.  
  76.   function TSimpleStreamCrypter.GetBytes:TBytes;
  77.   begin
  78.      Result := [];
  79.      SetLength(Result,Size);
  80.      move(PByte(memory)[0],Result[0],Size);  
  81.   end;
  82.  
  83.   { If you distrust the LCG, you can override this with
  84.     another PRNG, but since we use 5 cycles as default,
  85.     the resulting encryption is very, very strong.
  86.     If you test with chi squared (.5) you will find almost
  87.     perfect equi-distribution over 5 cycles and 1000 probes
  88.     with different keys. That means it is pretty much unbreakable
  89.     without the knowledge of key, cycles and prng. }
  90.   procedure TSimpleStreamCrypter.WriteByte(aByte:Byte);
  91.   begin
  92.     { This is an LCG, actually the same as Delphi's Random }
  93.     FKey := FKey * 134775813 { is prime, do not change }  + 1;
  94.     inherited WriteByte(aByte xor (FKey * 256 shr 32));
  95.   end;
  96.  
  97.   procedure TSimpleStreamCrypter.LoadFromStream(Stream:TStream);
  98.   var
  99.     i,j:integer;
  100.     b:Byte;
  101.   begin
  102.     { freshen up first }
  103.     clear;
  104.     { We only need to read the first cycle from the instream
  105.       Our stream is then already encrypted for one cycle }
  106.     if not Floaded then
  107.     begin
  108.       Stream.Seek(0,0);
  109.       for j:= 0 to Stream.Size -1 do
  110.       { encryption is byte wise and in-place }
  111.         WriteByte(Stream.ReadByte);
  112.       { flag the first encryption round }
  113.       FLoaded := True;
  114.       { Keep track of the cycles }
  115.       Dec(FCycles);
  116.     end;
  117.     { After that, we can cycle over our own data }    
  118.     for i:= 0 to FCycles-1 do
  119.     begin
  120.       Seek(0,0);
  121.       for j:= 0 to Size -1 do
  122.       begin
  123.         b:= ReadByte;
  124.         { Go back to where we were, because ReadByte advanced
  125.           the stream by one }
  126.         Seek(-1,soFromCurrent);
  127.         { Overwrite with new value }
  128.         WriteByte(b);
  129.       end;
  130.     end;
  131.   end;
  132.  
  133. end.
  134.  
Small example:
Code: Pascal  [Select][+][-]
  1. program testcryptstreams;
  2. {$mode objfpc}{$H+}{$codepage utf8}
  3. uses
  4.   sysutils, classes, cryptstreams,CryptRandom;
  5. var
  6.   Crypt:TSimpleStreamCrypter;
  7.   Instream:TStream;
  8.   S:UnicodeString = 'This is thè téxt to êncrypt/decrypt Ä.';
  9. begin
  10.   { Encrypt a stream. With strings, the encoding is important
  11.     to allow cross-platform crypt and binary compatibility. }
  12.   InStream := TStringStream.Create(S, Tencoding.Unicode);
  13.   try
  14.     Crypt:=TSimpleStreamCrypter.Create(InStream,12345);
  15.     try
  16.       S:=Crypt.Bytes;
  17.       writeln(S);
  18.     finally
  19.       Crypt.Free;
  20.     end;
  21.   finally
  22.     InStream.Free;
  23.   end;
  24.   { Decrypt the stream: same code }
  25.   InStream := TStringStream.Create(S,Tencoding.Unicode);
  26.   try
  27.     Crypt:=TSimpleStreamCrypter.Create(InStream,12345);
  28.     try
  29.       S:=Crypt.Bytes;
  30.       writeln(S);
  31.     finally
  32.       Crypt.Free;
  33.     end;
  34.   finally
  35.     InStream.Free;
  36.   end;
  37.   Readln;
  38. end.
needed operators for the example, as well as the original function:
Code: Pascal  [Select][+][-]
  1. {
  2.   This unit implements strong and very fast encryption/decrytion,
  3.   It is based on a pseudo random number generator (PRNG) where the
  4.   random seed is used as the key/pass. PRNG's produce repeatable
  5.   sequences given the same random seed. The values are equidistributed
  6.   over the domain, though.( tested chi squared )
  7.   To successfully attack this method of encryption you will need three things:
  8.   - knowledge of the key
  9.   - knowledge of the prng
  10.   - knowledge of the number of cycles
  11.   Any weakness is in the prng used, but offset by the number of cycles.
  12.   Encryption is symmetric: the same crypt routine encrypts and decrypts.
  13.   The encryption becomes stronger when the number of cycles is increased.
  14.  
  15.   Completely rewritten using modern object pascal features.
  16.   Prng is still the same.
  17.  
  18.   (c) 1998 - 2024, Thaddy de Koning. Use as you like, not licensed.
  19. }
  20. unit cryptrandom;
  21. {$mode objfpc}{$modeswitch advancedrecords}
  22. interface
  23. uses
  24.   {$ifdef unix}cwstring,{$endif}sysutils;
  25.  
  26.   function Crypt(const Data:TBytes;Key:Cardinal;Cycles:Cardinal=1):TBytes;inline;
  27.  
  28.   { convenience operators for string types to TBytes and back }
  29.   operator := (const a:ShortString):TBytes;inline;
  30.   operator := (const a:AnsiString):TBytes;inline;
  31.   operator := (const a:UTF8String):TBytes;inline;
  32.   operator := (const a:WideString):Tbytes;
  33.   operator := (const a:UnicodeString):Tbytes;
  34.  
  35.   operator := (const a:TBytes):ShortString;inline;
  36.   operator := (const a:TBytes):AnsiString;inline;
  37.   operator := (const a:TBytes):UTF8String;inline;
  38.   operator := (const a:Tbytes):WideString;inline;
  39.   operator := (const a:TBytes):UnicodeString;inline;
  40.  
  41. implementation
  42.  
  43.   function Crypt(const Data:TBytes;Key:Cardinal;Cycles:Cardinal=1):TBytes;inline;
  44.   var
  45.     i,j:integer;
  46.    begin
  47.     Result := [];
  48.     Setlength(Result, Length(Data));
  49.     For i:= 0 to Pred(Cycles) do
  50.       for j:= 0 to high(Data) do
  51.       begin
  52.         { this is the lcg type prng }
  53.         Key := Key * 134775813  + 1;
  54.         Result[j] := Data[j] xor (Key * 256 shr 32);
  55.       end;
  56.   end;
  57.    
  58.   operator := (const a:ShortString):TBytes;inline;
  59.   var
  60.     T:UTF8String;
  61.   begin
  62.     T:= a;
  63.     Result:=BytesOf(T);
  64.   end;
  65.  
  66.   operator := (const a:AnsiString):TBytes;inline;
  67.   begin
  68.     Result := BytesOf(a);
  69.   end;
  70.  
  71.   operator := (const a:UTF8String):TBytes;inline;
  72.   begin
  73.     Result := BytesOf(a);
  74.   end;
  75.  
  76.   operator := (const a:WideString):Tbytes;inline;
  77.   begin
  78.     Result := WideBytesOf(a);
  79.   end;
  80.  
  81.    
  82.   operator := (const a:UnicodeString):TBytes;inline;
  83.   begin
  84.     Result := WideBytesOf(a);
  85.   end;
  86.  
  87.   operator := (const a:TBytes):ShortString;inline;
  88.   begin
  89.     SetString(Result,PAnsiChar(a),Length(a));
  90.   end;
  91.  
  92.   operator := (const a:TBytes):AnsiString;inline;
  93.   begin
  94.     SetString(Result,PAnsiChar(a),length(a));
  95.   end;
  96.  
  97.   operator := (const a:TBytes):UTF8String;inline;
  98.   begin
  99.     SetString(Result,PAnsiChar(a),length(a));
  100.   end;
  101.  
  102.   operator := (const a:Tbytes):WideString;
  103.   begin
  104.     Result := WideStringOf(a);
  105.   end;
  106.    
  107.   operator := (const a:TBytes):UnicodeString;inline;
  108.   begin
  109.     Result := WideStringOf(a)
  110.   end;
  111.  
  112. {$ifndef unix}
  113. initialization
  114. {
  115.   This is for binary compatibility of shortstring and ansistring
  116.   between Windows and Linux.
  117.   NOT for display purposes, that depends on your console/terminal.
  118. }
  119.    SetMultiByteConversionCodePage(CP_UTF8);
  120. finalization
  121.    SetMultiByteConversionCodePage(CP_ACP);
  122. {$endif}
  123. end.

Remarks:
- This encryption is very fast
- Using cycles, it is stronger than any suggested (at the cost of some speed, of course )
- Firmly founded in theory.
- You can override the encryption scheme.

I hope this code is understandable even for beginners.
(plz note my windows console is configured as utf8. does not affect binary level)




« Last Edit: June 07, 2024, 10:19:02 am by Thaddy »
But I am sure they don't want the Trumps back...

Thaddy

  • Hero Member
  • *****
  • Posts: 16516
  • Kallstadt seems a good place to evict Trump to.
Re: <solved>Easy encryption of text files... Code added 16052024
« Reply #38 on: June 07, 2024, 11:38:35 am »
my previous post is about streams, but the core function is of course just this;
Code: Pascal  [Select][+][-]
  1.   function Crypt(const Data:TBytes;Key:Cardinal;Cycles:Cardinal=1):TBytes;inline;
  2.   var
  3.     i,j:integer;
  4.    begin
  5.     Result := [];
  6.     Setlength(Result, Length(Data));
  7.     For i:= 0 to Pred(Cycles) do
  8.       for j:= 0 to high(Data) do
  9.       begin
  10.         { this is the lcg type prng }
  11.         Key := Key * 134775813  + 1;
  12.         Result[j] := Data[j] xor (Key * 256 shr 32);
  13.       end;
  14.   end;

i recommend to use streaming, though.
But I am sure they don't want the Trumps back...

 

TinyPortal © 2005-2018