Monday, July 25, 2022

Encoding and Decoding in ABAP

This post tell you the way ABAP can encrypt and decrypt data.

First step: you can generate key or set fixed key.

lv_key cl_sec_sxml_writer=>generate_keyalgorithm cl_sec_sxml_writer=>co_aes256_algorithm  ).

Second step: you will encypt data with method encrypt_iv in class cl_sec_sxml_writer

* Converting the string to XSTRING format
lv_data_xstr cl_bcs_convert=>string_to_xstringiv_string lv_data ).

* Data Encryption
cl_sec_sxml_writer=>encrypt_iv(
         EXPORTING
           plaintext  lv_data_xstr
           key        lv_key
           iv         lv_iv
           algorithm  cl_sec_sxml_writer=>co_aes256_algorithm_pem
         IMPORTING
           ciphertext lv_encrypted_str  ).

Third step: you can decrypt data based on encrypted string and key.

cl_sec_sxml_writer=>decrypt(
  EXPORTING
    ciphertext =   lv_encrypted_str  " Ciphertext
    key        =   lv_key  " Key
algorithm  cl_sec_sxml_writer=>co_aes256_algorithm_pem
  IMPORTING
    plaintext  =  lv_decrypted_xstr ).

cl_bcs_convert=>xstring_to_string(
  EXPORTING
    iv_xstr   =  lv_decrypted_xstr
    iv_cp     =  1100   " SAP character set identification
  RECEIVING
    rv_string lv_decrypted_str
).

You can view all coding of program

REPORT ztest_giang NO STANDARD PAGE HEADING LINE-SIZE 255.

DATAlv_key       TYPE xstring.
DATAlv_data           TYPE string,
      lv_data_xstr      TYPE xstring,
      lv_iv             TYPE xstring,
      lv_encrypted_str  TYPE xstring,
      lv_decrypted_xstr TYPE xstring,
      lv_decrypted_str  TYPE string.

lv_key cl_sec_sxml_writer=>generate_keyalgorithm cl_sec_sxml_writer=>co_aes256_algorithm  ).

WRITE'Encryp with AES256:'.
WRITE 'Key:' && lv_key.

lv_data 'Text before encrypt'.

* Converting the string to XSTRING format
lv_data_xstr cl_bcs_convert=>string_to_xstringiv_string lv_data ).

* Define the initialization vector.
lv_iv '00000000000000000000000000000000'.

* Data Encryption
cl_sec_sxml_writer=>encrypt_iv(
         EXPORTING
           plaintext  lv_data_xstr
           key        lv_key
           iv         lv_iv
           algorithm  cl_sec_sxml_writer=>co_aes256_algorithm_pem
         IMPORTING
           ciphertext lv_encrypted_str  ).


cl_sec_sxml_writer=>decrypt(
  EXPORTING
    ciphertext =   lv_encrypted_str  " Ciphertext
    key        =   lv_key  " Key
algorithm  cl_sec_sxml_writer=>co_aes256_algorithm_pem
  IMPORTING
    plaintext  =  lv_decrypted_xstr ).

cl_bcs_convert=>xstring_to_string(
  EXPORTING
    iv_xstr   =  lv_decrypted_xstr
    iv_cp     =  1100   " SAP character set identification
  RECEIVING
    rv_string lv_decrypted_str
).

Write/.
WRITE'Data before encrypt: '.
WRITElv_data.
WRITE:'Encrypted Data:'.
WRITElv_encrypted_str.
WRITE'Decrypted data:'.
WRITElv_decrypted_str.

Output will look like