other
This commit is contained in:
54
backend/utils/encryptPgp.js
Normal file
54
backend/utils/encryptPgp.js
Normal file
@@ -0,0 +1,54 @@
|
||||
import * as openpgp from 'openpgp';
|
||||
import logger from './logger.js';
|
||||
|
||||
/**
|
||||
* Encrypts a message using PGP
|
||||
* @param {string} message - The message to encrypt
|
||||
* @param {string} publicKey - PGP public key for encryption
|
||||
* @returns {Promise<string>} - The encrypted message
|
||||
*/
|
||||
export const encryptWithPGP = async (message, publicKey) => {
|
||||
try {
|
||||
// Parse the public key
|
||||
const decodedPublicKey = await openpgp.readKey({ armoredKey: publicKey });
|
||||
|
||||
// Encrypt the message
|
||||
const encrypted = await openpgp.encrypt({
|
||||
message: await openpgp.createMessage({ text: message }),
|
||||
encryptionKeys: decodedPublicKey
|
||||
});
|
||||
|
||||
return encrypted;
|
||||
} catch (error) {
|
||||
logger.error('Error during PGP encryption', { error: error.message });
|
||||
throw new Error('Failed to encrypt message: ' + error.message);
|
||||
}
|
||||
};
|
||||
|
||||
/**
|
||||
* Decrypts a message using PGP
|
||||
* @param {string} encryptedMessage - The encrypted message
|
||||
* @param {string} privateKey - PGP private key for decryption
|
||||
* @param {string} passphrase - Passphrase for the private key
|
||||
* @returns {Promise<string>} - The decrypted message
|
||||
*/
|
||||
export const decryptWithPGP = async (encryptedMessage, privateKey, passphrase) => {
|
||||
try {
|
||||
// Parse the private key
|
||||
const decodedPrivateKey = await openpgp.readPrivateKey({
|
||||
armoredKey: privateKey
|
||||
});
|
||||
|
||||
// Decrypt the message
|
||||
const decrypted = await openpgp.decrypt({
|
||||
message: await openpgp.readMessage({ armoredMessage: encryptedMessage }),
|
||||
decryptionKeys: decodedPrivateKey,
|
||||
config: { allowInsecureDecryptionWithSignature: true }
|
||||
});
|
||||
|
||||
return decrypted.data;
|
||||
} catch (error) {
|
||||
logger.error('Error during PGP decryption', { error: error.message });
|
||||
throw new Error('Failed to decrypt message: ' + error.message);
|
||||
}
|
||||
};
|
||||
Reference in New Issue
Block a user