import { constants, createPublicKey, publicEncrypt } from 'node:crypto' /** * RSA-OAEP encrypt with platform public key. * * Algorithm: RSA/ECB/OAEPWithSHA-256AndMGF1Padding * - OAEP hash: SHA-256 * - MGF1 hash: SHA-256 * * @param plaintext - UTF-8 string to encrypt * @param publicKeyBase64 - Platform public key (X.509 DER, Base64 encoded) * @returns Base64-encoded ciphertext */ export const rsaOaepEncrypt = (plaintext: string, publicKeyBase64: string): string => { // Load public key from Base64-encoded DER (X.509 / SubjectPublicKeyInfo) const publicKeyDer = Buffer.from(publicKeyBase64, 'base64') const publicKey = createPublicKey({ key: publicKeyDer, format: 'der', type: 'spki', }) // Encrypt with RSA-OAEP (SHA-256 for both OAEP hash and MGF1) const encrypted = publicEncrypt( { key: publicKey, padding: constants.RSA_PKCS1_OAEP_PADDING, oaepHash: 'sha256', }, Buffer.from(plaintext, 'utf-8'), ) return encrypted.toString('base64') }