Recent

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

Sprek Skik

  • New Member
  • *
  • Posts: 21
  • Beginner Lazarus & Free Pascal
I Have made a Notebook program. It makes Txt files. But it would be nice to make some sort of encryption. It gives more privacy in my opinion. I have been looking for it sometime, but my attempt to install encrypt has failed. Can someone give me a suggestion?

Added Some Code 16052024

I Made the following Code:

procedure TfrmNoteBewerker.EncryptMemo;
var
  i: integer;
  Cipher: TDCP_rc4;
begin
  CheckEncoding;
  Cipher:= TDCP_rc4.Create(Self);
  Cipher.InitStr(KeyStr,TDCP_sha1);         // initialize the cipher with a hash of the passphrase
  for i:= 0 to Memo1.Lines.Count-1 do       // decrypt the contents of the memo
    begin
      if Memo1.Lines <> '' then
        Memo1.Lines:= Cipher.EncryptString(Memo1.Lines);
    end;
    Cipher.Burn;
    Cipher.Free;

end;
       

De code is not really working as expected. So on advice from Gemini I made a procedure Check Unicode but it can not compile:

procedure TfrmNoteBewerker.CheckEncoding;
var
  MemoEncoding, KeyStrEncoding: TEncoding;
begin
  {
  // Check Memo1 encoding
  MemoEncoding := Memo1.Lines.Strings[0].Encoding; // Get encoding of the first line

  // Check KeyStr encoding (assuming it's a string variable)
  KeyStrEncoding := KeyStr.Encoding;

  if MemoEncoding <> KeyStrEncoding then
  begin
    // Encodings are different, handle the conversion
    WriteLn('Warning: Memo and KeyStr encodings differ!');
    // Choose a common encoding (e.g., UTF-8)
    TargetEncoding := TEncoding.UTF8;
    Memo1.Lines.Strings[0].Encoding := TargetEncoding; // Convert first line encoding
    KeyStr := TargetEncoding.GetString(KeyStr); // Convert KeyStr encoding
  end;
  }
end;
« Last Edit: May 16, 2024, 10:43:04 pm by Sprek Skik »

Handoko

  • Hero Member
  • *****
  • Posts: 5290
  • My goal: build my own game engine using Lazarus

KodeZwerg

  • Hero Member
  • *****
  • Posts: 2269
  • Fifty shades of code.
    • Delphi & FreePascal
Re: Easy encryption of text files... Help/Info needed
« Reply #2 on: May 14, 2024, 08:54:39 am »
my attempt to install encrypt has failed
I am unsure what that means but use what Lazarus brings at installation, compression! Its a different kind of encryption with advantage to be smaller than the input was, but that depend on input.
Next mostest easiest "encryption" = Base-Encoded, that format is often used in telecommunication to transfer binary files to ascii-encrypted.
You can also combine one with another, or simply open a browser, there are many basics about encryption explained via wiki.
« Last Edit: Tomorrow at 31:76:97 xm by KodeZwerg »

Thaddy

  • Hero Member
  • *****
  • Posts: 15557
  • Censorship about opinions does not belong here.
Re: Easy encryption of text files... Help/Info needed
« Reply #3 on: May 14, 2024, 03:03:44 pm »
Oh, well,

Having some fun with randoms looks always good to me:
This code makes use of the predictability and repeatability of a PseudoRandom Number Generator. Actually any PRNG, but you do not want to ruin the system.randseed, so I use a separate random. Principle is the same:
Code: Pascal  [Select][+][-]
  1. program cryptrandom;
  2. {$mode objfpc}{$modeswitch typehelpers}{$H+}
  3. { This is demo that you can actually use random to encrypt/decrypt.
  4.   This is due to the nature of a Pseudo Random Number Generator,
  5.   where given a certain random seed, the sequence is predictable.
  6.   Here I use the Random Seed as a key to encrypt/decrypt a string.
  7.   The same code would also work with the Default random from FreePascal,
  8.   but it is better not to touch system.randseed, So I used a different
  9.   Random.
  10.  
  11.   Have fun, Thaddy}
  12. uses
  13. { The unit is based on my
  14.   https://wiki.freepascal.org/Delphi_compatible_LCG_Random
  15.   but I adapted it, so will add it below}
  16. lcg_random2;
  17.  
  18.  
  19. function Crypt(const value:AnsiString;const Key:Cardinal):AnsiString;
  20. var
  21.   i:integer;
  22. begin
  23.   RandSd := Key;
  24.   SetLength(Result,Length(Value));
  25.   for i := 1 to length(Value) do
  26.     Result[i] := Chr(Ord(Value[i]) xor lcgrandom(255));
  27. end;
  28.  
  29. var
  30.  a:AnsiString;
  31. begin
  32.  a:='This is the text to encrypt/decrypt.';
  33.  writeln(a);
  34.  writeln('Encrypting..');
  35.  a:=Crypt(a, 12345);
  36.  writeln(a);
  37.  writeln('Decrypting..');
  38.  a:=Crypt(a, 12345);
  39.  writeln(a);
  40. end.
