Skip to content

Instantly share code, notes, and snippets.

@victorighalo
Created May 3, 2024 08:47
Show Gist options
  • Save victorighalo/dac294dea367bb39a154f11d96285007 to your computer and use it in GitHub Desktop.
Save victorighalo/dac294dea367bb39a154f11d96285007 to your computer and use it in GitHub Desktop.
OpenPGP Encryption and Decryption
const openpgp = require('openpgp');
const pk = `-----BEGIN PGP PUBLIC KEY BLOCK-----
-----END PGP PUBLIC KEY BLOCK-----`;
const sk = `-----BEGIN PGP PRIVATE KEY BLOCK-----
-----END PGP PRIVATE KEY BLOCK-----`
const data = `xml payload`
const chunkArray = (arr, size) => {
const result = [];
for (let i = 0; i < arr.length; i += size) {
result.push(arr.slice(i, i + size));
}
return result;
}
const encryptData = async (data) => {
const publicKey = await openpgp.readKey({ armoredKey: pk });
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: data }),
encryptionKeys: publicKey,
});
return encrypted;
}
const decryptData = async (encryptedData) => {
const privateKey = await openpgp.readKey({ armoredKey: sk });
const publicKey = await openpgp.readKey({ armoredKey: pk });
const message = await openpgp.readMessage({
armoredMessage: encryptedData
});
const { data: decrypted, signatures } = await openpgp.decrypt({
message,
verificationKeys: publicKey, // optional
decryptionKeys: privateKey
});
return decrypted;
}
const encrypt = async ()=>{
const chunkSize = 1024;
const chunks = chunkArray(data, chunkSize);
let sBuilder = "";
for (const chunk of chunks) {
const result = await encryptData(chunk);
const base64Data = Buffer.from(result).toString('hex');
sBuilder += base64Data + ";";
}
return sBuilder;
}
const decrypt = async (encryptedString) => {
const encryptedChunks = encryptedString.split(';').filter(Boolean);
let decryptedData = '';
for (const encryptedChunk of encryptedChunks) {
const base64Data = Buffer.from(encryptedChunk, 'hex').toString();
const decryptedChunk = await decryptData(base64Data);
decryptedData += decryptedChunk;
}
return decryptedData;
}
encrypt().then(res=>{
console.log("\n===ENCRYPTED VALUE===\n")
console.log(res)
decrypt(res)
.then(res=>{
console.log("\n===DECRYPTED VALUE===\n")
console.log(res)
})
.catch(err => console.error(err));
}).catch(err => console.error(err));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment