Issue encountered with the openpgpjs example: `'The function openpgp.encrypt is not defined'`

I encountered an issue with the 'openpgp.encrypt is not a function' error while attempting to follow the sample provided on the openpgp.js github page: https://github.com/openpgpjs/openpgpjs/blob/master/README.md#getting-started

After following the example and installing it using npm install --save openpgp

I proceeded to test the code snippets labeled 'setup' and 'Encrypt and decrypt Uint8Array data with a password'

//Set up

var openpgp = require('openpgp'); // use as CommonJS, AMD, ES6 module or through window.openpgp

openpgp.initWorker({ path:'openpgp.worker.js' }) // specify the relative web worker path

openpgp.config.aead_protect = true // enable 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: ['confidential info'],              // multiple passwords allowed
    armor: false                              // avoid ASCII armor (for Uint8Array output)
};

openpgp.encrypt(options).then(function(ciphertext) {
    encrypted = ciphertext.message.packets.write(); // retrieve raw encrypted packets as Uint8Array
});

options = {
    message: openpgp.message.read(encrypted), // interpret encrypted bytes
    password: 'confidential info',                 // decrypt using password
    format: 'binary'                          // output as Uint8Array
};

openpgp.decrypt(options).then(function(plaintext) {
    return plaintext.data // Uint8Array([0x01, 0x01, 0x01])
});

This is the error message that appeared:

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

Answer №1

By running the command

npm install --save <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="4b243b2e2528303f07032d30033e">[email protected]</a>
, the version problem was successfully resolved.

For the example to function properly, it is essential to nest the decryption segment within the callback function of the encryption segment like below:

let openpgp = require('openpgp'); // import using CommonJS, AMD, ES6 module, or window.openpgp

openpgp.initWorker({ path:'openpgp.worker.js' }); // define the relative web worker path

openpgp.config.aead_protect = true; // enable quick AES-GCM mode (not currently part of OpenPGP standard)

let options, encrypted;

options = {
    data: new Uint8Array([0x01, 0x01, 0x01]), // input as Uint8Array (or String)
    passwords: ['confidential information'], // can use multiple passwords
    armor: false // do not ASCII armor (for Uint8Array output)
};

openpgp.encrypt(options).then(function(ciphertext) {
    encrypted = ciphertext.message.packets.write(); // retrieve raw encrypted packets as Uint8Array

    options = {
        message: openpgp.message.read(encrypted), // parse the encrypted bytes
        password: 'confidential information', // decrypt using the password
        format: 'binary' // output as Uint8Array
    };

    openpgp.decrypt(options).then(function(plaintext) {
        console.log(plaintext.data);
        return plaintext.data; // Uint8Array([0x01, 0x01, 0x01])
    });

});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

The node application route appears to be malfunctioning

