https://blogs.sap.com/2019/08/26/aes-encryption-in-abap/
https://github.com/Sumu-Ning/AES
https://blog.csdn.net/u012232542/article/details/103184183
介紹
最近,我們的組織要求對從 SAP 到外部系統的所有數據傳輸實施加密,以增加額外的安全層。要求是對系統之間共享的信息進行 AES256 加密和 Base64 編碼。加密/解密使用在 SAP 中生成並通過系統自動電子郵件共享的公共密鑰完成。
用於流程的 SAP 類/功能模塊:
- CL_SEC_SXML_WRITER 用於實現生成 AES 密鑰和信息加解密的邏輯。
- SCMS_BASE64_<EN/DE>CODE_STR FM 用於 Base64 編碼/解碼信息。
高級流程
以下是我們用於加密/解密的步驟和示例代碼。
生成加密密鑰
我們使用以下邏輯生成用於加密的密鑰,該密鑰存儲在表中,然后與外部系統共享。
*Sample Code to generate Key:
data: random type xstring, wa_bench_config type zhr_bench_config.
call method cl_sec_sxml_writer=>generate_key
exporting
algorithm = cl_sec_sxml_writer=>co_aes256_algorithm
receiving
key = random.
data(lr_conv_key) = cl_abap_conv_out_ce=>create( ).
lr_conv_key->write( data = random ).
e_key = lr_conv_key->get_buffer( ).
解密
外部系統發送 AES 加密和 Base64 編碼的數據,在 SAP 中,我們使用以下邏輯來解密文本。
data: i_key_xstring type xstring, i_iv type xstring.
i_iv = '00000000000000000000000000000000'.
if i_text is not initial.
call function 'SCMS_BASE64_DECODE_STR'
exporting
input = i_text
* UNESCAPE = 'X'
importing
output = i_xstring
* EXCEPTIONS
* FAILED = 1
* OTHERS = 2
.
if sy-subrc <> 0.
* Implement suitable error handling here
endif.
endif.
if i_xstring is not initial.
* For CL_SEC_SXML_WRITER to work with external application we need to add 16 bit
* extra padding before decryption
concatenate i_iv(16) i_xstring into i_xstring in byte mode.
try.
cl_sec_sxml_writer=>decrypt(
exporting
ciphertext = i_xstring
key = i_key_xstring
algorithm = cl_sec_sxml_writer=>co_aes256_algorithm_pem
importing
plaintext = data(lv_message_decrypted) ).
" convert xstring to string for output
cl_abap_conv_in_ce=>create( input = lv_message_decrypted )->read( importing data = e_text_dec ).
catch cx_sec_sxml_encrypt_error into data(oref). .
endtry.
endif.
加密:
SAP 處理信息並使用以下邏輯發回加密響應:
data(lr_conv_sec) = cl_abap_conv_out_ce=>create( ).
lr_conv_sec->write( data = i_text ).
" encrypt using AES256
i_xstring = lr_conv_sec->get_buffer( ).
i_iv = '00000000000000000000000000000000'.
cl_sec_sxml_writer=>encrypt_iv(
exporting
plaintext = i_xstring
key = i_key_xstring
iv = i_iv
algorithm = cl_sec_sxml_writer=>co_aes256_algorithm_pem
importing
ciphertext = data(lv_message) ).
data: lr_conv type ref to cl_abap_conv_in_ce,
lr_xstring type xstring,
lr_string type string.
*Before sending encrypted information to external system, remove the extra
*16 bit padding from the xstring
lr_xstring = lv_message+16.
data: lt_data type tsfixml, l_len type i.
call function 'SCMS_BASE64_ENCODE_STR'
exporting
input = lr_xstring
importing
output = e_text_enc.
endif.
示例輸出:
EXAMPLE:
Text: Test AES@CBC#PKCS$5
Encrypted Text : B8Q1+w5vH9jG3V/ejYg5igeGNgfX6nvqUGrDnogyDdo=
After Decryption : Test AES@CBC#PKCS$5
結論
該博客文章提供了有關如何在 SAP 中加密和解密信息以及如何規划與外部系統的集成的信息。此處的示例代碼適用於 AES256/CBC/PKCS5 Padding 算法,但 CL_SEC_SXML_WRITER 類也有其他 AES 加密算法。
請注意,除了加密密鑰外,我們還需要共享 16 位十六進制字符串 ('0000000000000000') 的 IV 密鑰。