How do I troubleshoot decrypting this OpenPGP.js message?

304 Views Asked by At

I have a string message called customerPublicKey which I encrypted with OpenPGP.js:

    const { customerPublicKey} = await openpgp.generateKey({
      type: 'rsa',
      passphrase: contract.passphrase,
      userIDs: [{ name: 'My Name', email: '[email protected]' }]
    });

    const message = await openpgp.createMessage({text: 'stringKey'});
    const encrypted = await openpgp.encrypt({
        message, // input as Message object
        encryptionKeys: customerPublicKey
    });

I'm trying to decrypt it with OpenPGP.js, like this:

    const buyerEncryptedKey = await openpgp.readMessage({
      armoredMessage: encrypted 
    })
    const { privateKey  } = await openpgp.generateKey({
      type: 'rsa',
      passphrase: passphrase.value,
      userIDs: [{ name: 'My Name', email: '[email protected]' }]
    });

    const decryptionKeys = await openpgp.decryptKey({
        privateKey: await openpgp.readPrivateKey({armoredKey:privateKey}),
        passphrase: passphrase.value 
    })

This is throwing the following error:

error: Error: Error decrypting message: Session key decryption failed.

What do I need to do to debug this? Does anyone have insight here?

1

There are 1 best solutions below

6
dave_thompson_085 On

That error is because your code is wrong. Your privateKey -- returned from openpgp.generateKey -- is the externalized (encrypted, serialized and armored) form of the key, but openpgp.decrypt wants the internal (JS-object) form; to get that you need to read back and decrypt the external form like this:

    const { data } = await openpgp.decrypt({
      message: buyerEncryptedKey,
      //decryptionKeys: privateKey
      decryptionKeys: await openpgp.decryptKey({privateKey: await openpgp.readPrivateKey({armoredKey:privateKey}),passphrase: whatevervalue })
    });

However, that gives a different error:

Error: Error decrypting message: Session key decryption failed.
    at Eh.decryptSessionKeys (/node_modules/openpgp/dist/node/openpgp.min.js:2:338991)
    at async Eh.decrypt (/node_modules/openpgp/dist/node/openpgp.min.js:2:336097)
    at async Object.exports.decrypt (/node_modules/openpgp/dist/node/openpgp.min.js:16:132527)
    at async [stdin]:30:22

because your design is wrong. You can only decrypt a publickey-encrypted message using the privatekey that MATCHES the publickey -- i.e. the other half of the same keypair, created by the same key-generation operation. Generating a new keypair as you do here creates a keypair that is different from all keypairs in existence anywhere in the world, and that includes the keypair whose publickey you (or someone) used to encrypt your message. Since the generated key is different from the correct key, it cannot decrypt the message.