Recently delving into the world of node JS, I encountered an issue while working on my application with the following 3 files. http.createServer(app).listen(**app.get('port')**, function(){ The error message reads 'undefined is not a func ...

Struggling to get my JavaScript function for calculating one rep max to work, need some help figuring out the issue

I have been working on a one rep max calculator using the Epley Formula. However, when I try to call the function, it returns as undefined. I have utilized the parameters weight and reps, both of which are parsed as integers, believing that they would be e ...

Utilizing the this.setState function within a callback

In my current project, I've encountered an issue with setting the state in a Twitter timeline react component. The code snippet causing trouble is as follows: componentWillMount: function() { twitter.get('statuses/user_timeline', ...

"Enhance your website with Ajax code that enables automatic refreshing of a PHP file, keeping its values up-to-date

Before diving in, I want to make it clear that my understanding of ajax is limited. I'm currently working on a small application where I have a load.php file that echoes 3 variables: $loadout[0]; $loadout[1]; $loadout[2]; The PHP file is functioning p ...

An error occurred when attempting to hide or show a jQuery loading animation

Here is the HTML code I am using: <div id="success_message" style="display:none"> <p>Good job!</p> </div> <div id="my-form"> <form> <input>....... (lots of inputs) <input id="my-btn" ...

Mastering the art of nested await functions in JavaScript

In my current Nodejs application using mongoose, I am implementing cache with MongoDB in-memory and MongoDB database. This setup is running on Nodejs 8.9 with async/await support enabled. let get_func = async(userId) => { let is_cached = await c ...

The Azure DevOps pipeline is indicating that the global CLI version is higher than the local version you have on

I'm currently facing an issue while trying to deploy an Angular front end to Azure pipeline from GitHub using yaml. The problem occurs during the npm build and install stage, with an error message stating 'Your global Angular CLI version (15.2.6) ...

Having issues with creating a poll command for my Discord bot as it keeps throwing the error message: "Oops! TypeError: Cannot read property 'push' of undefined."

Can anyone assist me with my question? I am using discord v11.5.1 Below is the code: exports.run = async (bot, message) => { const options = [" ...

What is the best way to implement a nested lookup in MongoDB within a field?

Within my database, I have a collection named Randomhospital. Inside this collection, there is a field named hospital structured as follows: { "id": "GuDMUPb9gq", "Hospital Name": "UPHI", "Hospital City&qu ...

Function being called by Intersection Observer at an inappropriate moment

After running the page, the intersection observer behaves exactly as desired. However, upon reloading the page, I am automatically taken back to the top of the page (which is expected). Strangely though, when the viewport interacts with the target elemen ...

Enhancing User Experience: Creating a Vue Button Component for Adding Items to Cart with the Power of Axios and Laravel Backend Integration

I have recently developed a Vue3 shopping cart with an "Add One" button feature. When the user clicks this button, it updates an input field of type "number" and sends a request to update the database using Axios along with Laravel's createOrUpdate me ...

"Exploring the world of Vue.js and videojs: refreshing the video

Is there a way to refresh the videojs in Vue (3)? Here is the code snippet I am currently using: <template> <video-js controls="true" preload="auto" ref="video_player" class="video-js vjs-big-play-centered&quo ...

Exploring the controller logic in Sails.js index.ejs

I'm struggling to understand how to integrate dynamic logic into the homepage of my Sails.js application. Currently, the homepage is static, but I want to display data on the index.ejs page. I have a MainController with an index function that retrieve ...

Stop the time-dependent function from executing within a specific condition

Here is the code snippet I am currently working with: var w = $(window); var $navbar = $('.navbar'); var didScroll = false; w.on('scroll', function(){ didScroll = true; }); function AddScrollHeader(pxFromTop) { setInterval(fun ...

Command to conceal components for users visiting as guests

I'm looking to develop a directive that hides specific elements for guest users. Here is the current code I have: angular.module('someMod') .directive('premiumUser', premiumUser) .controller('PremiumUserCtrl', Pr ...

The command 'webpack' is not identified as an internal or external command

I'm having trouble executing npm run build as it's showing me the following error: 'webpack' is not recognized as an internal or external command, Even after deleting the node_modules folder and running: npm install, the issue still p ...

A particular character is displayed exclusively in a text box using either jQuery or JavaScript

Text Box <input id="txtbo" type="text" value="CAN'T TOUCH THIS!" size="50" /> Solution Using jQuery or Javascript: var readOnlyLength = $('#txtbo').val().length; $('#txtbo').on('keypress, keydown', function(even ...

The npm workspaces command alerts users with a warning message stating that there is a "some-package-name" in the filter set, but no corresponding

I am dealing with a repository that includes numerous npm packages and utilizes npm workspaces The primary package.json file includes the following line: "workspaces": [ "*" ] Whenever I execute commands like npm i -ws, I enco ...

Learn how to utilize the Page props in the getServerSideProps method with Next.js

I have passed some properties to the _app page. <PageWrapper> <Component someProps={someProps} /> <GlobalCSS /> </PageWrapper> Can these props be accessed in the getServerSideProps method on each individual Page? export const g ...

"Successfully implementing AJAX POST functionality, but encountering issues where callbacks are not triggering

I have gone through numerous posts addressing this issue and attempted various solutions, however, none seem to work for me. My AJAX POST function correctly adds the email to my mailing list, but the success and error callbacks are not consistently firing, ...