Skip to content

Node.js Example Code ​

1. Core Security Component (sudSecurityUtil.js) ​

javascript
const crypto = require('crypto');

/**
 * SUD OpenPaaS API secure communication core utility class
 */
class SudSecurityUtil {
    /**
     * 1. Request business data encryption (AES-256-GCM)
     */
    static encryptRequest(urlPath, appId, keySn, symKeyBase64, reqData) {
        const timestamp = Math.floor(Date.now() / 1000);
        // base64url encoding inherently contains no '=' sign and complies with the URL-safe standard
        const nonce = crypto.randomBytes(16).toString('base64url');

        // Fill in the security check fields
        const payloadObj = {
            _n: nonce,
            _appid: appId,
            _timestamp: timestamp,
            ...reqData
        };
        const plaintext = JSON.stringify(payloadObj);

        // Concatenate AAD: urlpath|appid|timestamp|sn
        const aad = `${urlPath}|${appId}|${timestamp}|${keySn}`;
        const realKey = Buffer.from(symKeyBase64, 'base64');
        const iv = crypto.randomBytes(12);

        const cipher = crypto.createCipheriv('aes-256-gcm', realKey, iv);
        cipher.setAAD(Buffer.from(aad, 'utf-8'));

        const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf-8'), cipher.final()]);
        const authTag = cipher.getAuthTag();

        const httpBody = {
            iv: iv.toString('base64'),
            data: ciphertext.toString('base64'),
            authtag: authTag.toString('base64')
        };

        return {
            reqTs: timestamp,
            reqDataJSON: JSON.stringify(httpBody)
        };
    }

    /**
     * 2. Request message signing (RSA-PSS)
     */
    static signRequest(urlPath, appId, timestamp, reqDataJSON, privateKeyPem) {
        // Concatenate strictly in order
        const payload = `${urlPath}\n${appId}\n${timestamp}\n${reqDataJSON}`;

        const sign = crypto.createSign('RSA-SHA256');
        sign.update(payload, 'utf-8');
        sign.end();

        // PSS mode; the salt length must align with SHA256 (32 bytes)
        return sign.sign({
            key: privateKeyPem,
            padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
            saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
        }, 'base64');
    }

    /**
     * 3. Response message signature verification (RSA-PSS)
     */
    static verifyResponseSignature(urlPath, expectedAppId, localCertSn, platformCertPem, 
                                   respAppId, respTs, respSn, respSig, 
                                   respDeprecatedSn, respDeprecatedSig, respDataJSON) {
        // Basic security check
        if (expectedAppId !== respAppId) {
            throw new Error("Security check failed: the response AppId does not match the local one");
        }

        // Certificate serial number matching and smooth rotation support
        let signatureBase64 = '';
        if (localCertSn === respSn) {
            signatureBase64 = respSig;
        } else if (respDeprecatedSn && localCertSn === respDeprecatedSn) {
            signatureBase64 = respDeprecatedSig || respSig;
        } else {
            throw new Error(`Signature verification failed: the local certificate serial number (${localCertSn}) does not match the platform's current serial number (${respSn})`);
        }

        const payload = `${urlPath}\n${respAppId}\n${respTs}\n${respDataJSON}`;

        const verify = crypto.createVerify('RSA-SHA256');
        verify.update(payload, 'utf-8');
        verify.end();

        return verify.verify({
            key: platformCertPem,
            padding: crypto.constants.RSA_PKCS1_PSS_PADDING,
            saltLength: crypto.constants.RSA_PSS_SALTLEN_DIGEST
        }, signatureBase64, 'base64');
    }

