Recent

Author Topic: Encrypt a text (easily)  (Read 32284 times)

ezlage

  • Guest
Re: Encrypt a text (easily)
« Reply #15 on: June 17, 2016, 06:14:01 pm »
Use TFileStream instead of TMemo.
« Last Edit: June 17, 2016, 06:23:10 pm by ezlage »

rvk

  • Hero Member
  • *****
  • Posts: 6802
Re: Encrypt a text (easily)
« Reply #16 on: June 17, 2016, 06:14:39 pm »
Something like this:

Code: Pascal  [Select][+][-]
  1. uses BlowFish;
  2.  
  3. procedure EncryptAndWriteToFile(Filename: string; KeyPhrase: string; Value: string);
  4. var
  5.   en: TBlowFishEncryptStream;
  6.   s1: TFileStream;
  7. begin
  8.   s1 := TFileStream.Create(Filename, fmCreate or fmOpenReadWrite);
  9.   en := TBlowFishEncryptStream.Create(KeyPhrase, s1);
  10.   try
  11.     en.WriteAnsiString(Value);
  12.   finally
  13.     en.Free; // important to free en first (need for flush to s1)
  14.     s1.Free;
  15.   end;
  16. end;
  17.  
  18. function LoadFromFileAndDecrypt(Filename: string; KeyPhrase: string): string;
  19. var
  20.   de: TBlowFishDeCryptStream;
  21.   s1: TFileStream;
  22.   Value, temp: string;
  23. begin
  24.   Result := 'error';
  25.   s1 := TFileStream.Create(Filename, fmOpenRead);
  26.   de := TBlowFishDecryptStream.Create(KeyPhrase, s1);
  27.   try
  28.     Result := de.ReadAnsiString;
  29.   finally
  30.     s1.Free;
  31.     de.Free;
  32.   end;
  33. end;
  34.  
  35. procedure TForm1.Button1Click(Sender: TObject);
  36. var
  37.   Encrypted: string;
  38. begin
  39.   EncryptAndWriteToFile('C:\TEMP\TEST.TXT', '123', Memo1.Lines.Text);
  40. end;
  41.  
  42. procedure TForm1.Button2Click(Sender: TObject);
  43. begin
  44.   Memo2.Lines.Text := LoadFromFileAndDecrypt('C:\TEMP\TEST.TXT', '123');
  45. end;

SymbolicFrank

  • Hero Member
  • *****
  • Posts: 1315
Re: Encrypt a text (easily)
« Reply #17 on: June 17, 2016, 11:36:50 pm »
Any encryption can be broken, you rate the strength in the time it would take to do that.

And for many purposes a weak encryption is fine, if you discard and refresh it before it can possibly be broken. Just take a wide safety margin, because it might exist in that form for many years.

If you want to encrypt something in such a way that the encryption can never be broken, you're out of luck, and you only have a single option: a one-time pad. Which has a severe problem: how do you get that pad secretly to the receiving party? And even that will be breakable some time in the future.

Ericktux

  • Sr. Member
  • ****
  • Posts: 378
    • ericksystem software
Re: Encrypt a text (easily)
« Reply #18 on: March 07, 2017, 07:03:25 am »
hi my friends  :) , After time I share my progress.
Encrypt text and save it to inifile, then recover the decrypted text.

Code: Pascal  [Select][+][-]
  1. unit Unit1;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes,
  9.   SysUtils,
  10.   FileUtil,
  11.   Forms,
  12.   Controls,
  13.   Graphics,
  14.   Dialogs,
  15.   StdCtrls,
  16.   IniFiles,
  17.   BlowFish,  // necessary
  18.   base64;    // necessary
  19.  
  20. type
  21.  
  22.   { TForm1 }
  23.  
  24.   TForm1 = class(TForm)
  25.     Button1: TButton;
  26.     Button2: TButton;
  27.     Edit1: TEdit;
  28.     Edit2: TEdit;
  29.     Label1: TLabel;
  30.     Label2: TLabel;
  31.     procedure Button1Click(Sender: TObject);
  32.     procedure Button2Click(Sender: TObject);
  33.   private
  34.     { private declarations }
  35.   public
  36.     { public declarations }
  37.   end;
  38.  
  39. var
  40.   Form1: TForm1;
  41.  
  42. implementation
  43.  
  44. {$R *.lfm}
  45.  
  46. { TForm1 }
  47.  
  48. function encrypt(cle:string;chaine:string):string;
  49. var
  50.   en: TBlowFishEncryptStream;
  51.   de: TBlowFishDeCryptStream;
  52.   s1,s2: TStringStream;
  53.   value,temp: String;
  54. begin
  55.     s1 := TStringStream.Create('');
  56.     en := TBlowFishEncryptStream.Create(cle,s1);
  57.     en.WriteAnsiString(chaine);
  58.     en.Free;
  59.     result:=s1.datastring;
  60. end;
  61.  
  62. function decrypt(cle:string;chaine:string):string;
  63. var
  64.   en: TBlowFishEncryptStream;
  65.   de: TBlowFishDeCryptStream;
  66.   s1,s2: TStringStream;
  67.   value,temp: String;
  68. begin
  69.     s2 := TStringStream.Create(chaine);
  70.     de := TBlowFishDecryptStream.Create(cle,s2);
  71.     temp:=de.ReadAnsiString;
  72.     result:=temp;
  73. end;
  74.  
  75. // SAVE TEXT ENCRYPT IN INIFILE
  76. procedure TForm1.Button1Click(Sender: TObject);
  77. var
  78.   ini: TIniFile;
  79. begin
  80.   ini := TIniFile.Create('test.ini');
  81.   ini.WriteString('Section_Name1', 'Key_Name', EncodeStringBase64(encrypt('123',Edit1.Text)));
  82.   ini.Free;
  83. end;
  84.  
  85. // RECOVER TEXT DECRYPT FROM INIFILE
  86. procedure TForm1.Button2Click(Sender: TObject);
  87. var
  88.   ini: TIniFile;
  89.   res: string;
  90. begin
  91.   // Create INI Object and open or create file test.ini
  92. ini := TIniFile.Create('test.ini');
  93.   try
  94.     res := ini.ReadString('Section_Name1', 'Key_Name', 'default value');
  95.     Edit2.Text:=decrypt('123',DecodeStringBase64(res));
  96.   finally
  97.     ini.Free;
  98.   end;
  99. end;
  100.  
  101. end.

work fine :) :)
Attached project and image, regards.

« Last Edit: March 07, 2017, 07:05:11 am by Ericktux »
I love desktop software
https://www.ericksystem.com

Mr.Madguy

  • Hero Member
  • *****
  • Posts: 873
Re: Encrypt a text (easily)
« Reply #19 on: March 07, 2017, 08:59:21 am »
Of course real algorithms use better hash functions and random generators, but if you're interested, how real cyphers work, then they usually do something like that:
Code: Pascal  [Select][+][-]
  1. unit EncryptMain;
  2.  
  3. {$mode objfpc}{$H+}
  4.  
  5. interface
  6.  
  7. uses
  8.   Classes, SysUtils, FileUtil, Forms, Controls, Graphics, Dialogs, StdCtrls, md5;
  9.  
  10. type
  11.  
  12.   { TEncryptForm }
  13.  
  14.   TEncryptForm = class(TForm)
  15.     TestButton: TButton;
  16.     DecryptedEdit: TEdit;
  17.     EncryptedEdit: TEdit;
  18.     TextEdit: TEdit;
  19.     PasswordEdit: TEdit;
  20.     procedure TestButtonClick(Sender: TObject);
  21.   private
  22.     { private declarations }
  23.   public
  24.     { public declarations }
  25.   end;
  26.  
  27. var
  28.   EncryptForm: TEncryptForm;
  29.  
  30. implementation
  31.  
  32. {$R *.lfm}
  33.  
  34. type
  35.   TSeedUnion = packed record
  36.     case Boolean of
  37.       False:(Digest:TMD5Digest);
  38.       True:(Seed:Cardinal);
  39.   end;
  40.  
  41. function GenSeed(const APassword:UnicodeString):Cardinal;
  42.   var SeedUnion:TSeedUnion;
  43. begin
  44.   SeedUnion.Digest := MD5String(UTF8Encode(APassword));
  45.   Result := SeedUnion.Seed;
  46. end;
  47.  
  48. function Encrypt(const AString, APassword:UnicodeString):UnicodeString;
  49.   var I:Integer;
  50. begin
  51.   RandSeed := GenSeed(APassword);
  52.   SetLength(Result, Length(AString));
  53.   for I := 1 to Length(AString) do begin
  54.     Result[I] := WideChar(Word(AString[I]) xor Word(Random($10000)));
  55.   end;
  56. end;
  57.  
  58. { TEncryptForm }
  59.  
  60. procedure TEncryptForm.TestButtonClick(Sender: TObject);
  61. begin
  62.   EncryptedEdit.Text := UTF8Encode(
  63.     Encrypt(UTF8Decode(TextEdit.Text), UTF8Decode(PasswordEdit.Text))
  64.   );
  65.   DecryptedEdit.Text := UTF8Encode(
  66.     Encrypt(UTF8Decode(EncryptedEdit.Text), UTF8Decode(PasswordEdit.Text))
  67.   );
  68. end;
  69.  
  70. end.
  71.  

