|
const openpgp = require('openpgp'); |
|
const co = require('co'); |
|
const { |
|
randomBytes, |
|
} = require('crypto'); |
|
const originalMessage = require('../../__mock__/originalMessage'); |
|
|
|
|
|
/** |
|
* --------------------- |
|
* Note: |
|
* PGP is POST signage verification, not Pre Decryption |
|
* This could be an issue for DDOS attacks. |
|
* --------------------- |
|
*/ |
|
|
|
(async () => { |
|
// 32 Bytes = 256 bits |
|
const SenderPassphrase = randomBytes(32).toString('hex'); |
|
const ReceiverPassphrase = randomBytes(32).toString('hex'); |
|
|
|
// this is how to make a RSA key ( OpenPGP has many types of keys ) |
|
const SenderKey = await openpgp.generateKey({ |
|
userIds: [{ name: 'Jon Smith', email: '[email protected]' }], // you can pass multiple user IDs |
|
rsaBits: 4096, |
|
passphrase: SenderPassphrase, |
|
}); |
|
const ReceiverKey = await openpgp.generateKey({ |
|
userIds: [{ name: 'Jon Smith', email: '[email protected]' }], // you can pass multiple user IDs |
|
rsaBits: 4096, |
|
passphrase: ReceiverPassphrase, |
|
}); |
|
|
|
// Simple encryption and decryption, with signing and integrated verification |
|
co(function* () { |
|
const encrypted = yield co(function* () { |
|
const { keys: [privateKey] } = yield openpgp.key.readArmored(SenderKey.privateKeyArmored); |
|
yield privateKey.decrypt(SenderPassphrase); |
|
const { keys } = yield openpgp.key.readArmored(ReceiverKey.publicKeyArmored); |
|
const { data: encryptedResults } = yield openpgp.encrypt({ |
|
message: openpgp.message.fromText(JSON.stringify(originalMessage)), |
|
publicKeys: keys, |
|
privateKeys: [privateKey], |
|
}); |
|
return encryptedResults; |
|
}); |
|
console.log(encrypted); |
|
|
|
/** |
|
* --------------------- |
|
* Note: |
|
* when Private keys are provided during encryption, the content is signed. |
|
* --------------------- |
|
*/ |
|
|
|
const decrypted = yield co(function* () { |
|
const { keys: [privateKey] } = yield openpgp.key.readArmored(ReceiverKey.privateKeyArmored); |
|
yield privateKey.decrypt(ReceiverPassphrase); |
|
const message = yield openpgp.message.readArmored(encrypted); // parse armored message |
|
const { keys: publicKeys } = yield openpgp.key.readArmored(SenderKey.publicKeyArmored); |
|
const decryptedResults = yield openpgp.decrypt({ |
|
message, |
|
publicKeys, // for signature validation |
|
privateKeys: [privateKey], // for decryption |
|
streaming: false, // when false, valid becomes present on all the signatures |
|
}); |
|
if (decryptedResults.signatures.length === 0) { |
|
throw new Error('Missing Signature'); |
|
} |
|
if ((decryptedResults.signatures || []).some(({ valid }) => valid === false)) { |
|
throw new Error('Invalid Signature'); |
|
} |
|
return JSON.parse(decryptedResults.data); |
|
}); |
|
|
|
|
|
console.log(JSON.stringify(decrypted, null, 4)); |
|
}); |
|
})(); |
|
|