Skip to content

Instantly share code, notes, and snippets.

@larshp
Last active October 30, 2023 06:42
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save larshp/e99d9dcd87928aedef02f4048a52276b to your computer and use it in GitHub Desktop.
Save larshp/e99d9dcd87928aedef02f4048a52276b to your computer and use it in GitHub Desktop.
GUID v4 implementation in ABAP
* GUID v4 implementation in ABAP
* Also see SAP note 2619546 !
* https://answers.sap.com/questions/11928657/generating-uuid-in-abap.html
* http://www.cryptosys.net/pki/uuid-rfc4122.html
* https://tools.ietf.org/html/rfc4122#page-14
DATA guid TYPE c LENGTH 36.
DATA hex TYPE x LENGTH 16.
DATA xstr TYPE xstring.
* note: this relies on the randomness of the random number generator, but limits the number of possible guids to 4 billion, whereas there should be 5 undecillion possible outcomes
*DATA random TYPE REF TO cl_abap_random.
*DATA hex1 TYPE x LENGTH 1.
*DATA index TYPE i.
*random = cl_abap_random=>create( cl_abap_random=>seed( ) ).
*DO 16 TIMES.
* index = sy-index - 1.
* hex1 = random->intinrange( low = 0 high = 255 ).
* hex+index = hex1.
*ENDDO.
* this doesnt give a random guid,
* hex = cl_system_uuid=>create_uuid_c32_static( ).
* this might work, but depends on the kernel implementation
CALL FUNCTION 'GENERATE_SEC_RANDOM'
EXPORTING
length = 16
IMPORTING
random = xstr
EXCEPTIONS
invalid_length = 1
no_memory = 2
internal_error = 3
OTHERS = 4.
ASSERT sy-subrc = 0.
hex = xstr.
* set the four most significant bits of the 7th byte to 0100'B, so the high nibble is "4"
SET BIT 1 OF hex+6(1) TO 0.
SET BIT 2 OF hex+6(1) TO 1.
SET BIT 3 OF hex+6(1) TO 0.
SET BIT 4 OF hex+6(1) TO 0.
* set the two most significant bits of the 9th byte to 10'B, , so the high nibble will be one of "8", "9", "A", or "B"
SET BIT 1 OF hex+8(1) TO 1.
SET BIT 2 OF hex+8(1) TO 0.
guid = |{ hex(4) }-{ hex+4(2) }-{ hex+6(2) }-{ hex+8(2) }-{ hex+10(6) }|.
TRANSLATE guid TO LOWER CASE.
WRITE guid.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment