JavaScript: Decrypt content of GnuPG encrypted files using openpgp.js

好久不见. 提交于 2019-12-04 08:56:10

OpenPGP knows to encodings of messages,

  • binary messages, which are more space-efficient and
  • ASCII-armored messages encoded in a format similar to base64, providing higher reliability when transmitted through different channels as being plain text.

openpgp.message.readArmored (message) only understands ASCII-armored information. use openpgp.message.fromBinary (message) instead. As an alternative, encode the message through GnuPG using the --armor option while encrypting, or gpg --enarmor an already encrypted binary message.

With Openpgpjs version 3.x, I found that a private key object has to be created and used with the publicKey and message in the options variable. The private key object is created with the private key. First create the private key object, then decrypt it with your "secret" phrase, and then decrypt the message.

Here's an example using your variables.

 privKeyObj.decrypt(secret).then(function(oBoolean) {
      //Name oBoolean anything you want.
      //It will be true or false indicating
      //whether the secret phrase is right.
      if(!oBoolean) {
           output.innerHTML = "Incorrect password.";
           output.style.color = "red";
      } 
      else {
           var privateKey = "your openpgpjs private key created with your secret phrase";
           var privKeyObj = openpgp.key.readArmored(privateKey).keys[0];
           var options = {
                message: openpgp.message.readArmored(message),
                publicKeys: openpgp.key.readArmored(publickey).keys,
                privateKeys: [privKeyObj]
           };
           openpgp.decrypt(options).then(function(plaintext) {
                output.innerHTML = plaintext.data;
           }, function(error) {
                output.innerHTML = "Error while decrypting";
                output.style.color = "red";
           });
      }
 });
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!