Skip to content

Node.js Example Code ​

Covers the core scenarios of the two types of "data security" keys:

  • Data symmetric encryption key (AES-256-GCM): userSignature generation, sessionKey decryption
  • Data signature public/private key (RSASSA-PSS): business data signature verification (e.g., gameSignature)

General Notes ​

  • The AES part of the example is split into two layers:
    • AES-256-GCM utility module (aes256gcmUtil): a general-purpose symmetric encryption/decryption implementation, consistent with the internal encryption/decryption mechanism of the SUD SDK, and directly reusable in any AES-256-GCM scenario;
    • Business wrapper: builds on the utility module to perform Payload construction and field validation, covering userSignature generation and sessionKey decryption respectively.
  • The AES byte layout is uniformly: iv(12) || ciphertext || tag(16), then Base64-encoded as a whole.
  • The RSA part (§3 Business data signature verification) provides an independent rsaUtil utility module, whose PSS parameters are fully consistent with the SUD OpenPaaS server-side signing mechanism.
  • The example contains only the core logic; production environments need to add logging, exception fallbacks, monitoring alerts, and other engineering measures.

Environment Dependencies ​

  • Node.js 12+ (no additional dependencies required; based on the built-in crypto module).

General AES-256-GCM Utility ​

javascript
// aes256gcmUtil.js
const crypto = require('crypto');

const ALGORITHM = 'aes-256-gcm';
const IV_LENGTH = 12;
const TAG_LENGTH = 16;

function encrypt(plaintext, keyBase64) {
    const key = Buffer.from(keyBase64, 'base64');
    const iv = generateIV();
    const cipher = crypto.createCipheriv(ALGORITHM, key, iv);
    const cipherBytes = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()]);
    const tag = cipher.getAuthTag();
    // Consistent with Java/JCE: iv || ciphertext || tag
    return Buffer.concat([iv, cipherBytes, tag]).toString('base64');
}

function decrypt(encryptedBase64, keyBase64) {
    const key = Buffer.from(keyBase64, 'base64');
    const data = Buffer.from(encryptedBase64, 'base64');
    const iv = data.subarray(0, IV_LENGTH);
    const tag = data.subarray(data.length - TAG_LENGTH);
    const cipherBytes = data.subarray(IV_LENGTH, data.length - TAG_LENGTH);
    const decipher = crypto.createDecipheriv(ALGORITHM, key, iv);
    decipher.setAuthTag(tag);
    return Buffer.concat([decipher.update(cipherBytes), decipher.final()]);
}

function generateIV() {
    return crypto.randomBytes(IV_LENGTH);
}

module.exports = { encrypt, decrypt };

1. userSignature Generation ​

Build the authentication Payload based on aes256gcmUtil and encrypt it:

javascript
// userSignature.js
const aes256gcm = require('./aes256gcmUtil');

const SIGNATURE_VERSION = '1';

function generateUserSignature(userId, expiresAt, base64Key) {
    if (!userId || typeof userId !== 'string') {
        throw new Error('user_id must not be empty');
    }
    if (!Number.isInteger(expiresAt) || expiresAt <= Math.floor(Date.now() / 1000)) {
        throw new Error('expires_at must be an integer Unix timestamp (seconds) greater than the current time');
    }

    const payload = JSON.stringify({
        version: SIGNATURE_VERSION,
        user_id: userId,
        expires_at: expiresAt,
    });

    return aes256gcm.encrypt(payload, base64Key);
}

// Invocation example
const base64Key = 'Your Base64-encoded 32-byte AES key';
const userId = 'user_123456';
const expiresAt = Math.floor(Date.now() / 1000) + 24 * 3600; // expires in 24 hours
console.log('userSignature:', generateUserSignature(userId, expiresAt, base64Key));

2. sessionKey Decryption ​

Decrypt based on aes256gcmUtil and validate the payload fields:

javascript
// sessionKey.js
const aes256gcm = require('./aes256gcmUtil');

function decryptSessionKey(encryptedSessionKey, base64Key, expectedUserId) {
    const plaintextBytes = aes256gcm.decrypt(encryptedSessionKey, base64Key);
    const payload = plaintextBytes.toString('utf8');

    let parsed;
    try {
        parsed = JSON.parse(payload);
    } catch (e) {
        throw new Error('The decrypted payload is not valid JSON: ' + e.message);
    }

    const { user_id: userId, session_key: sessionKey } = parsed;
    if (!userId || !sessionKey) {
        throw new Error('payload missing required fields user_id / session_key');
    }
    if (expectedUserId && userId !== expectedUserId) {
        throw new Error(`user_id mismatch: expected ${expectedUserId}, actual ${userId}`);
    }

    return { userId, sessionKey };
}

// Invocation example
const encryptedSessionKey = 'Base64-encoded encrypted_session_key';
const base64Key = 'Your Base64-encoded 32-byte AES key';
const expectedUserId = 'user_123456';
const { userId, sessionKey } = decryptSessionKey(encryptedSessionKey, base64Key, expectedUserId);
console.log('user_id:', userId, 'session_key:', sessionKey);

3. Business Data Signature Verification ​

Based on the "data signature public/private key", perform RSASSA-PSS signature verification on the business data payload delivered by SUD OpenPaaS (such as gameSignature). The PSS parameters are SHA-256 / MGF1-SHA-256 / salt=32 / trailer=1 (the Node.js crypto module defaults to trailer=1), and the signature value is Base64-encoded.

3.1 General RSA Signing/Verification Utility ​

javascript
// rsaUtil.js
const crypto = require('crypto');

const HASH_ALGORITHM = 'sha256';
const SALT_LENGTH = 32;

function sign(content, privateKeyPem) {
    const signature = crypto.sign(HASH_ALGORITHM, Buffer.from(content, 'utf8'), {
        key: privateKeyPem,
        padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
        saltLength: SALT_LENGTH,
        // The mgf1 digest defaults to the same as the signature digest (SHA-256)
    });
    return signature.toString('base64');
}

function verify(content, signValueBase64, publicKeyPem) {
    return crypto.verify(
        HASH_ALGORITHM,
        Buffer.from(content, 'utf8'),
        {
            key: publicKeyPem,
            padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
            saltLength: SALT_LENGTH,
        },
        Buffer.from(signValueBase64, 'base64')
    );
}

module.exports = { sign, verify };

3.2 Invocation Example ​

javascript
// verifyData.js
const rsaUtil = require('./rsaUtil');

// publicKeyPem: the application public key obtained from the SUD OpenPaaS admin console (PEM string)
// content:      the "content to be verified" concatenated per the corresponding business documentation (e.g., gameSignature)
// signature:    the signature value carried in the business data payload (Base64)
const publicKeyPem = `-----BEGIN PUBLIC KEY-----
...
-----END PUBLIC KEY-----`;
const content = 'content to be verified';
const signature = 'the Base64 signature value carried in the business data';

if (!rsaUtil.verify(content, signature, publicKeyPem)) {
    throw new Error('Data signature verification failed; do not trust this business data content');
}
console.log('Data signature verification passed');