Search code examples
javascriptpgpopenpgp.js

Encrypt works, but not decrypt in openpgp.js


I am trying to decrypt and encrypt strings with openpgp.js.

Encryption works fine, but I can't decrypt. I really can't get it to work.

Here is a working example of the encryption: https://jsfiddle.net/d4vL8ueh/1/

var message = "secret message";
const encryptMessage  = async() => {
  if(window.crypto.getRandomValues){
    if(message != ""){
      const publicKeyString = document.getElementById("pubkey").innerHTML;

      var options = {
        message: openpgp.message.fromText(message),
        publicKeys: (await openpgp.key.readArmored(publicKeyString)).keys
      };


openpgp.encrypt(options).then(ciphertext => {
        alert(ciphertext.data);

    })



    }
  }
  else{
    window.alert("This browser does not support basic cryptography!");
  }
}

encryptMessage();

But the decryption doesn't work at all: https://jsfiddle.net/pceswg0t/2/

const decryptMessage  = async() => {
  encrypted = document.getElementById("encrypted").innerHTML;
  if(window.crypto.getRandomValues){
    if(encrypted != ""){
      const privateKeyString =  document.getElementById("privkey").innerHTML;

      var options = {
        message: await openpgp.message.readArmored(message),
        privateKeys: (await openpgp.key.readArmored(privateKeyString)).keys,
        passphrase: "dfgjk23jkfdklfsdds232334fddf"
      };


openpgp.decrypt(options).then(plaintext => {
        decrypted = plaintext.data
        alert(decrypted);
    })



   }
  }
  else{
    window.alert("This browser does not support basic cryptography!");
  }
}
decryptMessage();

Solution

  • There are two problems:

    Firstly, a non-existent message variable is being passed into readArmored when setting options.message. This should be using the encrypted variable instead:

    message: await openpgp.message.readArmored(encrypted),
    

    Secondly, the private key is encrypted, so it needs to be decrypted before it can be used. This can be done by calling decrypt() on the key before it is used:

    var privateKeys = await openpgp.key.readArmored(privateKeyString);
    privateKeys.keys[0].decrypt("dfgjk23jkfdklfsdds232334fddf")
    
    var options = {
        message: await openpgp.message.readArmored(encrypted),
        privateKeys: privateKeys.keys
    };
    

    Here's an updated JSFiddle: https://jsfiddle.net/gfkqbsoz/