0

Kindly ask you to help with the following. I'm trying to understand how the JOSE library works for JWE creating/validation in Node.js.

To create a JWE I need a secret key in KeyObject or Uint8Array format. I have a secret string in my .env file and want to create a secret key based on that.

const secret = Buffer.alloc(32, process.env.SECRET_KEY);
const jwe = await new jose.EncryptJWT({ userId: '1234532' })
.setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
.setIssuedAt()
.setIssuer('urn:example:issuer')
.setAudience('urn:example:audience')
.setExpirationTime('2h')
.encrypt(secret);

Works fine, we created a JWE.

Then I want to provide an invalid secret, changing my .env key.

const secretWithInvalidString = Buffer.alloc(32, process.env.INVALID_SECRET);
const { payload, protectedHeader } = await jose.jwtDecrypt(jwt, secretWithInvalidString, {
  issuer: 'urn:example:issuer',
  audience: 'urn:example:audience'
});

My JWE is still VALID but it shouldn't be as I changed a secret string in .env file.

After comparing two buffers with different strings I can see that they are equal, but why?

// returns true but why when provided strings to Buffer are different?
   console.log(console.log(secret.equals(secretWithInvalidString)));

P.S. I haven't worked with Buffers too much before :|

THANKS!

Gleb Gaiduk
  • 363
  • 4
  • 13
  • I'm not sure if it will help you to solve the problem, but I noticed that you're passing a variable called secret1 to the encrypt method, shouldn't you pass the secret variable? – Eduardo Sep 14 '22 at 14:58
  • Edited, but it's not the case here :) – Gleb Gaiduk Sep 14 '22 at 17:12

1 Answers1

0

I assume you're passing a string longer than 32 octets in either both cases or at least one of them and the different octets are at the end.

Buffer.alloc, the way you call it, allocates 32 bytes and fills it with whatever you pass but will not exceed the 32 bytes allocated.

You probably want to use Buffer.from instead.