AES实现

加密

DATA: lv_base64 TYPE string,
      lv_str    TYPE string.
 
DATA: lv_data      TYPE string,
      lv_data_xstr TYPE xstring,
      lv_key_xstr  TYPE xstring,
      lv_key_str   TYPE string,
      lv_iv_xstr   TYPE xstring,
      lv_iv_str    TYPE string,
      lv_en_xstr   TYPE xstring,
      lv_de_xstr   TYPE xstring,
      lv_de_str    TYPE string,
      lv_en_str    TYPE string.
 
lv_data = '待加密字符串'.
lv_data_xstr = cl_bcs_convert=>string_to_xstring( iv_string   = lv_data iv_codepage = '4110' ).
 
" key aes256 32字节 aes192 24字节 aes128 16字节
lv_key_str = 'ABCDEFGHIJKLMNOP'.
lv_key_xstr = cl_bcs_convert=>string_to_xstring( iv_string   = lv_key_str iv_codepage = '4110' ).
" 偏移量 cbc模式使用
lv_iv_str = '1234567890123456'.
lv_iv_xstr = cl_bcs_convert=>string_to_xstring( iv_string   = lv_iv_str iv_codepage = '4110' ).
 
TRY.
    cl_sec_sxml_writer=>encrypt_iv(
      EXPORTING
        plaintext =  lv_data_xstr
        key       =  lv_key_xstr
        iv        =  lv_iv_xstr
        algorithm =  cl_sec_sxml_writer=>co_aes128_algorithm
      IMPORTING
        ciphertext = lv_en_xstr ).
  CATCH cx_root.
ENDTRY.
 
" 移除偏移量
lv_en_str =  lv_en_xstr.
IF strlen( lv_en_str ) > 32.
  SHIFT lv_en_str LEFT BY 32 PLACES.
  lv_en_xstr = lv_en_str.
ENDIF.
CALL FUNCTION 'SCMS_BASE64_ENCODE_STR'
  EXPORTING
    input  = lv_en_xstr
  IMPORTING
    output = lv_str.
WRITE:/ lv_str.

解密

DATA: lv_base64 TYPE string,
      lv_str    TYPE string.
 
DATA: lv_data      TYPE string,
      lv_data_xstr TYPE xstring,
      lv_key_xstr  TYPE xstring,
      lv_key_str   TYPE string,
      lv_iv_xstr   TYPE xstring,
      lv_iv_str    TYPE string,
      lv_en_xstr   TYPE xstring,
      lv_de_xstr   TYPE xstring,
      lv_de_str    TYPE string,
      lv_en_str    TYPE string.
 
lv_base64 = '7pSa8sj9sCWvzgQIMgr/0AtKolaS/K54V3MUCEE0mXg='.
CALL FUNCTION 'SCMS_BASE64_DECODE_STR'
  EXPORTING
    input  = lv_base64
*   UNESCAPE       = 'X'
  IMPORTING
    output = lv_en_xstr
  EXCEPTIONS
    failed = 1
    OTHERS = 2.
 
" 前置8位补位 偏移量
lv_iv_str = '1234567890123456'.
lv_iv_xstr = cl_bcs_convert=>string_to_xstring( iv_string   = lv_iv_str iv_codepage = '4110' ).
lv_en_xstr = lv_iv_xstr && lv_en_xstr.
" DES key 8字节,如果为TDEA加密(3DES)key为24字节,转化为十六进制使用
lv_key_str = 'ABCDEFGHIJKLMNOP'.
lv_key_xstr = cl_bcs_convert=>string_to_xstring( iv_string   = lv_key_str iv_codepage = '4110' ).
 
TRY.
    cl_sec_sxml_writer=>decrypt(
      EXPORTING
        ciphertext = lv_en_xstr
        key        = lv_key_xstr
         algorithm  = cl_sec_sxml_writer=>co_aes128_algorithm
       IMPORTING
         plaintext  = lv_de_xstr
           ).
  CATCH cx_root.
ENDTRY.
 
lv_de_str = cl_bcs_convert=>xstring_to_string( iv_xstr = lv_de_xstr iv_cp = '4110' ).
 
WRITE: / '解密后字符串:', lv_de_str.