    /**
     * 4. Response ciphertext decryption (AES-256-GCM)
     */
    static decryptResponse(urlPath, appId, respTs, keySn, symKeyBase64, respDataJSON) {
        const encBody = JSON.parse(respDataJSON);
        const iv = Buffer.from(encBody.iv, 'base64');
        const data = Buffer.from(encBody.data, 'base64');
        const authTag = Buffer.from(encBody.authtag, 'base64');

        const aad = `${urlPath}|${appId}|${respTs}|${keySn}`;
        const realKey = Buffer.from(symKeyBase64, 'base64');

        const decipher = crypto.createDecipheriv('aes-256-gcm', realKey, iv);
        decipher.setAAD(Buffer.from(aad, 'utf-8'));
        decipher.setAuthTag(authTag);

        try {
            // The final() stage automatically verifies the validity of the AuthTag
            const plaintext = Buffer.concat([decipher.update(data), decipher.final()]);
            const realResp = JSON.parse(plaintext.toString('utf-8'));

            // Strong validation of the internal security fields
            if (realResp._appid !== appId || realResp._timestamp !== respTs) {
                throw new Error("Security field validation failed: the _appid or _timestamp inside the response plaintext has been illegally tampered with");
            }

            return realResp;
        } catch (error) {
            throw new Error(`Decryption failed: AuthTag verification did not pass or plaintext parsing error - ${error.message}`);
        }
    }
}

module.exports = SudSecurityUtil;

2. Business Invocation Demo (demo.js) ​

javascript
const SudSecurityUtil = require('./sudSecurityUtil');

// Simulated global application configuration
const CONFIG = {
    appId: "cp_10010",
    urlPath: "https://api.sud.com/v1/game/login",
    symKeySn: "key_v1",
    symKey: "otUpngOjU+nVQaWJIC3D/yMLV17RKaP6t4Ot9tbnzLY=",
    privateKeyPem: "-----BEGIN PRIVATE KEY-----\nMIIEvQIB... (application private key) ...W6w=\n-----END PRIVATE KEY-----",
    platformCertSn: "sud_cert_v1",
    platformCertPem: "-----BEGIN CERTIFICATE-----\nMIID0jCC... (SUD platform public key certificate) ...Q==\n-----END CERTIFICATE-----"
};

function main() {
    try {
        console.log("=== 1. Send request: encrypt and sign business data ===");
        
        // Raw business request parameters
        const bizReq = {
            appid: CONFIG.appId,
            sud_uid: "user_889900",
            scene: 0,
            client_ip: "127.0.0.1"
        };

        // Step A: encryption
        const { reqTs, reqDataJSON } = SudSecurityUtil.encryptRequest(
            CONFIG.urlPath, CONFIG.appId, CONFIG.symKeySn, CONFIG.symKey, bizReq
        );

        // Step B: signing
        const reqSig = SudSecurityUtil.signRequest(
            CONFIG.urlPath, CONFIG.appId, reqTs, reqDataJSON, CONFIG.privateKeyPem
        );

        console.log("HTTP Header X-Sud-Timestamp:", reqTs);
        console.log("HTTP Header X-Sud-Signature:", reqSig);
        console.log("HTTP Body:", reqDataJSON);


        console.log("\n=== 2. Receive response: verify signature and decrypt ciphertext ===");

        // Simulate the data obtained from the HTTP response
        const respTs = reqTs; 
        const respHeaderAppId = CONFIG.appId;
        const respHeaderSn = CONFIG.platformCertSn;
        const respHeaderSig = reqSig; // For demonstration; in practice this is the received signature
        const respBodyJSON = `{"iv":"r2WDQt56rEAmMuoR","data":"HExs66...","authtag":"z2BF..."}`;

        // Step C: signature verification
        const isSigValid = SudSecurityUtil.verifyResponseSignature(
            CONFIG.urlPath, CONFIG.appId, CONFIG.platformCertSn, CONFIG.platformCertPem,
            respHeaderAppId, respTs, respHeaderSn, respHeaderSig, null, null, respBodyJSON
        );

        if (isSigValid) {
            console.log("Response signature verification succeeded!");
            
            // Step D: decryption
            const decryptedBizData = SudSecurityUtil.decryptResponse(
                CONFIG.urlPath, CONFIG.appId, respTs, CONFIG.symKeySn, CONFIG.symKey, respBodyJSON
            );
            console.log("Response decryption succeeded, business data:", decryptedBizData);
        }

    } catch (error) {
        console.error("Flow interrupted:", error.message);
    }
}

main();