jwtcoldfusion

Coldfusion JWT using string as key without keystore


I'm trying to do the following:

secret_key = "sometihng";
web_token = CreateSignedJWT(payload_string, secret_key, hash_params );

And I receive error: signOptions type not supported, it has to be of type Key or KeyPair or Struct

Coldfusion's jwt documentation states the secret_key parameter should be a struct, which I understand. However, I'm unclear on how to use the secret key as a string without using the keystore, because if I use

key_options = {
        key = secret_key
    }

web_token = CreateSignedJWT(payload_string, key_options, hash_params );

then I receive error Either the keystore path is invalid or corrupt or the keystore password is wrong.

The key itself is stored in an encrypted database column, so I want to pass a string version of it. How can I do this without the keystore?


Solution

  • For HS256, the key is a byte sequence of at least 32 bytes. If the key is Base64 encoded, it must first be Base64 decoded and then imported.

    The example for RS256 described in the documentation for CreateSignedJWT() looks as follows for HS256:

    <cfset text = {
        "iss" = "a",
        "sub" = "b",
        "abcd" = "efgh",
        "aud" = "adobe",
        "exp" = "#DateAdd("n", 30, now())#",
        "id"="cc",
        "iat"="#DateAdd("n", -30, now())#"
    }>
    
    <!--- Base64 decode and import key --->
    <cfset rawKeyeyB64 = "ViHV9/ImYwwnx8GLevuR4oB8QYST4izOiJzi8CCT+Yc=">
    <cfset rawKey = binaryDecode(rawKeyeyB64, "base64" )> 
    <cfset keySpec = createObject("java", "javax.crypto.spec.SecretKeySpec")>
    <cfset key = keySpec.init(rawKey, "HmacSHA256")>
    
    <cfset c = {
        "algorithm" = "HS256", <!--- specify HS256 algorithm --->
        "generateIssuedAt"= true,
        "generateJti"=true
    }>
    
    <cfset createjws = CreateSignedJWT(text, key, c)>
    <cfdump var = "#createjws#">
    

    Here, the Base64 decoding was carried out with binaryDecode() and the key import was implemented according to the documentation, sec. Using Java Objects.
    The script can be executed e.g. on trycf.com using the Adobe ColdFusion 2023 engine. A possible output is the following signed JWT (changes due to the dates):

    eyJhbGciOiJIUzI1NiJ9.eyJhdWQiOiJhZG9iZSIsInN1YiI6ImIiLCJpc3MiOiJhIiwiaWQiOiJmRGl6SHF0QnlNR096N3pIS2gtbEl3IiwiYWJjZCI6ImVmZ2giLCJleHAiOiJGZWJydWFyeSwgMjIgMjAyNCAyMDoyMDozNSIsImlhdCI6MTcwODYzMTQzNTI5MX0.0vJchMc2YvIXuq28tyH2vaAAW8vugYx5nc1HcK_L8qc
    

    which can be successfully verified on jwt.io using the Base64 encoded key.