JwtGenerateAndVerify

Ukázka vygenerování a ověření JWT

Popis

Skript vygeneruje JWT (JSON Web Token) ( https://jwt.io/ ) a následně provede verifikaci
declare function GetAsciiCharByDec dll "ActualDocument" (integer): string

declare function StrPosRight dll "ActualDocument" (string, string): integer

declare procedure StrLeft dll "ActualDocument" (string, integer, string, string)

declare function ConvertEncoding dll "ScriptEx" (string, string, string): string
declare function ComputeHmac dll "ScriptEx" (string, string, string): string

script JwtGenerateAndVerify(): boolean
var
  CRLF: string
  CRLF2: string

  Header: string
  Payload: string

  HeaderAndPayload: string
  HeaderAndPayloadEncoded: string

  SecretKey: string
  SecretKeyEncoded: string

  Signature: string
  SignatureExpected: string

  Token: string
  TokenExpected: string

  P: integer
  Dummy: string
begin
  CRLF := GetAsciiCharByDec(13) + GetAsciiCharByDec(10)
  CRLF2 := CRLF + CRLF

  Header := "{""alg"":""HS256"",""typ"":""JWT""}"
  Header := ConvertEncoding("", Header, "BASE64URL")

  Payload := "{""sub"":""1234567890"",""name"":""John Doe"",""iat"":1516239022}"
  Payload := ConvertEncoding("", Payload, "BASE64URL")

  HeaderAndPayload := Header + "." + Payload
  HeaderAndPayloadEncoded := ConvertEncoding("", HeaderAndPayload, "BASE64")

  SecretKey := "your-256-bit-secret"
  SecretKeyEncoded := ConvertEncoding("", SecretKey, "BASE64")

  Signature := ComputeHmac("SHA256", HeaderAndPayloadEncoded, SecretKeyEncoded)
  Signature := ConvertEncoding("BASE64", Signature, "BASE64URL")

  Token := HeaderAndPayload + "." + Signature

  // ---------------------------------------------------------------------------

  // jwt.io
  TokenExpected := "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"

  if Token = TokenExpected then
    write("Token " + CRLF2 + Token + CRLF2 + " successfully generated")
  else
    write("ERROR: Token " + CRLF2 + TokenExpected + CRLF2 + " expected but " + CRLF2 + Token + CRLF2 + " found")
  end

  // ---------------------------------------------------------------------------

  P := StrPosRight(".", Token)

  StrLeft(Token, P - 1, HeaderAndPayload, Dummy)
  StrLeft(Token, P, Dummy, SignatureExpected)

  HeaderAndPayloadEncoded := ConvertEncoding("", HeaderAndPayload, "BASE64")

  Signature := ComputeHmac("SHA256", HeaderAndPayloadEncoded, SecretKeyEncoded)
  Signature := ConvertEncoding("BASE64", Signature, "BASE64URL")

  result := Signature = SignatureExpected

  if result then
    write("Signature successfully verified")
  else
    write("ERROR: Signature " + CRLF2 + SignatureExpected + CRLF2 + " expected but " + CRLF2 + Signature + CRLF2 + " found")
  end
end