RSA Encryption (Polish KSeF)

Hi,
Now I need to encrypt string with RSA SHA 256 using public key.
When I try to load a public key, I receive the error:
FromPublicKeyFile: This is not a valid public key file [02].

My public key file (.crt) starts with
-----BEGIN CERTIFICATE-----
MIIC4zCCAmegAwIBAgIIAf4E5T3MU/0wDAYIKoZIzj0EAwIFADBvMQswCQYDVQQG
and ends with
SCdPfMG/WyfEPJskA2OCBGU3HvuxfmU=
-----END CERTIFICATE-----

My code is following:

function EncryptTokenWithRSA (const TextToEncrypt:string; const CrtFileName: string): string;
begin
RSA := TRSAEncSign.Create(nil);
try
RSA.KeyLength := kl2048;
RSA.OutputFormat := base64;
RSA.Unicode := yesUni;
RSA.hashFunction := TRSAHashFunction.sha256;
RSA.encType := TRSAEncType.oaep;
try
RSA.FromOpenSSLPublicKey (CrtFileName);
except
on E:Exception do
Application.MessageBox (E.Message, 'Warning', MB_OK);
end;
Result := RSA.Encrypt(TextToEncrypt);
finally
RSA.Free;
end;
end;

Send me your cert at bernard[at]tmssoftware[dot]com to ckeck whether the lib can decode it.

Thank you. Certificate file has been sent.

Your file is a PEM certificate, not a public key file.
At this stage, it is better to use procedure
TX509Certificate.DecodeCertFromPEM(PEMfilePath: string);
and encrypt from there.
Another option is to use procedure
TRSAEncSign.FromCertificateFile(CertFile: string);
but you need to remove the first and last line of the cert before loading it.
-----BEGIN CERTIFICATE-----
and
-----END CERTIFICATE-----

I can add a TRSAEncSign.FromPEMCertificate in a future release. It will check the first and last lines, decode the cert and load the public key.

My mistake, just use
procedure TRSAEncSign.FromCertificateFile(CertFile: string);

It calls X509 that does the PEM verification and decoding:

  X509 := TX509Certificate.Create();
  conv := TConvert.Create(hexa);
  try
    X509.CrtFilePath := CertFile; // THIS DOES THE PEM VERIFICATION
    X509.Decode;

Thank you Bernard,
I tried it, but I receive the error:
Signature algorithm not supported (ECDSA with SHA256)

It looks like there is no TSignAlgo.sa_sha256ec handling and BitSizeEncryptionAlgorithm = 0

That's normal if you load an EC cert from RSA.

You need to load it either using X509Certificate or TECCEncSign.FromCertificateFile (encryption only) or TECCEncSign.FromPrivateKeyFile (both keys are in there).

Wait for the next release if you need to use TECCEncSign.FromCertificateFile or modify line 775:

self.PublicKey := X509.PublicKey;

Thank you,

However line 775 can not be modified this way in RSAObj, X509Obj or ECCObj file. Any of these can not be compiled after such modification.

Hi Bernard,
I downloaded the new release - 5.1.0.4.
However when I call RSA.FromCertificateFile (CertFile), I receive the error:

Signature algorithm not supported (ECDSA with SHA256)

Hi,

RSA.FromCertificateFile can only load RSA keys.