P.S. I'm Delphi programmer mostly. Is there some way to force String = UnicodeString or WideString to avoid this constant UTF8Decode/UTF8Encode, especially when performing some WinApi calls?
« Last Edit: March 07, 2017, 09:12:28 am by Mr.Madguy »
Is it healthy for project not to have regular stable releases?
Just for fun: Code::Blocks, GCC 13 and DOS - is it possible?

rvk

  • Hero Member
  • *****
  • Posts: 6802
Re: Encrypt a text (easily)
« Reply #20 on: March 07, 2017, 09:57:46 am »
Of course real algorithms use better hash functions and random generators, but if you're interested, how real cyphers work, then they usually do something like that:
Yikes !!! Don't use random in combination with encryption !

You're a Delphi programmer... You did read the following note in the Delphi documentation on Random??

Quote
Note: Because the implementation of the Random function may change between compiler versions, we do not recommend using Random for encryption or other purposes that require reproducible sequences of pseudo-random numbers.
http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/System_Random.html

I'm not sure if this would also be the case in FPC but the function is not called random for nothing. And implementation could change in the future.

So always make sure you use the same pseudo-random generator (and using the compiler version might not always be the same).

Thaddy

  • Hero Member
  • *****
  • Posts: 17414
  • Ceterum censeo Trumpum esse delendum (Tnx Charlie)
Re: Encrypt a text (easily)
« Reply #21 on: March 07, 2017, 11:23:08 am »
Hmm, RVK. Freepascal has a totally different implementation of Random than Delphi has and would be acceptable for simple encryption purposes. A Mersenne twister has a much higher period and passes more tests. This is on purpose.

See the manual http://www.freepascal.org/docs-html/rtl/system/random.html
"Remark:      The Free Pascal implementation of the Random routine uses the Mersenne Twister to simulate randomness. This implementation has a better statistical distribution than for example a Linear Congruential generator algorithm, but is considerably slower than the latter. If speed is an issue, then alternate random number generators should be considered."

If compatibility with Delphi is important then I can provide you with a Marsalia twister that's even better and gives -geven the same seed - the same results on Freepascal and Delphi.

Note that "Linear Congruential generator algorithm" is tongue in cheek for "Delphi's random sucks"... O:-) :P

« Last Edit: March 07, 2017, 11:29:33 am by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

rvk

  • Hero Member
  • *****
  • Posts: 6802
Re: Encrypt a text (easily)
« Reply #22 on: March 07, 2017, 11:29:47 am »
Hmm, RVK. Freepascal has a totally different implementation of Random than Delphi has and would be acceptable for simple encryption purposes. (Mersenne twister has a much higher period and passes more tests)
Yes, but the point is... will the random-function in FPC never change? Will it never deliver different numbers when beginning from the same randseed?

If you can guarantee that random numbers following a certain randseed will never change in FPC then, yes, you can use it.

For instance... the Random-documentation page of FPC has this:
Quote
Remark: The Free Pascal implementation of the Random routine uses the Mersenne Twister to simulate randomness. This implementation has a better statistical distribution than for example a Linear Congruential generator algorithm, but is considerably slower than the latter. If speed is an issue, then alternate random number generators should be considered.
Is it guaranteed that Random will always use the Mersenne Twister algoritme in the future?

If this can't be guaranteed you better create your own random-function according to a set algoritme which won't change.

Edit: Ah, my post crossed your edit. My point still remains. Make sure your Random-function is based on the SAME algoritme when you used it to encrypt. And document this clearly so when you get a new version of the compiler you check it is still the case.
« Last Edit: March 07, 2017, 11:32:08 am by rvk »

