Sample code for 30+ languages & platforms
React Native

Decrypt a JWE with a Private Key

See more JSON Web Encryption (JWE) Examples

Demonstrates Jwe.SetPrivateKey, which sets the private key used to decrypt a recipient of a loaded JWE.

The file path is relative to the application's current working directory. An absolute path may also be used. Supply the path appropriate to your own environment.

Background. The private key unwraps the content-encryption key that was wrapped with the corresponding public key during encryption.

Chilkat React Native Downloads

React Native
import { Jwe, PrivateKey } from '@chilkat/react-native'

function chilkatExample() {
  const jwe = new Jwe();

  // Load the JWE compact serialization to be decrypted.
  const jweCompact = 'eyJhbGciOiJBMjU2S1ciLCJlbmMiOiJBMjU2R0NNIn0.<...>.<iv>.<ciphertext>.<tag>';
  try {
    jwe.loadJwe(jweCompact);
  } catch {
    console.log(jwe.lastErrorText);
    return;
  }

  // The file path is relative to the application's current working directory.  An absolute path
  // may also be used.  Supply the path appropriate to your own environment.
  // Load the recipient's private key.
  const privKey = new PrivateKey();
  try {
    privKey.loadPemFile('qa_data/recipient_privkey.pem');
  } catch {
    console.log(privKey.lastErrorText);
    return;
  }

  // Set the private key used to decrypt recipient 0.
  try {
    jwe.setPrivateKey(0, privKey);
  } catch {
    console.log(jwe.lastErrorText);
    return;
  }

  let content: string;
  try {
    content = jwe.decrypt(0, 'utf-8');
  } catch {
    console.log(jwe.lastErrorText);
    return;
  }

  console.log(content);
}