I have a backend service utility (based on this gist) which looks like this:
import crypto from 'crypto';
interface KeyPair {
publicKey: string;
privateKey: string;
}
export class RSAController {
static async generateKeys(): Promise<KeyPair> {
return new Promise((res, rej) => {
crypto.generateKeyPair(
'rsa',
{
modulusLength: 2048,
},
(err, publicKeyObject, privateKeyObject) => {
if (err) rej(err);
const publicKey = publicKeyObject.export({
type: 'pkcs1',
format: 'pem',
});
const privateKey = privateKeyObject.export({
type: 'pkcs1',
format: 'pem',
});
res({
publicKey: publicKey as string,
privateKey: privateKey as string,
});
},
);
});
}
static encrypt({ data, publicKey }: { data: string; publicKey: string }) {
const encryptedData = crypto.publicEncrypt(
{
key: publicKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256',
},
Buffer.from(data),
);
return encryptedData.toString('base64');
}
static decrypt({ encryptedData, privateKey }: { encryptedData: string; privateKey: string }) {
const decryptedData = crypto.privateDecrypt(
{
key: privateKey,
padding: crypto.constants.RSA_PKCS1_OAEP_PADDING,
oaepHash: 'sha256',
},
Buffer.from(encryptedData, 'base64'),
);
return decryptedData.toString();
}
}
What works is if I try to encrypt and subsequently decrypt a string on the backend:
const { privateKey, publicKey } = await RSAController.generateKeys();
const encryptedData = await RSAController.encrypt({ data: 'hello world', publicKey });
console.log('encryptedData', encryptedData);
const decryptedData = await RSAController.decrypt({ encryptedData, privateKey });
console.log('decryptedData', decryptedData); // works fine, I see "hello world"
But I’m also using the react-native-rsa-native
library, which encrypts on the frontend first, before sending out the message to the backend.
This is where my problem arises, because encrypting and subsequently decrypting works fine if I’m just using RSAController
, but if I encrypt with the client libary’s RSA.decrypt
method, and then try to decrypt this on the backend with RSAController
, I catch the error,
error:02000079:rsa routines::oaep decoding error
What am I doing wrong here?