How to manually generate JWE using jsrsasign?

295 Views Asked by At

I'm trying to manually build a JWE payload following https://www.rfc-editor.org/rfc/rfc7516#section-3 (so I an better learn it) in Javascript and for that I'm using the jsrsasign library.

I've created a JOSE header and now I need to create a random Content Encryption Key (CEK) and then I encrypt it with the target's RSA public key creating a JWE Encryption Key. If I understood the spec correctly the CEK should be byte array and after the RSA encryption I'll format the result using BASE64URL.

The jsrsasign.KJUR.crypto.Cipher.encrypt docs says that input must be string but when I passed an Array buffer it didn't complain however I'm unsure if this way I'll end up with a broken JWE Encryption Key.

Can some one help me ou and confirm if I'm doing it wrong or not?

const header = {"alg":"RSA-OAEP-256","enc": "A256GCM"};
const jweProtectedHeader = jsrsasign.utf8tob64u(JSON.stringify(header));
const cek = jsrsasign.hextoArrayBuffer(jsrsasign.KJUR.crypto.Util.getRandomHexOfNbits(256));
const pKey = jsrsasign.KEYUTIL.getKey(targetPublicKey);
const encryptedCek = jsrsasign.KJUR.crypto.Cipher.encrypt(cek, pKey, "RSAOAEP");
const jweEncriptionKey = jsrsasign.hextob64u(encryptedCek);

Also, I noticed that the every time I generate a new cek using the getRandomHexOfNbits(256) the final Array is 33 long instead of 32, with the first byte zeroed. Is this expected or should I discard this first byte?

Thanks in advance

0

There are 0 best solutions below