Of course this is not hack safe, but:
- You have to know the Random generator that is used
- You have to know the Key. The Key is a numeric value in the range of cardinal.
- It is way better than XOR!
- It is also much simpler than XOR!, although it uses XOR the key is derived from the randseed.

Have fun!
Code: Pascal  [Select][+][-]
  1. // adapted version of my wiki entry with RandSeed factored out
  2. unit lcg_random2;
  3. // Delphi compatible LCG random number generator routines for Freepascal.
  4. // (c)2017, Thaddy de Koning. Use as you like
  5. // Algorithm, Delphi multiplier and increment taken from:
  6. // https://en.wikipedia.org/wiki/Linear_congruential_generator
  7. // The default Delphi RandomSeed is determined as zero.
  8. {$ifdef fpc}{$mode objfpc}{$endif}{$J+}
  9.  
  10. interface
  11. const
  12.   RandSd:cardinal = 0;
  13.  
  14. function LCGRandom: extended; overload;inline;
  15. function LCGRandom(const range:longint):longint;overload;inline;
  16.  
  17. implementation
  18.  
  19. function IM:cardinal;inline;
  20. begin
  21.   RandSd := RandSd * 134775813  + 1;
  22.   Result := RandSd;
  23. end;
  24.  
  25. function LCGRandom: extended; overload;inline;
  26. begin
  27.   Result := IM * 2.32830643653870e-10;
  28. end;
  29.  
  30. function LCGRandom(const range:longint):longint;overload;inline;
  31. begin
  32.   Result := IM * range shr 32;
  33. end;
  34.  
  35. end.

[edit]
I added this code to the wiki too, since I think it is a good example for PRNG behavior.


« Last Edit: May 14, 2024, 06:24:00 pm by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

Thaddy

  • Hero Member
  • *****
  • Posts: 15557
  • Censorship about opinions does not belong here.
Re: Easy encryption of text files... Help/Info needed
« Reply #4 on: May 14, 2024, 04:54:19 pm »
Technical detail:
Periodicity for this particular random encryption is 2^32 and is not vulnarable to frequency analysis, unlike xor.

Frequency analysis is also fun. Will write a simple example for that too:
Basically any natural language has a bias to certain characters. If you know that bias you can easily calculate the mean and the standard deviation to determine the likelyhood what a certain encrypted character actually is most likely. This works pretty good! And simple to do.

You can make it pretty much unbreakable with cycles:
Code: Pascal  [Select][+][-]
  1. function Crypt(const value:AnsiString;const Key:Cardinal;cycles:integer = 100):AnsiString;
  2. var
  3.   c,i:integer;
  4. begin
  5.   RandSd := Key;
  6.   SetLength(Result,Length(Value));
  7.   for c:= 1 to cycles do
  8.   begin
  9.     for i := 1 to length(Value) do
  10.     Result[i] := Chr(Ord(Value[i]) xor lcgrandom(255));
  11.   end;
  12. end;

I just love PRNG's, as most people know.
[edit] chatGPT is working on the above, but as yet no result for weakness....


« Last Edit: May 14, 2024, 06:32:52 pm by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

cdbc

  • Hero Member
  • *****
  • Posts: 1499
    • http://www.cdbc.dk
Re: Easy encryption of text files... Help/Info needed
« Reply #5 on: May 14, 2024, 05:34:12 pm »
Hi
Thanks Thaddy, very 'nifty' piece of code, Me Likey  8-)
Regards Benny
If it ain't broke, don't fix it ;)
PCLinuxOS(rolling release) 64bit -> KDE5 -> FPC 3.2.2 -> Lazarus 2.2.6 up until Jan 2024 from then on it's: KDE5/QT5 -> FPC 3.3.1 -> Lazarus 3.0

