const crypto = require('crypto') // https://stackoverflow.com/questions/11449577/why-is-base64-encode-adding-a-slash-in-the-result // plus and slash must be replaced with another character to ensure URL correctness. Will be replaced again on the api server to the old characters function base64url_encode(s) { return s.replaceAll("+", "-").replaceAll("/", "_") } function encryptMessage(checkMessage) { const { publicKey, privateKey } = crypto.generateKeyPairSync('rsa', { modulusLength: 2048, publicKeyEncoding: {type: 'pkcs1',format: 'pem'}, privateKeyEncoding: {type: 'pkcs1', format: 'pem'} }); console.log(publicKey) const b64PublicKey = Buffer.from(publicKey).toString('base64') console.log("-------------------------") console.log("PUBLIC KEY:", b64PublicKey) console.log("-------------------------") // encrypt message const encryptedCheckMessage = crypto.privateEncrypt(privateKey, checkMessage) const encryptedBase64CheckMessage = encryptedCheckMessage.toString('base64') const b64CheckMessage = base64url_encode(encryptedBase64CheckMessage) console.log("ENCRYPTED B64 CHECK MESSAGE:", b64CheckMessage) console.log("-------------------------") // testing decryption const decrB64 = Buffer.from(encryptedBase64CheckMessage, 'base64') const decr = crypto.publicDecrypt(publicKey, decrB64) console.log("DECRYPTED MESSAGE:", decr.toString()) // sending request fetch("http://localhost:8080/v1/user/pkeys", { method: "PATCH", headers: { "Content-Type": "application/json", "X-Authorization": "mw7RtGyI-1CZ3-ukNC-YTFp-UCZLvzw5gUQb" }, body: JSON.stringify( { "PKey": b64PublicKey, "CM": b64CheckMessage } ) }) .then((res) => res.json()) .then((data) => console.log(data)) } encryptMessage("test")