How to Create a JSON Web Token (Jwt) Using Openssl Shell Commands

How to create a Json Web Token (JWT) using OpenSSL shell commands?

I was able to recreate the JWT from https://jwt.io/

In your example, there was a hidden newline on the user secret. So in the below, I also add on that newline, purely to recreate the desired output.
Also the email address in your payload was not consistent, so for below I have used jordan@example.com.

I took a slightly different approach to the hmac step. I converted the user secret to hex bytes and used that as the key (using the hexkey option for the HMAC).

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

# ans: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9

# Construct the payload
payload=$(echo -n '{"email":"jordan@example.com"}' | base64 | sed s/\+/-/g |sed 's/\//_/g' | sed -E s/=+$//)

# ans: eyJlbWFpbCI6ImpvcmRhbkBleGFtcGxlLmNvbSJ9

# Store the raw user secret (with example of newline at end)
secret=$'bigsecretisveryhardtoguessbysneakypeopleright\n'

# Note, because the secret may have newline, need to reference using form $""
echo -n "$secret"

# Convert secret to hex (not base64)
hexsecret=$(echo -n "$secret" | xxd -p | paste -sd "")

# ans: 62696773656372657469737665727968617264746f67756573736279736e65616b7970656f706c6572696768740a

# For debug, also display secret in base64 (for input into https://jwt.io/)
echo -n "$secret" | base64

# ans: Ymlnc2VjcmV0aXN2ZXJ5aGFyZHRvZ3Vlc3NieXNuZWFreXBlb3BsZXJpZ2h0Cg==

# Calculate hmac signature -- note option to pass in the key as hex bytes
hmac_signature=$(echo -n "${jwt_header}.${payload}" | openssl dgst -sha256 -mac HMAC -macopt hexkey:$hexsecret -binary | base64 | sed s/\+/-/g | sed 's/\//_/g' | sed -E s/=+$//)

# Create the full token
jwt="${jwt_header}.${payload}.${hmac_signature}"

# ans: eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImpvcmRhbkBleGFtcGxlLmNvbSJ9.C3MVjfmnul8dLNIgiv6Dt3jSefD07Y0QtDrOZ5oYSXo

Create RS256 JWT in bash

Successfully resolved this. It was caused by a couple of issues:

  1. openssl base64 inserts carriage returns every 70-odd characters by default. I believe you can override this, but just using the base64 command instead solved that.
  2. My signing step was wrong. I replaced rsautl with dgst as follows:

    openssl dgst -sha256 -sign private.key -out sig.txt unsigned.b64

RS256 signatures now pass validation in jwt.io

Complete working code (for posterity):

cat header.txt | tr -d '\n' | tr -d '\r' | base64 | tr +/ -_ | tr -d '=' > header.b64
cat payload.txt | tr -d '\n' | tr -d '\r' | base64 | tr +/ -_ |tr -d '=' > payload.b64
printf "%s" "$(<header.b64)" "." "$(<payload.b64)" > unsigned.b64
rm header.b64
rm payload.b64
openssl dgst -sha256 -sign -privateKey2.key -out sig.txt unsigned.b64
cat sig.txt | base64 | tr +/ -_ | tr -d '=' > sig.b64
printf "%s" "$(<unsigned.b64)" "." "$(<sig.b64)" > jwt.txt
rm unsigned.b64
rm sig.b64
rm sig.txt

How do you create an RS256 JWT assertion with bash/shell scripting?

Consider the following, which supports both HS256 and RS256:

#!/usr/bin/env bash

# Inspired by implementation by Will Haley at:
# http://willhaley.com/blog/generate-jwt-with-bash/

set -o pipefail

# Shared content to use as template
header_template='{
"typ": "JWT",
"kid": "0001",
"iss": "https://stackoverflow.com/questions/46657001/how-do-you-create-an-rs256-jwt-assertion-with-bash-shell-scripting"
}'

build_header() {
jq -c \
--arg iat_str "$(date +%s)" \
--arg alg "${1:-HS256}" \
'
($iat_str | tonumber) as $iat
| .alg = $alg
| .iat = $iat
| .exp = ($iat + 1)
' <<<"$header_template" | tr -d '\n'
}

b64enc() { openssl enc -base64 -A | tr '+/' '-_' | tr -d '='; }
json() { jq -c . | LC_CTYPE=C tr -d '\n'; }
hs_sign() { openssl dgst -binary -sha"${1}" -hmac "$2"; }
rs_sign() { openssl dgst -binary -sha"${1}" -sign <(printf '%s\n' "$2"); }

sign() {
local algo payload header sig secret=$3
algo=${1:-RS256}; algo=${algo^^}
header=$(build_header "$algo") || return
payload=${2:-$test_payload}
signed_content="$(json <<<"$header" | b64enc).$(json <<<"$payload" | b64enc)"
case $algo in
HS*) sig=$(printf %s "$signed_content" | hs_sign "${algo#HS}" "$secret" | b64enc) ;;
RS*) sig=$(printf %s "$signed_content" | rs_sign "${algo#RS}" "$secret" | b64enc) ;;
*) echo "Unknown algorithm" >&2; return 1 ;;
esac
printf '%s.%s\n' "${signed_content}" "${sig}"
}

(( $# )) && sign "$@"

...usage as:

rsa_secret='
-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEAtHEDjwkBpsjhit+wXZMMj2AaRHyWSKatjzLtVEGdyXrbQGgQ
PjbfqPtqKsBPjcifHh8VAgrEtETbLN8pbE/XLRaB9P76hib6DATBn2JC6XG/NkAu
0b2F8WB6ZuJh3fbubSOZaORRIyRvfidV5Wjb7NbEDhuSxFLaq0ad2+rQHyBgMfQS
43OqhEa463WQt5F9NuWRTqweh5UotT6Mg9YgkvmBdA4IbJMEDWGFNecUzAGuESYq
wzJaaQ4S58ce7HxFDywM0nFXlNx1pxZwZOZfG7bddUD8FuwbBMx5c3Z3U8LAA+J/
50A/kxuZoa6sRTb7gXfBxy2riechlOTL+5ut3wIDAQABAoIBAD8bm5wGEV7MuR1B
+MPxbx4iBW3YiRMlwGPp8tlaDZ5u6onPG4c21+iY7du/4NL8zLHTOxy4uW02+9To
w+sOzXoGejM+jk4nCaL0cueUjURqNO77aaSPfW4bSRP8ry/bci4Xmkr2N25sCtZ7
WW5fyzM9NdqdSCqDs9jdXM6ShHGt4aG1w4Q38pfl2O2KUqgGYA8j8S7oEpcuApIj
sNH8o2PIFaFuRoUBq6WxSZBY7YdvKM0xlE0NKiDMAUIeTIRqtm8GPo7ot8dV6VHU
EglN7gaEve75XW0DAkK2lDDpGPlVHJwLgKGiSuW0qMh6lY+dKjsZ8wyz85DqTnyo
+42ZI6kCgYEA36X4c4a/tlh0A6i+EaA1CqmN8jh3nNMYgZvovTnIezCvO+RuJJEG
KQQjr8/z+E8FYobImrrZsuSL+UFs1trl/nSndWh22B7fQQbJBdHwhv39YWReS0tW
7t3LJJG3oQnR/ChlqyTToHfS0WcdtYQ0cnFWSx73Hg/S+cu0vHtcUrUCgYEAzosH
dXq1VGRgf3TIoI9s4xJt/SnH+VHtP4dvLKzY7NN4K76DIYdQIn1xQ1Y3705v/XG+
xTNAaoOaH6hBnRxwxcv6GmCpICJ2C21puxA63RqCslab5fc23wvMv/wwoEWPtXhf
3OOKZxszLR1vFqZaYTWzVmTxg+r5b2aNBB0MtsMCgYBAv+6Ek/ihNE6yWIJe3AE/
SwOboxmOP9eSfq8NSdNvRxMUxffVgl9ENLyYRB6gP1CRy+/8TCiHEIAt8/Es60c3
OlLZPRtbSuTcELjWhIecraBUOBjMt809bt1HgyCk8RDoblGxEQJsLQTON4p0aQg+
Me4H5bkp7O7p/z4ea6C5GQKBgQCewy+QliocHKwwTMyK3rSMNvZky2DzvI3pb2l9
pb95C3Qr691QQHrQiCwv3m5QfLKI1o4VdzfkqBQokWUeJ2ZoJEqzS+m00ch7MDc9
m1Qj8OTVwM1FD6oV+TQBvxCBofa9PzIw0JbqenX0D9P8TRLb9jNMDXu4Mz5Y6zMq
HkpPkQKBgQCgrcW7U0Q+081N25VfghCPRd/o+dtqP3udXgj0nIX6y3qeCJiPeamZ
plMNqdZScaK37wMouAIPD0u5w1OCnlepuUxU3h5y55Lzx3PnDlU1H+yfBsTi1KL/
sDjgs31j//w80krxJNj5/i2AeYzATmybPwyM/c/PVBv/hecreUbTlQ==
-----END RSA PRIVATE KEY-----
'

test_payload='{
"Id": 1,
"Name": "Hello, world!"
}'
sign rs256 "$test_payload" "$rsa_secret"

Create JWT from secrete and payload in Spring boot

You could do something like this:

add this to your pom.xml:

<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-security</artifactId>
</dependency>
<dependency>
<groupId>io.jsonwebtoken</groupId>
<artifactId>jjwt</artifactId>
<version>0.9.1</version>
</dependency>
</dependencies>

and create a util class for generating your tokens:

@Service
public class JwtUtil {

private String secret;
private int jwtExpirationInMs;

@Value("${jwt.secret}")
public void setSecret(String secret) {
this.secret = secret;
}

@Value("${jwt.expirationDateInMs}")
public void setJwtExpirationInMs(int jwtExpirationInMs) {
this.jwtExpirationInMs = jwtExpirationInMs;
}

// generate token for user
public String generateToken(UserDetails userDetails) {
Map<String, Object> claims = new HashMap<>();
Collection<? extends GrantedAuthority> roles = userDetails.getAuthorities();
if (roles.contains(new SimpleGrantedAuthority("ROLE_ADMIN"))) {
claims.put("isAdmin", true);
}
if (roles.contains(new SimpleGrantedAuthority("ROLE_USER"))) {
claims.put("isUser", true);
}
return doGenerateToken(claims, userDetails.getUsername());
}

private String doGenerateToken(Map<String, Object> claims, String subject) {
return Jwts.builder().setClaims(claims).setSubject(subject)
.setIssuedAt(new Date(System.currentTimeMillis()))
.setExpiration(new Date(System.currentTimeMillis() + jwtExpirationInMs))
.signWith(SignatureAlgorithm.HS512, secret).compact();
}

}

Take a look at hashicorp vault for a secure way of storing your secret (you dont want this in your
property file)

add the following to your properties file and choose sensible defaults for your use case:

jwt.jwtExpirationInMs=18000000

you can modify the algorithm to HS256 on this line:

return Jwts.builder()
.setClaims(claims)
.setSubject(subject)
.setIssuedAt(
new Date(System.currentTimeMillis())).setExpiration(new Date(System.currentTimeMillis()+jwtExpirationInMs)
)
.signWith(SignatureAlgorithm.HS512,secret).compact();

but I prefer HS512 (it's faster on 64 bit machines)

Verifying JWT (RS256) using OpenSSL

The signature of a JWT is base64url encoded and needs to be decoded first.
The suggested duplicate only deals with a base64 encoded signature and openssl seems not to be working with base64url encoding.

If you're working on a Windows system, you can decode the signature file with certutil, which can directly decode bas64url:

certutil -decode signature.txt signature.sha256

Then use the signature.sha256 as input for openssl:

openssl.exe dgst -sha256 -verify pubkey.pem -signature signature.sha256 data.txt

Then you should get the result:

Verified OK

Generated JSON Web Signature in Java produce invalid signature

It looks like you are using the SHA-256 digest of "secret" as the key to create the MAC, and plain old "secret" for validating. Replace:

byte[] bytes = new byte[32];
String message = "secret";
MessageDigest md = MessageDigest.getInstance("SHA-256");
bytes = md.digest(message.getBytes("UTF-8"));

JWSSigner signer = new MACSigner(bytes);

with:

JWSSigner signer = new MACSigner("secret");

How to manually validate a JWT signature using online tools

It's all a matter of formats and encoding.

On https://jwt.io you get this token based on your input values and secret:

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.3pIaKksiX9Zv8Jg-hWbrD24VhL36hBIFaNpA4fVx29M

We want to prove that the signature:

3pIaKksiX9Zv8Jg-hWbrD24VhL36hBIFaNpA4fVx29M

is correct.

The signature is a HMAC-SHA256 hash that is Base64url encoded.
(as described in RFC7515)

When you use the online HMAC generator to calculate a hash for

eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ

with the secret

hONPMX3tHWIp9jwLDtoCUwFAtH0RwSK6

you get

de921a2a4b225fd66ff0983e8566eb0f6e1584bdfa84120568da40e1f571dbd3

as result, which is a HMAC-SHA256 value, but not Base64url encoded. This hash is a hexadecimal string representation of a large number.

To compare it with the value from https://jwt.io you need to convert the value from it's hexadecimal string representation back to a number and Base64url encode it.

The following script is doing that and also uses crypto-js to calculate it's own hash. This can also be a way for you to verify without JWT libraries.

var CryptoJS = require("crypto-js");

// the input values
var base64Header = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9";
var base64Payload = "eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ";
var secret = "hONPMX3tHWIp9jwLDtoCUwFAtH0RwSK6";

// two hashes from different online tools
var signatureJWTIO = "3pIaKksiX9Zv8Jg-hWbrD24VhL36hBIFaNpA4fVx29M";
var onlineCaluclatedHS256 = "de921a2a4b225fd66ff0983e8566eb0f6e1584bdfa84120568da40e1f571dbd3";

// hash calculation with Crypto-JS.
// The two replace expressions convert Base64 to Base64url format by replacing
// '+' with '-', '/' with '_' and stripping the '=' padding
var base64Signature = CryptoJS.HmacSHA256(base64Header + "." + base64Payload , secret).toString(CryptoJS.enc.Base64).replace(/\+/g,'-').replace(/\//g,'_').replace(/\=+$/m,'');

// converting the online calculated value to Base64 representation
var base64hash = new Buffer.from(onlineCaluclatedHS256, 'hex').toString('base64').replace(/\//g,'_').replace(/\+/g,'-').replace(/\=+$/m,'')


// the results:
console.log("Signature from JWT.IO : " + signatureJWTIO);
console.log("NodeJS calculated hash : " + base64Signature);
console.log("online calulated hash (converted) : " + base64hash);

The results are:

Signature from JWT.IO             : 3pIaKksiX9Zv8Jg-hWbrD24VhL36hBIFaNpA4fVx29M

NodeJS calculated hash : 3pIaKksiX9Zv8Jg-hWbrD24VhL36hBIFaNpA4fVx29M

online calulated hash (converted) : 3pIaKksiX9Zv8Jg-hWbrD24VhL36hBIFaNpA4fVx29M

identical!

Conclusion:

The values calculated by the different online tools are all correct but not directly comparable due to different formats and encodings.
A little script as shown above might be a better solution.



Related Topics



Leave a reply



Submit