So, as the title says, I’m trying to implement a service on the client with SvelteKit that encrypts the user data sent to the server made with Express.
I’m trying to do achieve this with the RSA encryption that I found in several forums.
The thing is, on the backend, it works perfectly fine:
Encryption:
import { constants, publicEncrypt } from 'node:crypto';
import { readFileSync } from 'node:fs';
export const encryptData = (data: string) => {
const publicKey = readFileSync('public.pem');
const encryptedData = publicEncrypt(
{
key: publicKey,
padding: constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256',
},
Buffer.from(data),
);
return encryptedData.toString('base64');
};
Decryption:
import { constants, privateDecrypt } from 'node:crypto';
import { readFileSync } from 'node:fs';
export const decryptData = (data: string) => {
const privateKey = readFileSync('private.pem');
const decryptedData = privateDecrypt(
{
key: privateKey,
padding: constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256',
},
Buffer.from(data, 'base64'),
);
return decryptedData.toString();
};
But in the frontend I can’t find a way to get the server receiving the data and parsing it to a JSON. This is the last code I tried to implement:
Encryption:
import axios from 'axios';
async function retrieveRsaKey() {
const BACKEND = import.meta.env.VITE_SERVER_URL;
const PUBLIC_RSA_KEY = await axios.get(BACKEND + '/public_rsa').then((res) => res.data);
return PUBLIC_RSA_KEY;
}
export async function encryptData (data: {[key:string]: unknown}) {
const parsedData = JSON.stringify(data)
const crypto = new Crypto;
crypto.subtle.encrypt({name: "RSA-OAEP"}, await retrieveRsaKey(), parsedData)
}
Do you know can I achieve this? I’ve been searching for this topic for about two days and couldn’t find anything working with JS or TS only. Some even rely on PHP or Python to make the encryption.
What I have tried?
- Use the “web crypto api”
- Search for packages that imitate the functions in “node:crypto”
What am I expeting?
- A service that receives a JSON with the information of an user that creates an encrypted message for the server with the PUBLIC RSA KEY.