views:

145

answers:

3

I need to encrypt some text in my program developed using Lazarus/Freepascal, but I should be able to load them as text and decrypt them, rather than in binary because I need to save them in a TStrings type property.

Which algorithm(s) are suited to that?

A: 

Afaik the much used Delphi dcpcrypt2 package works fine on FPC/Lazarus.

http://www.cityinthesky.co.uk/cryptography.html

I usually use Rijndael.

Freepascal has an own unit for mime encoding that works fine, also in Delphi

Marco van de Voort
Rijndael certainly has the best name. Although its FAQ suggested an even better one - teaching someone to say "Koeieuier" provides hours of entertainment! (Great for causing another name they list: "Angstschreeuw"!)
Frank Shearar
Ask de zeeeend.
Marco van de Voort
+6  A: 

Use any suitable encryption, and then use base64 MIME encoding to make it into a plain string that you can store in a normal string.

mj2008
You can even zip encrypted string before base64-ing it.
I wouldn't try that. Compression doesn't work well with randomized data.
Mason Wheeler
You're right. So if it's large amount of text, he can compress it *before* encryption. Just to compensate base64 overhead.
+1  A: 

The correct answer is: don't do it. Don't pick algoritm, which encrypts text to text.

You need to do 2 steps:

  1. Encrypting (chiper the text).
  2. Encoding (convert binary result to text).

No matter, which encrypting method you'll choose - the important part is how you'll convert binary to text. This means that any encrypting will do. You can pick DCPCrypt, Windows cryptography - anything.

How to convert binary to text?

1). For example, you can just escape bad characters, so TStrings will no be confused. Pick a special character. For example: #1.

Now, to encode string, replace all #1 -> #1#2, #0 -> #1#3, #13 -> #1#4, #10 -> #1#5. This should be enough for TStrings to accept this without issues.

To decode - do reverse order: replace #1#5 -> #10, #1#4 -> #13, #1#3 -> #0, #1#2 -> #1.

2). Alternatively, you can use Base64, as mj2008 pointed out. Base64 is well-known standard. However, it produces more bloated text (compared to prev. method) and may work a bit more slowely (complex encoding instead simple search&replace logic).

3). Or you can just write each byte as 2 characters: i.e. write hex-code of each-byte (like BinToHex do). This is even more bloated than base64 (but may be the fastest one), but it has advantage that is most easy to implement than any other method. You even don't need to write much code, as Delphi already have BinToHex/HexToBin routines.

Alexander