Zaubrik / djwt

Create and verify JSON Web Tokens (JWT) with Deno or the browser.
MIT License
225 stars 23 forks source link

How to use Cert files #56

Closed itohatweb closed 3 years ago

itohatweb commented 3 years ago

I noticed djwt now wants a CryptoKey and not cert strings anymore. Since I'm pretty new to crypto I would love to have an example of how to use eg RSA key files.

timonson commented 3 years ago

Hi, to generate a CryptoKey or a CryptoKeyPair from existing keys you can use the importKey method from the Web Crypto API. You should be able to use your .pem files with this method.

Please take a look at this documentation and the containing examples and let me know if they helped: https://developer.mozilla.org/en-US/docs/Web/API/SubtleCrypto/importKey

If you just want to generate a CryptoKeyPair I added an example for the RS384 algorithm here.

Thanks!

itohatweb commented 3 years ago

Looks like pkcs8 is not available in deno 🤔

koanzen commented 3 years ago

@TS

Easiest way is to declare a Global var for your key and use it to create and verify your JWT.

Just put this code in your Starting Application


declare global { var keys: any; interface Window { keys: any; } }

window.keys = await crypto.subtle.generateKey( { name: "RSASSA-PKCS1-v1_5", modulusLength: 4096, publicExponent: new Uint8Array([1, 0, 1]), hash: "SHA-384", }, true, ["verify", "sign"], )

to create JWT token:

const jwtpayload: Payload = { sub: "1234567890", name: "John Doe", admin: true, iat: 1516239022, }

const jwtheader: Header = { alg: "RS384",typ: "JWT" }

const jwt = await create(jwtheader,jwtpayload,keys.privateKey)

to verify:

await verify(jwt,keys.publicKey)


I think this is not a good practice but it works, hope it will help.

Edited: Derived from RSA of timonson.

itohatweb commented 3 years ago

For my application I need to use RSA and I need the tokens to be valid even after a restart.

timonson commented 3 years ago

Hi @itohatweb , pkcs8 has been implemented by the deno authors now.

I added an example for generating, exporting and importing a key in pkcs8 format here. Does it help?

itohatweb commented 3 years ago

Yes thank you.