#9 Encrypt and Decrypt using AES_128_CFB algorithm

Unlicensed
None
2023-04-03
2020-12-14
i-campbell
No

Based on Crypto Example

PROGRAM PLC_PRG
VAR
    Result1, Result2, Result3, Result4 : RTS_IEC_RESULT;

    _hCipher : RTS_IEC_HANDLE := CryptoGetAlgorithmById(ui32CryptoID:=RtsCryptoID.AES_128_CFB, pResult:=0);
    _szBlock : ULINT := 16; // Blocksize of ``_hCipher`` => 128 Bit for AES_128_CFB
    _sKey : SECRET; // 128 Bit Secret Key
    _szKey : ULINT := 16; // 128 Bit
    _sInitVector : MESSAGE; // Random Initial Value of Length ``_szBlock``
    sPlainText : MESSAGE := 'The red fox has an elongated body and relatively short limbs. The tail, which is longer than half the body length.';
    szPlainText : ULINT := TO_ULINT(Standard.LEN(sPlainText));
    sCipherText : MESSAGE;
    sDecipherText : MESSAGE;

    bsKey : RtsByteString := (ui32MaxLen:=SIZEOF(_sKey), ui32Len:=0, pByData:=ADR(_sKey));
    ckKey : RtsCryptoKey;
    bsInitVector : RtsByteString := (ui32MaxLen:=SIZEOF(_sInitVector), ui32Len:=0, pByData:=ADR(_sInitVector));
    bsPlainText : RtsByteString := (ui32MaxLen:=SIZEOF(MESSAGE), ui32Len:=TO_UDINT(szPlainText), pByData:=ADR(sPlainText));
    bsCipherText : RtsByteString := (ui32MaxLen:=SIZEOF(MESSAGE), ui32Len:=0, pByData:=ADR(sCipherText));
    bsDecipheredText : RtsByteString := (ui32MaxLen:=SIZEOF(MESSAGE), ui32Len:=0, pByData:=ADR(sDecipherText));

    Init: BOOL := TRUE;
END_VAR


IF Init THEN
    Result1 := CryptoGenerateRandomNumber(ui32NumOfRandomBytes:=TO_UDINT(_szKey), pRandom:=ADR(bsKey));
    Result2 := CryptoGenerateRandomNumber(ui32NumOfRandomBytes:=TO_UDINT(_szBlock), pRandom:=ADR(bsInitVector));
    ckKey.keyType := RtsCryptoKeyType.KeyType_Key;
    ckKey.key.byteString := bsKey;

    Result3 := CryptoSymmetricEncrypt(
        hAlgo:=_hCipher,
        pPlainText:=ADR(bsPlainText),
        key:=ckKey,
        pInitVector:=ADR(bsInitVector),
        xEnablePadding:=TRUE,
        pCipherText:=ADR(bsCipherText) );

    Result4 := CryptoSymmetricDecrypt(
        hAlgo:=_hCipher,
        pCipherText:=ADR(bsCipherText),
        key:=ckKey,
        pInitVector:=ADR(bsInitVector),
        xEnablePadding:=TRUE,
        pPlainText:=ADR(bsDecipheredText) );
    Init := FALSE;
END_IF;

Discussion

  • hermsen

    hermsen - 2021-12-24

    A good example of Symmetric Encryption (usage of a single key to Encrypt/Decrypt data) which is less complex then its Asymmetrical counterpart.

     
    👍
    1

    Last edit: hermsen 2021-12-24
  • siwasubramaniam - 2023-04-03

    Does this work? I tried it and it doesn't give me a value for the sCipherText nor sDecipherText. I've tried the CryptoDemo file too, same problem.

     

Log in to post a comment.