Thaddy

  • Hero Member
  • *****
  • Posts: 17414
  • Ceterum censeo Trumpum esse delendum (Tnx Charlie)
Re: Encrypt a text (easily)
« Reply #23 on: March 07, 2017, 11:43:10 am »
The dev team will imho never replace it with an inferior one. They may go with the Marsalia twister or similar, but that was not yet available (2003 vs 1997).
In programming languages one tends not to adapt the prng because it breaks code. That's also the reason Delphi kept its prng.
Prng's are not only used for encryption but also for e.g statistics. To test, one needs that given the same random seed the results are reproducable.
Which means the same algorithm, which means it is unlikely to be replaced.

So I don't think this will be changed any time soon.

In addition: strange encryption that relies on a particular random generation algorithm.
Here we use a prng to delelop and switch to a hwrng in production. A hwrng has no known seed and therefor no predicatble reproducability.
If your encryption algorithm relies on a particular impementation of the prng, you are plain stupid. >:D And defeats RVK's argument.

Note that hwrng's are now available on many processors: intel, but also Raspberry Pi (for which I have FPC code).
« Last Edit: March 07, 2017, 12:01:10 pm by Thaddy »
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

jmm72

  • Jr. Member
  • **
  • Posts: 79
  • Very experienced in being a beginner...
Re: Encrypt a text (easily)
« Reply #24 on: March 07, 2017, 12:04:37 pm »
A comment on the XOR encryption. Believe it or not, it's a math variation of the Vigenère code for an alphabet of 256 characters. It is effectively unbreakable if three requirements are met:
1. Password is random (not subject to frequency analisys).
2. Password and message are of same length.
3. Password is not reused to encrypt other messages (there's an attack to decrypt two messages encrypted with the same password).

Why unbreakable? Because you can only use brute force, and while it will undoubtly find the right unencrypted message, it will also find all the wrong messages too. And there will be no way to distinguish one from each other.

Consider the text 'Attack valley at dawn' (example taken from a book). You find the encrypted message, and brute force decrypt it, until you find 'Defend hill at sunset'. It has the same length, it looks legit, so you think you decrypted it. Then your forces are massacred at the valley because you thought the enemy was moving to the hill to defend it.

This applies to part of the message; you might find 'love' exchanged for 'hate' or viceversa; numbers 25300 and 37822 indistinguishable which one is the right one; or you can decrypt the first part of Moby Dick where the white whale is a vicious purple anchovy. This follows the same principle of an army of monkeys with typewriters and an infinite amount of time, or things like The Bible Code (which explained how the author of The Bible Code killed Kennedy). Too many options. Without the right password, you can't know which one is the right one.
Lazarus 1.6.4 + FPC 3.0.2 64bits under Windows 7 64bits
Only as a hobby nowadays
Current proyect release: TBA

Mr.Madguy

  • Hero Member
  • *****
  • Posts: 873
Re: Encrypt a text (easily)
« Reply #25 on: March 07, 2017, 12:48:40 pm »
Of course real algorithms use better hash functions and random generators, but if you're interested, how real cyphers work, then they usually do something like that:
Yikes !!! Don't use random in combination with encryption !

You're a Delphi programmer... You did read the following note in the Delphi documentation on Random??

Quote
Note: Because the implementation of the Random function may change between compiler versions, we do not recommend using Random for encryption or other purposes that require reproducible sequences of pseudo-random numbers.
http://docs.embarcadero.com/products/rad_studio/delphiAndcpp2009/HelpUpdate2/EN/html/delphivclwin32/System_Random.html

I'm not sure if this would also be the case in FPC but the function is not called random for nothing. And implementation could change in the future.

So always make sure you use the same pseudo-random generator (and using the compiler version might not always be the same).
I thought, I mentioned, that my program isn't real encryption algorithm. It's just simple example of symmetrical stream cipher. Yeah, other types of encryption algorithms are more secure, but this one is the fastest and most simple one.

P.S. Bad thing about using some data (such as text from some book) as password - some unfortunate data, that should be encrypted, can expose password itself, so password should be indiscernible.
« Last Edit: March 07, 2017, 12:53:13 pm by Mr.Madguy »
Is it healthy for project not to have regular stable releases?
Just for fun: Code::Blocks, GCC 13 and DOS - is it possible?

Thaddy

  • Hero Member
  • *****
  • Posts: 17414
  • Ceterum censeo Trumpum esse delendum (Tnx Charlie)
Re: Encrypt a text (easily)
« Reply #26 on: March 10, 2017, 03:31:07 pm »
BTW: I wrote a wiki entry about random generators as mentioned here.
http://wiki.freepascal.org/Marsaglia%27s_pseudo_random_number_generators
Although only slightly related to encryption one might find it interesting. Particularly for the ones that mention encryption and random in the same sentence  8-) ::)
Due to censorship, I changed this to "Nelly the Elephant". Keeps the message clear.

