From b1198d277d5c5112d436ecd7f59bdae52ba14e70 Mon Sep 17 00:00:00 2001 From: Igor Zalutski Date: Thu, 8 Aug 2024 14:43:05 +0400 Subject: [PATCH 1/2] Fix encryption function padding --- src/utils/crypto.ts | 23 ++++++++++++++++++++++- 1 file changed, 22 insertions(+), 1 deletion(-) diff --git a/src/utils/crypto.ts b/src/utils/crypto.ts index 8dd36545..f6deea3d 100644 --- a/src/utils/crypto.ts +++ b/src/utils/crypto.ts @@ -1,6 +1,7 @@ import crypto from 'crypto'; -export function encryptWithPublicKey(text: string, publicKey: string) { +//TODO remove old encryption +export function encryptWithPublicKeyOld(text: string, publicKey: string) { const buffer = Buffer.from(text, 'utf8'); const encrypted = crypto.publicEncrypt( { @@ -13,6 +14,26 @@ export function encryptWithPublicKey(text: string, publicKey: string) { return encrypted.toString('base64'); } +export function encryptWithPublicKey( + data: string, + publicKeyPEM: string, +): string { + // Ensure the public key has the correct PEM format + const formattedPublicKey = publicKeyPEM.includes('-----BEGIN PUBLIC KEY-----') + ? publicKeyPEM + : `-----BEGIN PUBLIC KEY-----\n${publicKeyPEM}\n-----END PUBLIC KEY-----`; + + const buffer = Buffer.from(data, 'utf8'); + const encrypted = crypto.publicEncrypt( + { + key: formattedPublicKey, + padding: crypto.constants.RSA_PKCS1_PADDING, + }, + buffer, + ); + return encrypted.toString('base64'); +} + export function decryptWithPrivateKey( encryptedText: string, privateKey: string, From 10d273a2902a3cbe1a56fa9309afbf1020087c18 Mon Sep 17 00:00:00 2001 From: Igor Zalutski Date: Thu, 8 Aug 2024 14:47:56 +0400 Subject: [PATCH 2/2] Remove old encryption function --- src/utils/crypto.ts | 14 -------------- 1 file changed, 14 deletions(-) diff --git a/src/utils/crypto.ts b/src/utils/crypto.ts index f6deea3d..658e274c 100644 --- a/src/utils/crypto.ts +++ b/src/utils/crypto.ts @@ -1,19 +1,5 @@ import crypto from 'crypto'; -//TODO remove old encryption -export function encryptWithPublicKeyOld(text: string, publicKey: string) { - const buffer = Buffer.from(text, 'utf8'); - const encrypted = crypto.publicEncrypt( - { - key: publicKey, - padding: crypto.constants.RSA_PKCS1_OAEP_PADDING, - oaepHash: 'sha256', - }, - buffer, - ); - return encrypted.toString('base64'); -} - export function encryptWithPublicKey( data: string, publicKeyPEM: string,