I use following procedure to encode stream.
procedure SaveEncodedStream(Strm:TStream; LicFileName:String);
var
C:TCodec;
CL:TCryptographicLibrary;
Sg:TSignatory;
KFS,DFS:TFileStream;
Dir:String;
begin
CL:=TCryptographicLibrary.Create(nil);
C:=TCodec.Create(nil);
SG:=TSignatory.Create(nil);
Dir := ExtractFilePath(ParamStr(0));
KFS:=TFileStream.Create(Dir+PublicKeyFile,fmOpenRead);
DFS:=TFileStream.Create(LicFileName,fmCreate);
try
C.CryptoLibrary:=CL;
C.BlockCipherId := 'native.RSA';
C.ChainModeId := 'native.CBC';
C.AsymetricKeySizeInBits := 1024;
SG.Codec:=C;
SG.LoadKeysFromStream(KFS,[partPublic]);
C.EncryptStream(Strm,DFS);
finally
CL.Free;
C.Free;
SG.Free;
KFS.Free;
DFS.Free;
end;
end;
And receive "Wrong Mode" error on
C.EncryptStream(Strm,DFS);
call
Stepping into the code I discovered that it even does not try to load keys as Codec is not initialized. When I place componets on the form - everything works. But I do not need Form or DataModule.
Have not found solution to get rid of DataModule. It looks like components need one to properly initialize themselves. So as workaround I have created global DataModule with all components configured in design mode. I use that module in SaveEncodedStream like that:
uses
... EncryptDataModule;
...
var
BeenHere:Boolean = false;
...
procedure SaveEncodedStream(Strm:TStream; LicFileName:String);
var
KFS,DFS:TFileStream;
Dir:String;
begin
Dir := ExtractFilePath(ParamStr(0));
KFS:=TFileStream.Create(Dir+PublicKeyFile,fmOpenRead);
DFS:=TFileStream.Create(LicFileName,fmCreate);
try
DataModule.SG.LoadKeysFromStream(KFS,[partPublic]);
if BeenHere then DataModule.C.Reset;
DataModule.C.EncryptStream(Strm,DFS);
BeenHere:=true;
finally
KFS.Free;
DFS.Free;
end;
end;