TSimpleCodec.Begin_EncryptMemory - Wrong mode

2.3k Views Asked by At

I get TSimpleCodec.Begin_EncryptMemory - Wrong mode exception wile executing the following code. Is it something wrong?

FLibrary := TCryptographicLibrary.Create(Self);
FCodec := TCodec.Create(Self);
FCodec.CryptoLibrary := FLibrary;
FCodec.BlockCipherId := 'native.AES-256';
FCodec.ChainModeId := 'native.ECB';
FCodec.Password := 'password';
plain := 'The plain text';
FCodec.EncryptString(plain, astr);
FCodec.DecryptString(dec, astr);
2

There are 2 best solutions below

0
On

I'm not a programmers... and my english skill is low.

I use Delphi 10.4 Community Edition, LockBox verison 3.4.1.0 (Run-time) and 3.4.0.0 (design-time)

Drop Codec and CryptographicLibrary components to your form (or create run-time)

Set the Key1. (maybe constant). if yout set password once in start your program, and run a function without key setting line, you get error message:TSimpleCodec.Begin_EncryptMemory...

But... If you set password every time, the program will working fine.

Code example:

const
  Key1='JDGHn%/=UHBrgtsh!/';

function TForm1.EncryptString(InString:String):String;

var  Res:    String;

begin

    Codec1.Password := Key1;

    Codec1.EncryptString(InString, Res, TEncoding.UTF8);

    Result:=Res;

end;

function TForm1.DecryptString(InString:String):String;

var  Res:    String;

begin

    Codec1.Password := Key1;

    Codec1.DecryptString(InString, Res, TEncoding.UTF8);

    Result:=Res;

end;
1
On

When initialising the codec by run-time code, you need to set the StreamCipherId. Insert the following line just before setting the BlockCipherId.

 FCodec.StreamCipherId := BlockCipher_ProgId;

You don't need to do this if you are setting up the codec with design-time values. It's much easier to do at design-time. Just set the published properties as required.

The demo program for Delphi 2010, gives an example in methods TmfmLockbox3_Demo.FormCreate() and TmfmLockbox3_Demo.actCustomBlockEncryptExecute() .

Also read the on-line help about it.

As a general hint, if you just look at the demo program and/or read the on-line help, you will rarely need to come to StackOverflow. If there are any short-comings in the documentation, please post some constructive actionable suggestions on the LockBox forums to improve the documentation (demos + on-line help).