加密有效,但不能在openpgp.js中解密

时间:2018-09-28 08:44:42

标签: javascript pgp openpgp.js

我正在尝试使用openpgp.js解密和加密字符串。

加密工作正常,但我无法解密。我真的无法正常工作。

以下是加密的有效示例: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();

但是解密根本不起作用: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();

1 个答案:

答案 0 :(得分:1)

有两个问题:

首先,在设置message时将不存在的readArmored变量传递到options.message中。应该使用encrypted变量代替

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

第二,私钥是加密的,因此需要对其进行解密才能使用。这可以通过在使用之前在键上调用decrypt()来完成:

var privateKeys = await openpgp.key.readArmored(privateKeyString);
privateKeys.keys[0].decrypt("dfgjk23jkfdklfsdds232334fddf")

var options = {
    message: await openpgp.message.readArmored(encrypted),
    privateKeys: privateKeys.keys
};

这是更新的JSFiddle:https://jsfiddle.net/gfkqbsoz/