From 0bf6a65d715e44cf2728738e2d74339033a702e7 Mon Sep 17 00:00:00 2001 From: alex Date: Fri, 3 Feb 2023 23:35:10 +0100 Subject: [PATCH] added test for rsa --- rsa/rsa-test.js | 59 +++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 59 insertions(+) create mode 100644 rsa/rsa-test.js diff --git a/rsa/rsa-test.js b/rsa/rsa-test.js new file mode 100644 index 0000000..a6b4330 --- /dev/null +++ b/rsa/rsa-test.js @@ -0,0 +1,59 @@ +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") \ No newline at end of file