Node.js XML Encryption

4.0.0 · active · verified Tue Apr 21

xml-encryption is a Node.js library that provides a W3C XML Encryption implementation. The current stable version is 4.0.0, released recently on March 31, 2026, indicating active development and maintenance. This library facilitates the encryption and decryption of XML documents, supporting various algorithms like AES-GCM, AES-CBC (with caveats), and RSA-OAEP-MGF1P for key transport. A key differentiator is its explicit handling of insecure cryptographic algorithms, defaulting to disallow them and providing warnings when they are used. Since version 2.0.0, it has transitioned to using native Node.js crypto functions, reducing external dependencies like `node-forge`. It focuses specifically on the XML Encryption standard, offering a robust solution for securing XML data in Node.js environments.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates encrypting a simple XML string using recommended secure algorithms (AES-256-GCM and RSA-OAEP) and subsequently decrypting it. It highlights secure configuration practices and handles potential errors.

import { readFileSync } from 'node:fs';
import xmlenc from 'xml-encryption'; // Using import for modern TS/Node compatibility, despite CJS origin

const options = {
  rsa_pub: readFileSync('./your_rsa.pub', 'utf8'),
  pem: readFileSync('./your_public_cert.pem', 'utf8'),
  encryptionAlgorithm: 'http://www.w3.org/2009/xmlenc11#aes256-gcm', // Recommended secure algorithm
  keyEncryptionAlgorithm: 'http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p',
  keyEncryptionDigest: 'sha256', // Stronger digest for OAEP
  disallowEncryptionWithInsecureAlgorithm: true, // Recommended security posture
  warnInsecureAlgorithm: true
};

const contentToEncrypt = '<data>Secret information</data>';

xmlenc.encrypt(contentToEncrypt, options, function(err: Error | null, result?: string) {
  if (err) {
    console.error('Encryption failed:', err);
    return;
  }
  console.log('Encrypted XML:\n', result);

  const decryptOptions = {
    key: readFileSync('./your_private_key.key', 'utf8'),
    disallowDecryptionWithInsecureAlgorithm: true,
    warnInsecureAlgorithm: true
  };

  if (result) {
    xmlenc.decrypt(result, decryptOptions, function(err: Error | null, decryptedContent?: string) {
      if (err) {
        console.error('Decryption failed:', err);
        return;
      }
      console.log('Decrypted content:\n', decryptedContent);
    });
  }
});

// Placeholder for key files for demonstration purposes
// In a real application, these would be securely generated and managed.
// Example: create a self-signed cert for testing:
// openssl genrsa -out your_private_key.key 2048
// openssl rsa -in your_private_key.key -pubout -out your_rsa.pub
// openssl req -new -x509 -key your_private_key.key -out your_public_cert.pem -days 365 -nodes -subj "/CN=test"

view raw JSON →