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;
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.
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: