Skip to Content
0
Apr 02, 2019 at 09:19 AM

CL_SEC_SXML_WRITER=>DECRYPT AES decryption fails / CX_SEC_SXML_ENCRYPT_ERROR

2798 Views

Dear SAP-Community,

my goal is to encrypt a string in one program using a given password and to save the encrypted result in a file. In another program I will read the encrypted message from that file and decrypt it.

I'm using CL_SEC_SXML_WRITER=>ENRCYPT for encryption and CL_SEC_SXML_WRITER=>DECRYPT for decryption (algorithm: cl_sec_sxml_writer=>co_aes256_algorithm). Encrypting works smoothly. When I try to decrypt I'm getting the exception: CX_SEC_SXML_ENCRYPT_ERROR (UNCAUGHT_EXCEPTION).

If I encrypt and decrypt in the same program, everything works fine. Only when I split the encryption and decryption in two programs I get the exception.

My encryption demo:

REPORT y_enrypt_txt.

PARAMETERS:
p_msg TYPE string OBLIGATORY DEFAULT 'This is my test' LOWER CASE,
p_pwd TYPE string OBLIGATORY DEFAULT '1234' LOWER CASE,
p_file TYPE string OBLIGATORY LOWER CASE.

START-OF-SELECTION.

* create message
DATA(lr_conv_sec) = cl_abap_conv_out_ce=>create( ).
lr_conv_sec->write( p_msg ).

* create key
DATA(lr_conv_key) = cl_abap_conv_out_ce=>create( ).
lr_conv_key->write( p_pwd ).

* encrypt using AES256
cl_sec_sxml_writer=>encrypt(
EXPORTING
plaintext = lr_conv_sec->get_buffer( )
key = lr_conv_key->get_buffer( )
algorithm = cl_sec_sxml_writer=>co_aes256_algorithm
IMPORTING
ciphertext = DATA(lv_message) ).

OPEN DATASET p_file FOR OUTPUT IN BINARY MODE.
TRANSFER lv_message TO p_file.
CLOSE DATASET p_file.

My decryption demo:

REPORT y_decrypt_txt.

DATA:
lv_enc_msg_xstring TYPE xstring,
lf_plaintext_file TYPE xstring,
lv_decrypted_string TYPE string.

PARAMETERS:
p_pwd TYPE string OBLIGATORY DEFAULT '1234' LOWER CASE,
p_file TYPE string OBLIGATORY LOWER CASE.

START-OF-SELECTION.

OPEN DATASET p_file FOR INPUT IN BINARY MODE.
READ DATASET p_file INTO lv_enc_msg_xstring.
CLOSE DATASET p_file.

* create key
DATA(lr_conv_key) = cl_abap_conv_out_ce=>create( ).
lr_conv_key->write( p_pwd ).

* decrypt using AES256

cl_sec_sxml_writer=>decrypt(
EXPORTING
ciphertext = lv_enc_msg_xstring
key = lr_conv_key->get_buffer( )

algorithm = cl_sec_sxml_writer=>co_aes256_algorithm

IMPORTING
plaintext = lf_plaintext_file ).

cl_abap_conv_in_ce=>create( input = lf_plaintext_file )->read( IMPORTING data = lv_decrypted_string ).

WRITE: / 'Decrypted: ', lv_decrypted_string.

What am I doing wrong? Why is it possible to encrypt and decrypt in the same program? Why do I get an exception if I split the code in two programs?

Best regards,

Hanno