ertank

  • Sr. Member
  • ****
  • Posts: 276
Re: Encrypt a text (easily)
« Reply #27 on: March 10, 2017, 08:16:54 pm »
Hi,

There is an ORM framework called mORMot. Web link: https://synopse.info/fossil/wiki/Synopse+OpenSource

This framework is specialized in SQLite database and REST (json objects). Optimized in a such way. Framework also includes crypt random generator functions.
Link: http://blog.synopse.info/post/AES-CSPRNG

Additionally, framework is capable of doing some cryption including AES-CFB and some others.

Below example is making it easier to use framework crypt routines over two functions.
Code: [Select]
program project1;


uses
  SysUtils,
  SynCrypto,  // mORMot framework unit
  SynCommons;  // mORMot framework unit

function EncryptItAES(const s:string; const aKey: string): string;
var
  key : TSHA256Digest;
  aes : TAESCFB;
  _s:RawByteString;
begin
  Result := EmptyStr;
  SynCommons.HexToBin(Pointer(SHA256(StringToUTF8(aKey))), @key, 32);

  aes := TAESCFB.Create(key, 256);
  try
    _s := StringToUTF8(s);
    _s := BinToBase64(aes.EncryptPKCS7(_s, True));
    Result := UTF8ToString(_s);
  finally
    aes.Free;
  end;
end;


function DecryptItAES(const s:string; const aKey: string): string;
var
  key : TSHA256Digest;
  aes : TAESCFB;
  _s:RawByteString;
begin
  Result := EmptyStr;
  SynCommons.HexToBin(Pointer(SHA256(StringToUTF8(aKey))), @key, 32);

  aes := TAESCFB.Create(key, 256);
  try
    _s     := StringToUTF8(s);
    try
      _s     := aes.DecryptPKCS7(Base64ToBin(_s), True);
    except
      Exit(EmptyStr);
    end;
    Result := UTF8ToString(_s);
  finally
    aes.Free;
  end;
end;

const
  AKey = 'secondary key for encrypting text. Better be character bytes';

var
  SampleText: string;
  Encrypted: string;
  Decrypted: string;
begin
  SampleText := 'test me good';
  Encrypted := EmptyStr;
  Decrypted := EmptyStr;

  WriteLn('Initial Text: ', SampleText);
  Encrypted  := EncryptItAES(SampleText, AKey);
  WriteLn('Crypt Text: ', Encrypted);

  Decrypted := DecryptItAES(Encrypted, AKey);
  WriteLn('Decrypt Text: ', SampleText);
end.

Output I am getting is something like:
Code: [Select]
C:\cryptest>project1.exe
Initial Text: test me good
Crypt Text: +saEqNYjII94hYpYNTM0QID7DoredRVUI4YMB3JfElA=
Decrypt Text: test me good

C:\cryptest>project1.exe
Initial Text: test me good
Crypt Text: 1+mfoOH70vubVNjHlU2yDQTYc5pwF1PXishN6GVlEyk=
Decrypt Text: test me good

C:\cryptest>

Please note that same text with same Key value is crypt into something totally different and can be de-crypt correctly.

Since crypt text is converted into base64 encoded string. You will be able to save it into a file and load it back from it. One thing that should be taken care of is: If crypt text is not correct, meaning it is modified and is a wrong one now. There will be an exception raised during decryption. Sample code suppress that exception and return back an empty string if that ever happens.

Application is tested under Windows. I expect it to be running under Linux, too. Don't have Linux OS available to test.
« Last Edit: March 10, 2017, 08:29:15 pm by ertank »

farhan

  • Newbie
  • Posts: 5
Re: Encrypt a text (easily)
« Reply #28 on: September 27, 2017, 03:42:55 am »
thanks for then info sir

 

TinyPortal © 2005-2018