bobby100

  • Full Member
  • ***
  • Posts: 245
    • Malzilla
Re: Easy encryption of text files... Help/Info needed
« Reply #6 on: May 14, 2024, 06:43:04 pm »
@Thaddy
I've seen professional products using XOR (encoded data is in 100Mb to 200Mb size-range, and need to be processed in real-time on a 266MHz ARM device on Windows CE):
- Key (XOR table) is 4kb in size (2D array)
- after decoding the first 4kb of data, for the next 4kb of data to be decrypted you need to use offset on the XOR key table (use 2nd array row as first, use first row at the end). Every next 4kb data block needs another offset shift.

Another encryption where I have had fun "learning it", was also XOR, but no key was used except for one byte. Encryption was based on the character position in the stream and on the value of the previous character.
At decrypting - if you do it wrong for one single char - the rest of the sequence will be wrong.
Does not work well for variable-length encoding without extra code, but works fine for ASCII.

Personally, I also use XOR with very long keys - good luck with frequency analysis here.
Note to the other developers - do not keep the keys in plain form in your binaries (hint: Xing and DeCSS)

Thaddy

  • Hero Member
  • *****
  • Posts: 15557
  • Censorship about opinions does not belong here.
Re: Easy encryption of text files... Help/Info needed
« Reply #7 on: May 14, 2024, 07:32:25 pm »
XOR alone is not very good with any key length, but my example shows you can improve on it.
That is basically what the new FPC generator does, but instead of Xoshiro128** - only in trunk- which is of the xorshift family of prng's I use a simpler prng.
This is over-simplified. If you know the prng it is easy to hack, even with multiple rounds, but not by the average 14 year old kid  :D (who can hack XOR!)
The reason why I showed these examples is also to show PRNG's are predictable if the seed is known, so I used the seed as a key. If you don't know the key?, good luck ltitle 14 year old... If you don't know the PRNG? just as well. This scheme is only hackable by pro's, but it is hackable. Needs a lot of processing power, though.
But it is mathematically better than simple xor with any key length.
(And to show Pascal Random can be used for encryption and decription with the same function)

