sbeaudoin - 2023-06-07

Sorry, I accidentally posted this in Runtime but I think this forum may be more appropriate.

I am having trouble verifying a RSA PKCS1.5 SHA256 signature given a message, the signature as a hex string, and a public key as a .pem file.

Here is an example of how I am trying to verify a signature using the CmpCrypto library in CODESYS V3.5 SP15:

FUNCTION AsymmetricVerifyMessage : BOOL
VAR_INTPUT
    sMessage : REFERENCE TO STRING;
    szMessage : ULINT;
    abySignature : REFERENCE TO ARRAY[0..255] OF BYTE;
    szSignature : ULINT;
    abyPublicKey : REFERENCE TO ARRAY[0..291] OF BYTE;
    szPublicKey : ULINT;
END_VAR
VAR
    result : RTS_IEC_RESULT;
    bsMessage : RtsByteString := (ui32MaxLen:=SIZEOF(STRING), ui32Len:=TO_UDINT(szMessage), pByData:=ADR(smessage));
    bsSignature : RtsByteString := (ui32MaxLen:=256, ui32Len:=TO_UDINT(szSignature), pByData:=ADR(abySignature));
    bsPublicKey : RtsByteString := (ui32MaxLen:=292, ui32Len:=TO_UDINT(szPublicKey), pByData:=ADR(abyPublicKey));
    ksPublicKey : RtsCryptoKey;
END_VAR

ksPublicKey.keyType := RtsCryptoKeyType.KeyType_Key;
ksPublicKey.key.byteString := bsPublicKey;

result := CryptoSignatureVerify(
    hAlgo:=CryptoGetAlgorithmById(ui32CryptoID:=RtsCryptoID.RSA_PKCS1_V15_SHA256, pResult:=0),
    pData:=ADR(bsMessage),
    publicKey:=ksPublicKey,
    pSignature:=ADR(bsSignature)
);

AsymmetricVerifyMessage := (result = CmpErrors.Errors.ERR_OK);

Attached are a public key and signature that have been verified outside of CODESYS with message "TEST".

Any feedback on the code I have here, or other examples on how I can verify a signature with a .pem public key in CODESYS V3.5 SP15 would be appreciated.

Thank you