简体   繁体   中英

How to calculate the HMAC(hsa256) of a text using a public certificate (.pem) as key

I'm working on Json Web Tokens and wanted to reproduce it using python, but I'm struggling on how to calculate the HMAC_SHA256 of the texts using a public certificate (pem file) as a key.
Does anyone know how I can accomplish that!?

Tks

Ok, I got this after 22 hours of study/google.


Spoiler Alert

Since this is one of pentesterlab's pro exercises, I'll not post the code demonstrating how to generate a full JWT using HSA256. Instead, it'd be better if I post how to do calculate the HSA256 using a pem file in python, as it was my original question:

import hashlib
import hmac

key = open("public_cert.pem","r").read()
signature = hmac.new(key, unsignedToken, digestmod=hashlib.sha256).digest()
print signature

Basically we just need to read the public key file and use the hmac.new(..) function, setting hashlib.sha256 as the digest to be used. The "unsignedToken" is the JWT text (or declarations) that we wanted to calculate the signature.

For those still trying to figure it out how to create a valid JWT for pentesterlab's exercise, the only hint I can give is to urlsafe-base64 encode everything. There is also a python module, named "pyjwt" that can be used, but its source code must be edited to allow public keys to be used as a HMAC key.

In case any one found this question. The answer provided by the host works, but the idea is wrong. You don't use any RSA keys with HMAC method. The RSA key pair (public and private) are used for asymmetric algorithm while HMAC is symmetric algorithm.

In HMAC, the two sides of the communication keep the same secret text(bytes) as the key. It can be a public_cert.pem as long as you keep it secretly. But a public.pem is usually shared publicly, which makes it unsafe.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM