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

Error: The function setOpenModal is not defined

I'm currently working on creating a login modal popup that will appear when a button inside a navbar is clicked. However, I'm encountering the following error: TypeError: setOpenModal is not a function Despite going through various discussions ...

Transforming a collection of items into a JSON format string

UPDATE: There was a mistake in the programming, please refrain from submitting answers. This question will be removed. If you have already submitted an answer, kindly delete it. I am attempting to submit a form using jQuery and ajax. One of the fields con ...

The pagination feature in React MUI DataGrid is malfunctioning

I am currently working with a datagrid and implementing server-side pagination. I have set a limit of 5 objects to be returned from the backend, and an offset variable to indicate from which index the next set of data should come. const handlePageChange = ...

React Button Axios: A Primer for Complete Beginners

For the past few weeks, I've been using create-react-app and trying to modify the App.js file to include a button that executes an axios HTTP request when clicked. However, during my attempts, I keep running into errors like "unexpected token" in hand ...

Converting a PHP variable to JSON in an AJAX call

At the moment, my approach involves using a jQuery Ajax asynchronous function to repeatedly request a PHP page until a large number of spreadsheet rows are processed. I am uncertain if the way I set the variables to be passed to the requested page is corre ...

Perform the function with the value of the currently selected option

Despite selecting an option, a message still appears stating "Please choose something." This function works with only one dropdown list, but encounters issues when there are two or more. (In this example, the variable 'sport' is document.getElem ...

Having trouble with the npm build command - getting an error message saying "npm-build.html not found"

I'm encountering an issue where "npm build" is not working because it's searching for a file that no longer exists. PS C:\Users\simon\Desktop\3-Projects\1-Coding\simon\simon> npm build npm ERR! code 1 npm ERR ...

What is the best way to split an array into smaller chunks?

My JavaScript program fetches this array via ajax every second, but the response time for each request is around 3 to 4 seconds. To address this delay, I attempted to split the array into chunks, however, encountered difficulties in completing the task: { ...

Having trouble with the clip-path in d3.js liquid fill gauge

Attempting to integrate the d3.js liquid fill gauge into my angular2 webapp has been a challenge. The clippath functionality seems to be malfunctioning, resulting in no wave being generated at all. https://i.stack.imgur.com/3Bmga.png instead of https://i. ...

I am encountering an issue where I am unable to successfully fetch a cookie from the Express backend to the React

const express = require("express"); // const storiesRouter = require("./routes/storiesRouter") // const postsRouter = require("./routes/postsRouter"); // const usersRouter = require("./routes/usersRouter"); const cors = require("cors"); const cookieParser ...

What's the reason for the icon not updating in the responsive mode?

I am venturing into the world of responsive web design for the first time. My aim is to create a website menu that drops down when the menu icon is clicked, using the onclick command in JavaScript. However, upon inspecting my browser, I noticed an uncaught ...

saving user information with asynchronous HTTP calls

I am encountering an issue while trying to save my form data using AJAX. When I submit the form data in a JavaScript file that calls another PHP file to perform an insertion operation, an error occurs. Here is the code snippet: <button id="submit" cl ...

Having trouble opening a JPEG file that was generated using the Writefile Api in Ionic-Cordova

Currently, I am using the writeFile API to create a JPEG image. The process is successful and the image is stored in the directory as expected. However, when I try to open the file manually from the directory, I encounter an error message saying "Oops! Cou ...

A single snippet of JavaScript blocking the loading of another script

I've encountered an issue where the code seems to be conflicting with itself. The top part works fine, but the bottom part doesn't. However, when I remove the top portion, everything works as intended! You can see a working example of both compo ...

JavaScript for Acrobat

I am currently creating a form in Adobe Acrobat and incorporating additional functionality using JavaScript. I have been searching for information on the control classes for the form, such as the member variables of a CheckBox, but haven't found any c ...

Error in Node.js Express: Attempted to access property 'image' of null resulting in an unhandled error event

I've been trying to identify where the issue lies. Can someone lend a hand with this? When attempting to submit the post without an image, instead of receiving a flash message, the following error pops up: and here's the source code link: https: ...

Modifying the URL path while navigating through pages with ajax and jQuery

I have implemented ajax post requests to enable paging on a feed within my website. Upon receiving the post request data, I refresh the page by clearing out previous content and displaying the new data retrieved from the request. In addition to this, I wan ...

Tips for accessing cart values when navigating to a different view in AngularJS

Hi, I'm currently working on a project involving a shopping cart. The project includes various categories with different products within each category. When adding a product to the cart from one category, it displays correctly. Likewise, adding anot ...

Troubles encountered in transferring arguments from npm command line to package.json using a bash script

This is a different question compared to this particular thread. I am in search of the optimal method to input command line arguments into my package.json file and npm scripts without necessarily passing it directly into a script. While there are queries ...

Turn off the ability to drag on an HTML page

Need help with creating an HTML etch-a-sketch! I have a div container with multiple div elements inside it, all set up with CSS grid display. HTML structure: <div id="canvas"></div> To populate the canvas with div elements, I'v ...