October 21, 2024
Chicago 12, Melborne City, USA
javascript

Signing and encrypting data sent to frontend


I’m planning on sending some sensitive data to the font-end in an encrypted form, storing it for a short time and then sending it back to the backend where it’s decrypted and used. For this I guess I would need to both encrypt and sign the data for extra security. There are a lot of ways out there to accomplish this, be it with using the combination of jsonwebtoken and crypto packages to encrypt the payload and then sign it with either jsonwebtoken or jose or just use jose to do both. Both have their advantages and disadvantages..

My current solution is built purely on jose:
Encrypt and signing

export const signAndEncryptObject = async (
    obj: object,
    key: Uint8Array
): Promise => {
    const signedToken = await new jose.SignJWT(obj as JWTPayload)
        .setProtectedHeader({ alg: 'HS256' })
        .setIssuedAt()
        .setExpirationTime('1h')
        .sign(key);

    return await new jose.EncryptJWT({ jwt: signedToken })
        .setProtectedHeader({ alg: 'dir', enc: 'A256GCM' })
        .encrypt(key);
};

Decrypt and verification

export const verifyAndDecryptObject = async (
    token: string,
    key: Uint8Array
): Promise

I’ve seen few people recommend this approach, but I’m not sure whether it’s a good one, creating a JWT to store it in an encrypted JWT seems kind of complex.

What would be the best practice to handle this situation? Are there any better ways to to do the signing and encryption?



< h3>You need to sign in to view this answers

Leave feedback about this

  • Quality
  • Price
  • Service

PROS

+
Add Field

CONS

+
Add Field
Choose Image
Choose Video