54 lines
1.8 KiB
JavaScript
54 lines
1.8 KiB
JavaScript
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);
|
|
}
|
|
};
|