Hey, I just wrote it for fun and to explain something about one of my favorite passtimes: PRNG's!
PRNG's are very important for statistics. BTW the same code works with Freepascal's PRNG's, both the mersenne twister in 2.0 to 3.2.2 or the new one.
Demo screws up the rand seed, so if you rely on random, call randomize. 8-) But then you need to hack it... cause calling randomize screws up predicatbility.. can you still follow me ?  ;D ;)
Code: Pascal  [Select][+][-]
  1. program cryptrandomwithdefaults;
  2. { using FPC's default random }
  3. {$mode objfpc}{$modeswitch typehelpers}{$H+}
  4. function Crypt(const value:AnsiString;Key:Cardinal):AnsiString;
  5. var
  6.   c,i:integer;
  7. begin
  8.   RandSeed := Key;
  9.   SetLength(Result,Length(Value));
  10.   for c:= 1 to random(255) do
  11.   begin
  12.     for i := 1 to length(Value) do
  13.       Result[i] := Chr(Ord(Value[i]) xor random(255));
  14.   end;
  15. end;
  16.  
  17. var
  18.  a:AnsiString;
  19. begin
  20.  a:='This is the text to encrypt/decrypt.';
  21.  writeln(a);
  22.  writeln('Encrypting..');
  23.  a:=Crypt(a,54321);
  24.  writeln(a);
  25.  writeln('Decrypting..');
  26.  a:=Crypt(a, 54321);
  27.  writeln(a);
  28. end.
Don't do that in your own code, because system.randseed is reset...
This will work with 3.2.2, the mersenne twister, ot trunk, with xorhiro128**
« Last Edit: May 14, 2024, 09:41:53 pm by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

Thaddy

  • Hero Member
  • *****
  • Posts: 15557
  • Censorship about opinions does not belong here.
Re: Easy encryption of text files... Help/Info needed
« Reply #8 on: May 14, 2024, 10:11:44 pm »
I hope, more in general, that the core devlopers really understand that changing the prng is not really smart, because code encrypted like this is not compatible between 3.2.2 and trunk.
This only worls - my first example - because I purposely introduced a separate PRNG.
If I smell bad code it usually is bad code and that includes my own code.

bobby100

  • Full Member
  • ***
  • Posts: 245
    • Malzilla
Re: Easy encryption of text files... Help/Info needed
« Reply #9 on: May 14, 2024, 10:17:00 pm »
I fully understand your point. I just wanted to say that "XORing" isn't really useless.

I do not know much about generating random numbers. The last article I've read on that was about Pentium IV's integrated random number generator, who was generating numbers according to the temperature fluctuations inside the CPU. I really do not know much about this topic.

Thaddy

  • Hero Member
  • *****
  • Posts: 15557
  • Censorship about opinions does not belong here.
Re: Easy encryption of text files... Help/Info needed
« Reply #10 on: May 14, 2024, 10:53:46 pm »
And just that is the difference between a PRNG and true random. In the case of true random my code would not work.
If I smell bad code it usually is bad code and that includes my own code.

Thaddy

  • Hero Member
  • *****
  • Posts: 15557
  • Censorship about opinions does not belong here.
Re: Easy encryption of text files... Help/Info needed
« Reply #11 on: May 15, 2024, 06:37:10 am »
BTW I would not use the last example myself: as I wrote before, but implicitly, if you use the default Random, basically the crypt code claims the random generator all for itself. If you use the random generator elsewhere in your code there can be unwanted side effects. So I have to protect you.
One of the reasons I used a custom random in the first place, but to make the code really safe, the random generator needs to be inaccessible to other code.
You also can not use class methods for this. Although I demonstrated the priniciple, which is correct, to actually use it we need a stronger separation from other code.
As usual, I dreamt, literally...
Will fix the flaw. It will be either an advanced record or a class.
« Last Edit: May 15, 2024, 07:23:30 am by Thaddy »
If I smell bad code it usually is bad code and that includes my own code.

Khrys

  • Jr. Member
  • **
  • Posts: 82
Re: Easy encryption of text files... Help/Info needed
« Reply #12 on: May 15, 2024, 07:46:53 am »
Quote
XOR alone is not very good with any key length

If the key is both longer than the data and truly random, then XOR alone is indeed enough to make the encryption unbreakable, as it forms a one-time pad (OTP): https://en.wikipedia.org/wiki/One-time_pad

KodeZwerg

  • Hero Member
  • *****
  • Posts: 2269
  • Fifty shades of code.
    • Delphi & FreePascal
Re: Easy encryption of text files... Help/Info needed
« Reply #13 on: May 15, 2024, 12:34:46 pm »
Interesting way of doing @Thaddy
IKR that what I now suggest would be against your code but I'll suggest to make it a class, internal work with TStream, at end or start add a fixed size hash generated from password/passkey so the class could quick abort decryption or output some other kind of data ....
« Last Edit: Tomorrow at 31:76:97 xm by KodeZwerg »

Fibonacci

  • Sr. Member
  • ****
  • Posts: 453
  • Internal Error Hunter
Re: Easy encryption of text files... Help/Info needed
« Reply #14 on: May 15, 2024, 02:55:52 pm »
Just uploaded ChaCha20 implementation for FPC, super simple to use:
https://github.com/fibodevy/fpc-chacha20/blob/main/chacha20.pas

Code: Pascal  [Select][+][-]
  1. program example;
  2.  
  3. uses chacha20;
  4.  
  5. var
  6.   s: string;
  7.   cc: chacha20state;
  8.  
  9. begin
  10.   // key should be 32 bytes, nonce 12 bytes
  11.   chacha20_init(cc, 'key', 'nonce');
  12.  
  13.   s := 'hello';
  14.   s := copy(s, 1, 999); // make string memory writable
  15.  
  16.   // encrypt
  17.   chacha20_xor(cc, @s[1], length(s));
  18.   writeln('encrypted = ', s);
  19.  
  20.   // decrypt
  21.   chacha20_set_counter(cc, 0);
  22.   chacha20_xor(cc, @s[1], length(s));
  23.   writeln('decrypted = ', s);
  24.  
  25.   readln;
  26. end.

Compatible with this PHP implementation to use on server side: https://github.com/lt/PHP-ChaCha20

 

TinyPortal © 2005-2018