#9 Encrypt and Decrypt using AES_128_CFB algorithm

Unlicensed
None
2020-12-14
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


Log in to post a comment.