在尝试 openpgp.js github 页面上给出的示例时,我收到“openpgp.encrypt 不是函数”错误:https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started
按照所提供的示例并使用npm install --save openpgp
安装后
然后我尝试了标记为“设置”和“使用密码加密和解密 Uint8Array 数据”的片段
// Set up
var openpgp = require('openpgp'); // use as CommonJS, AMD, ES6 module or via window.openpgp
openpgp.initWorker({ path:'openpgp.worker.js' }) // set the relative web worker path
openpgp.config.aead_protect = true // activate fast AES-GCM mode (not yet OpenPGP standard)
// Encrypt and decrypt Uint8Array data with a password
var options, encrypted;
options = {
data: new Uint8Array([0x01, 0x01, 0x01]), // input as Uint8Array (or String)
passwords: ['secret stuff'], // multiple passwords possible
armor: false // don't ASCII armor (for Uint8Array output)
};
openpgp.encrypt(options).then(function(ciphertext) {
encrypted = ciphertext.message.packets.write(); // get raw encrypted packets as Uint8Array
});
options = {
message: openpgp.message.read(encrypted), // parse encrypted bytes
password: 'secret stuff', // decrypt with password
format: 'binary' // output as Uint8Array
};
openpgp.decrypt(options).then(function(plaintext) {
return plaintext.data // Uint8Array([0x01, 0x01, 0x01])
});
这是错误:
TypeError: openpgp.encrypt is not a function
at Object.<anonymous> (/home/tgrego/1/Src/Example/Javascript/Node.js/OpenPgp/openpgpExamp.js:20:9)
at Module._compile (module.js:409:26)
at Object.Module._extensions..js (module.js:416:10)
at Module.load (module.js:343:32)
at Function.Module._load (module.js:300:12)
at Function.Module.runMain (module.js:441:10)
at startup (node.js:139:18)
at node.js:968:3
最佳答案
使用npm install --save openpgp@2.2.1
安装解决了版本问题。
此外,为了使示例正常工作,解密部分需要嵌入到加密部分的回调函数中,如下所示:
var openpgp = require('openpgp'); // use as CommonJS, AMD, ES6 module or via window.openpgp
openpgp.initWorker({ path:'openpgp.worker.js' }) // set the relative web worker path
openpgp.config.aead_protect = true // activate fast AES-GCM mode (not yet OpenPGP standard)
var options, encrypted;
options = {
data: new Uint8Array([0x01, 0x01, 0x01]), // input as Uint8Array (or String)
passwords: ['secret stuff'], // multiple passwords possible
armor: false // don't ASCII armor (for Uint8Array output)
};
openpgp.encrypt(options).then(function(ciphertext) {
encrypted = ciphertext.message.packets.write(); // get raw encrypted packets as Uint8Array
options = {
message: openpgp.message.read(encrypted), // parse encrypted bytes
password: 'secret stuff', // decrypt with password
format: 'binary' // output as Uint8Array
};
openpgp.decrypt(options).then(function(plaintext) {
console.log (plaintext.data);
return plaintext.data // Uint8Array([0x01, 0x01, 0x01])
});
});
关于javascript - openpgpjs 示例中的错误 : 'openpgp.encrypt is not a function' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36805701/