11
votes

I'm trying to understand the logic of using JSON web tokens with private/public keys (RS512) when signing a payload of data sent from a client (in this case, a React Native App) to my server.

I thought the whole point of private/public keys was to keep the private key private (on my server) and hand the public key to the person who's successfully logged into the app.

I thought, with each API request to my server, the authenticated user of the app would use the public key to create the JWT (on the client side) and the server would use the private key to verify the signature/payload from the API request.

It seems I have it backwards because everywhere I read, you're supposed to sign a JWT with the private key -- but that goes against my understanding of who's in possession of the keys.

Depending on how the keys are created, some private keys can have a passcode which is supposed to be secret! So if the private key and the secret is out in the open (in client-side code) how secure can that be?

And where does the encryption come in? If the user of the app is sending sensitive data in the API, am I supposed to encrypt the payload and sign it with the JWT on the client side and then let the server verify the JWT signature and decrypt the data?

This tutorial was helpful https://medium.com/@siddharthac6/json-web-token-jwt-the-right-way-of-implementing-with-node-js-65b8915d550e but it seems backwards.

Any explanation would definitely help because all of the on-line tutorials aren't making sense.

Thank you.

2
JWTs are usually NOT used for encrypting/decrypting of payload. They are solemnly used for authentication and authorization. The website you are linking to is describing the process correctly. A user logs in at an authorization server and receives a JWT token which is signed with the private key of the authorization server. The user then attaches this very JWT to every sent request. The authorization server then verifies whether the JWT was issued by this authorization server and if it was tampered by someone by verifying its signature with the public key.pero_hero
I think you are confused by two different terms; signing and encryption. The data is encrypted using the public key and decrypted using the private key. On the other hand, you use your private key to sign your data and use your public key to verify it.R.Cha

2 Answers

15
votes

With JWT, the possession and the use of the key materials is exactly the same as any other contexts where cypher operations occur.

For signing:

  • The private key is owned by the issuer.
  • The public key can be shared with all parties that need to verify the signature.

For encryption:

  • The private key is owned by the recipient
  • The public key can be shared to any party that want to send sensitive data to the recipient.

The encryption is rarely used with JWT. Most of the time the HTTPS layer is sufficient and the token itself only contain a few information that are not sensitive (datatime, IDs...). The issuer of the token (the authentication server) has a private key to generate signed tokens (JWS). These tokens are sent to the clients (an API server, a web/native application...). The clients can verify the token with the public key.

If you have sensitive data that shall not be disclosed to a third party (phone numbers, personnal address...), then the encrypted tokens (JWE) is highly recommended. In this case, each client (i.e. recipient of a token) shall have a private key and the issuer of the token must encrypt the token using the public key of each recipient. This means that the issuer of the token can select the appropriate key for a given client.

3
votes

Solutions for JWT and JWE in React Native and Node Backend

The hardest part was finding a method that works in both RN and Node because I can't just use any Node library in RN so the crypto and jwt packages I install in the App and on the server have to work together.

I'm transmitting all of the API calls over HTTPS so the encryption part is probably overkill anyway, as Florent mentioned.

Method #1 is cleaner but I prefer Method #2 because it gives me more control over what is encrypted and how the JWT is created. This lets me validate the JWT before I attempt to decrypt the payload.

Method #1

Create a JWE to encrypt the token and payload simultaneously.

Pros:

  1. Conforms to accepted encryption/security standards.
  2. Much less code.
  3. Don't need to keep track of secret passwords because we're just using a public/private key pair only known by the server and the app -- created at login.

Cons:

  1. I don't see a way to customize the JWT. When making a simple JWT, I could set an explicit expiration time of 60s or less. I don't see a way to do that with a JWE.
  2. The errors thrown when decrypting a JWE are not as helpful. It'll either work or fail. With JWT decryption, you're given good error messages if something fails or is not valid.

React Native App Code

import {JWK, JWE} from 'react-native-jose';

/**
 * Create JWE encrypted web token
 *
 * @param payload
 * @returns {Promise<string>}
 */
