Create HS256 in linux command

Hello, I need to create HS256 to save this for encryption, in this elixir I can do it with:

JOSE.JWS.generate_key(%{"alg" => "HS256"}) |> JOSE.JWK.to_map |> elem(1)

but how can I do this in linux command? because I have a shell which creates docker image for me.

I see this page but I think this page result is different with elixir code


I suggest this would appear to be doing what you ask using using openssl.

1 Like

Thanks, when I create the “k” with linux command:

$(echo -n '{"alg":"HS256","typ":"JWT"}' | base64 | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)

this will be 36 characters, but when I use

JOSE.JWS.generate_key(%{"alg" => "HS256"}) |> JOSE.JWK.to_map |> elem(1)
  "alg" => "HS256",
  "k" => "4gOvXdZuoc9_iffdfDnZB2lsxhEePhUe16pFbQXX9Mc",
  "kty" => "oct",
  "use" => "sig"

it will be 43 characters, why are these difference between? what does mean "k" => and how to create this?


from JWK Parameters for Symmetric Keys

The k (key value) member contains the value of the symmetric (or other single-valued) key. It is represented as the base64url encoding of the octet sequence containing the key value.

JOSE adds that “k” field as a random string generated by: crypto:strong_rand_bytes(Size) (In case of HS256 eventually it happens here)

you can try:

iex> {_, _, {_, key}, _} = :jose_jws_alg.generate_key({:oct, 32}, "HS256")
{:jose_jwk, :undefined,
  <<228, 203, 21, 38, 196, 206, 135, 106, 22, 209, 53, 114, 53, 199, 255, 223,
    52, 25, 242, 56, 5, 215, 65, 135, 13, 217, 14, 38, 235, 214, 135, 165>>},

iex> :jose_jwa_base64url.encode(key)

# which is basically the same as
iex> Base.url_encode64(key, padding: false)

So in bash probably something like

dd if=/dev/urandom bs=32 count=1 | base64 | sed 's/+/-/g; s/\//_/g; s/=//g'

Could generate you similarly random password to put into "k" field of the map