async function createJWEToken(payload = {}) {

  // This is the Public Key created at login. It is stored in the App.  
  // I'm hard-coding the key here just for convenience but normally it 
  // would be kept in a Keychain, a flat file on the mobile device, or 
  // in React state to refer to before making the API call.

  const publicKey = `-----BEGIN PUBLIC KEY-----
MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEApl9FLYsLnP10T98mT70e
qdAeHA8qDU5rmY8YFFlcOcy2q1dijpgfop8WyHu1ULufJJXm0PV20/J9BD2HqTAK
DZ+/qTv4glDJjyIlo/PIhehQJqSrdIim4fjuwkax9FOCuFQ9nesv32hZ6rbFjETe
QSxUPjNzsYGOuULWSR3cI8FuV9InlSZQ7q6dEunLPRf/rZujxiAxGzY8zrMehjM5
LNdl7qDEOsc109Yy3HBbOwUdJyyTg/GRPwklLogw9kkldz5+wMvwOT38IlkO2rCr
qJpqqt1KmxdOQNbeGwNzZiGiuYIdiQWjilq5a5K9e75z+Uivx+G3LfTxSAnebPlE
LwIDAQAB
-----END PUBLIC KEY-----`;

  try {

    const makeKey = pem => JWK.asKey(pem, 'pem');
    const key = await makeKey(publicKey);

    // This returns the encrypted JWE string

    return await JWE.createEncrypt({
      zip:    true,
      format: 'compact',
    }, key).update(JSON.stringify(payload)).final();

  } catch (err) {
    throw new Error(err.message);
  }

}

Node Backend

const keygen = require('generate-rsa-keypair');
const {JWK, JWE} = require('node-jose');

/**
 * Create private/public keys for JWE encrypt/decrypt
 *
 * @returns {Promise<object>}
 *
 */
async function createKeys() {

  // When user logs in, create a standard RSA key-pair.
  // The public key is returned to the user when he logs in.
  // The private key stays on the server to decrypt the message with each API call.
  // Keys are destroyed when the user logs out.

  const keys = keygen();
  const publicKey = keys.public;
  const privateKey = keys.private;

  return {
    publicKey,
    privateKey
  };

}

/**
 * Decrypt JWE Web Token
 *
 * @param input
 * @returns {Promise<object>}
 */
async function decryptJWEToken(input) {

  // This is the Private Key kept on the server.  This was
  // the key created along with the Public Key after login.
  // The public key was sent to the App and the Private Key
  // stays on the server.
  // I'm hard-coding the key here just for convenience but 
  // normally it would be held in a database to 
  // refer during the API call.

  const privateKey = `-----BEGIN RSA PRIVATE KEY-----
MIIEpAIBAAKCAQEApl9FLYsLnP10T98mT70eqdAeHA8qDU5rmY8YFFlcOcy2q1di
jpgfop8WyHu1ULufJJXm0PV20/J9BD2HqTAKDZ+/qTv4glDJjyIlo/PIhehQJqSr
dIim4fjuwkax9FOCuFQ9nesv32hZ6rbFjETeQSxUPjNzsYGOuULWSR3cI8FuV9In
lSZQ7q6dEunLPRf/rZujxiAxGzY8zrMehjM5LNdl7qDEOsc109Yy3HBbOwUdJyyT
g/GRPwklLogw9kkldz5+wMvwOT38IlkO2rCrqJpqqt1KmxdOQNbeGwNzZiGiuYId
iQWjilq5a5K9e75z+Uivx+G3LfTxSAnebPlELwIDAQABAoIBAQCmJ2FkMYhAmhOO
LRMK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1dqeCY1sOFLmg/NlYooO1t5oYM
bNDYOkFMzHTOeTUwbuEbCO5CEAj4psfcorTQijMVy3gSDJUuf+gKMzVubzzmfQkV
syUSjC+swH6T0SiEFYlU1FTqTGKsOM68huorD/HEX64Bt9mMBFiVyA==
-----END RSA PRIVATE KEY-----`;

  try {

    const makeKey = pem => JWK.asKey(pem, 'pem');
    const key = await makeKey(privateKey);

    // This returns the decrypted data

    return await JWE.createDecrypt(key).decrypt(input);

  } catch (err) {
    throw new Error(err.message);
  }

}

Method #2

Create a JWT and encrypt the payload yourself.

The JS below shows how I create the JWT and encrypt the data in React Native and then verify the token and decrypt the data in a Node backend.

When the user logs in, I'll pass back a secret key for the JWT and a separate secret key for the encryption (if necessary) that only lasts for the duration of the session. After they logout, the keys are destroyed.

I'm also keeping the JWT expires time to something like 60 seconds just to be safe.

Pros:

You have more control over the JWT in terms of setting the expiration time.

Cons:

Could be slower because you have to create the JWT and encrypt the payload in separate steps.

React Native App

import jwt from 'react-native-pure-jwt';
import CryptoJS from 'react-native-crypto-js';

/**
 * Create JWT Signature from payload for API call
 *
 * @param payload {object|string} - payload to add to JWT
 * @param encrypt {boolean} - encrypt the payload
 *
 */
async function createJWT(payload, encrypt = false) {

  try {

    const signature = await jwt.sign({

        // REQUIRED: Payload
        // Any data you want to pass in the JWT
        // Two options:
        // 1. Send the payload without encryption.
        //      No need to stringify payload. Just send it as-is.
        // 2. Send the payload as an encrypted string.
        //      Use the CryptoJS library with a 'another-secret-key' that the App and the server share.
        //      Payload needs to be stringified.

        data: encrypt ? CryptoJS.AES.encrypt(JSON.stringify(payload), 'another-secret-key').toString() : payload,

        // REQUIRED: Expires Time
        // Milliseconds since 1970 when the token can no longer be decoded.
        // Here, I've set the value to however many seconds I want the token to last.
        // The clock starts ticking from the moment this token was created.  Afer the time has expired,
        // the token can't be decoded by anyone.

        exp: new Date().getTime() + 60 * 1000,

        // OPTIONAL: Issuer Claim
        // String that identifies whoever issued this JWT.
        // The JWT is coming from my App so I'll use the App name here.

        iss: 'APP ID',

        // OPTIONAL: Subject Claim
        // String that uniquely identifies the subject of the JWT.
        // The I'll probably use the Username or User ID of the person using the App.

        sub: 'UNIQUE USER ID',

      },

      // REQUIRED: Secret Key
      // This is the string that is used to encode/decode the JWT.
      // Here, I'll probably use something that's unique to the user's account on the App such
      // as a password or strong token that's stored in the user's Keychain and that's
      // also in a database the server can retrieve.

      'my-secret-key',

      {

        // REQUIRED: Algorithm
        // What algorithm is being used to encode the JWT
        // The supported algorithms by react-native-pure-jwt are HS256, HS384, HS512.
        // The higher the number, the better the security but it will also take longer to encode/decode the token.
        // I would prefer to use RS256 or RS512 but those algorithms aren't supported
        // by the react-native-pure-jwt package as far as I can tell.

        alg: 'HS256',

      },
    );

    return signature;

  } catch (err) {

    throw new Error(err.message);

  }

}

Node Backend

const jwt = require('jsonwebtoken');
const CryptoJS = require('crypto-js');

/**
 * Decode JWT Signature from API call
 *
 * @param token {string}
 * @param decrypt {boolean} - decrypt the payload
 *
 */
async function decodeJWT(token, decrypt = false) {

  // Use the same options to decode the JWT that were used to encode the JWT.

  const options = {
    issuer:  'APP ID',
    subject: 'UNIQUE USER ID',
  };

  // Use the same Secret Key that was used to encode the JWT.
  // This should be a password or some hidden value that is only
  // known by the App and the Server such as the user's password or previously
  // agreed upon strong token shared after login and discarded after logout.

  const secretJWTKey = 'my-secret-key';

  // If decrypting an encrypted payload, you'll also need the encryption secret
  // which should ideally not be the same as the secretJWTKey.
  // It can also be some hidden value that is only known by the App and the Server such
  // an agreed upon strong token shared after login and discarded after logout.

  const secretDecryptKey = 'another-secret-key';

  return new Promise((resolve, reject) => {

    try {

      // First check if the token is valid. Otherwise, it will throw an error.

      const verified = jwt.verify(token, secretJWTKey, options);

      let data = verified.data;

      if (decrypt) {

        // If the payload is encrypted, unwind it into an object or string.

        const bytes = CryptoJS.AES.decrypt(data, secretDecryptKey);
        data = JSON.parse(bytes.toString(CryptoJS.enc.Utf8));

      }

      resolve(data);

    } catch (err) {

      // If the token is not valid or the decryption failed.

      reject(err.message);

    }

  });

}

Example

async function test() {

  // Create the JWT and encrypt the payload (optional) in React Native

  const tokenSignature = await createJWT({
    name: 'Marc',
    password: 'P@55w0rd',
    cc: 'Visa',
    cc_num: '4400-0000-0000-0000'
    phone: '704-000-0000'
    info: {
      birthdate: '1970-00-00',
      ssn: '000-00-0000',
    },
  }, true).catch(err => {

    console.log('Error creating signature', err);

  });

  // Use the JWT signature to make the https api call.

  // On the server...
  // Decode the JWT and decrypt the payload (optional)

  const data = await decodeJWT(tokenSignature, true).catch(err => {

    console.log('Error retrieving data', err);

  });

  // Use the data to update the database, etc.

  console.log({data});

}