What is openpgp?
The openpgp npm package is a JavaScript implementation of the OpenPGP standard, which allows for encryption, decryption, signing, and verification of messages and files. It is widely used for secure communication and data protection.
What are openpgp's main functionalities?
Encrypting a message
This feature allows you to encrypt a message using a public key. The code sample demonstrates how to read a public key, create a message, and then encrypt it.
const openpgp = require('openpgp');
(async () => {
const publicKeyArmored = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----';
const message = 'Hello, world!';
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
const encrypted = await openpgp.encrypt({ message: await openpgp.createMessage({ text: message }), encryptionKeys: publicKey });
console.log(encrypted);
})();
Decrypting a message
This feature allows you to decrypt a message using a private key and passphrase. The code sample demonstrates how to read a private key, decrypt it with a passphrase, read an encrypted message, and then decrypt it.
const openpgp = require('openpgp');
(async () => {
const privateKeyArmored = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----';
const passphrase = 'yourPassphrase';
const encryptedMessage = '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----';
const privateKey = await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }), passphrase });
const message = await openpgp.readMessage({ armoredMessage: encryptedMessage });
const { data: decrypted } = await openpgp.decrypt({ message, decryptionKeys: privateKey });
console.log(decrypted);
})();
Signing a message
This feature allows you to sign a message using a private key and passphrase. The code sample demonstrates how to read a private key, decrypt it with a passphrase, create a message, and then sign it.
const openpgp = require('openpgp');
(async () => {
const privateKeyArmored = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----';
const passphrase = 'yourPassphrase';
const message = 'Hello, world!';
const privateKey = await openpgp.decryptKey({ privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }), passphrase });
const signedMessage = await openpgp.sign({ message: await openpgp.createMessage({ text: message }), signingKeys: privateKey });
console.log(signedMessage);
})();
Verifying a signed message
This feature allows you to verify a signed message using a public key. The code sample demonstrates how to read a public key, read a signed message, and then verify the signature.
const openpgp = require('openpgp');
(async () => {
const publicKeyArmored = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----';
const signedMessage = '-----BEGIN PGP SIGNED MESSAGE ... END PGP SIGNED MESSAGE-----';
const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });
const message = await openpgp.readMessage({ armoredMessage: signedMessage });
const verificationResult = await openpgp.verify({ message, verificationKeys: publicKey });
const { verified } = verificationResult.signatures[0];
try {
await verified;
console.log('Signature is valid');
} catch (e) {
console.log('Signature is invalid');
}
})();
Other packages similar to openpgp
node-forge
node-forge is a JavaScript library that provides a set of cryptographic utilities, including support for RSA, AES, and other encryption algorithms. It is more general-purpose compared to openpgp, which is specifically focused on the OpenPGP standard.
crypto
The crypto module is a built-in Node.js module that provides cryptographic functionality, including a set of wrappers for OpenSSL's hash, HMAC, cipher, decipher, sign, and verify functions. It is more low-level compared to openpgp, which provides higher-level abstractions for OpenPGP operations.
kbpgp
kbpgp is a JavaScript library for OpenPGP encryption and decryption, similar to openpgp. It is designed to be compatible with the Keybase platform and provides a simpler API for common OpenPGP operations.
OpenPGP.js 
OpenPGP.js is a JavaScript implementation of the OpenPGP protocol. This is defined in RFC 4880.

Table of Contents
Platform Support
-
OpenPGP.js v3.x is written in ES7 but is transpiled to ES5 using Babel to run in most environments. We support Node.js v8+ and browsers that implement window.crypto.getRandomValues.
-
The API uses the Async/Await syntax introduced in ES7 to return Promise objects. Async functions are available in most modern browsers. If you need to support older browsers, fear not! We use core-js to polyfill new features so that no action is required on your part!
-
For the OpenPGP HTTP Key Server (HKP) client the new fetch API is used. The module is polyfilled for browsers and is included as a dependency for Node.js runtimes.
Performance
-
Version 3.0.0 of the library introduces support for public-key cryptography using elliptic curves. We use native implementations on browsers and Node.js when available or Elliptic otherwise. Elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported (* = when available):
Curve | Encryption | Signature | Elliptic | NodeCrypto | WebCrypto |
---|
p256 | ECDH | ECDSA | Yes | Yes* | Yes* |
p384 | ECDH | ECDSA | Yes | Yes* | Yes* |
p521 | ECDH | ECDSA | Yes | Yes* | Yes* |
secp256k1 | ECDH | ECDSA | Yes | Yes* | No |
brainpoolP256r1 | ECDH | ECDSA | Yes | Yes* | No |
brainpoolP384r1 | ECDH | ECDSA | Yes | Yes* | No |
brainpoolP512r1 | ECDH | ECDSA | Yes | Yes* | No |
curve25519 | ECDH | N/A | Yes | No | No |
ed25519 | N/A | EdDSA | Yes | No | No |
-
Version 2.x of the library has been built from the ground up with Uint8Arrays. This allows for much better performance and memory usage than strings.
-
If the user's browser supports native WebCrypto via the window.crypto.subtle
API, this will be used. Under Node.js the native crypto module is used. This can be deactivated by setting openpgp.config.use_native = false
.
-
The library implements the IETF proposal for authenticated encryption using native AES-EAX, OCB, or GCM. This makes symmetric encryption up to 30x faster on supported platforms. Since the specification has not been finalized and other OpenPGP implementations haven't adopted it yet, the feature is currently behind a flag. Note: activating this setting can break compatibility with other OpenPGP implementations, and also with future versions of OpenPGP.js. Don't use it with messages you want to store on disk or in a database. You can enable it by setting openpgp.config.aead_protect = true
.
You can change the AEAD mode by setting one of the following options:
openpgp.config.aead_mode = openpgp.enums.aead.eax // Default, native
openpgp.config.aead_mode = openpgp.enums.aead.ocb // Non-native
openpgp.config.aead_mode = openpgp.enums.aead.experimental_gcm // **Non-standard**, fastest
We previously also implemented an earlier version of the draft (using GCM), which you could enable by setting openpgp.config.aead_protect = true
. If you need to stay compatible with that version, you need to set openpgp.config.aead_protect_version = 0
.
-
For environments that don't provide native crypto, the library falls back to asm.js implementations of AES, SHA-1, and SHA-256. We use Rusha and asmCrypto Lite (a minimal subset of asmCrypto.js built specifically for OpenPGP.js).
Getting started
Npm
npm install --save openpgp
Bower
bower install --save openpgp
Or just fetch a minified build under dist.
Examples
Here are some examples of how to use the v2.x+ API. For more elaborate examples and working code, please check out the public API unit tests. If you're upgrading from v1.x it might help to check out the documentation.
Set up
var openpgp = require('openpgp');
openpgp.initWorker({ path:'openpgp.worker.js' })
Encrypt and decrypt Uint8Array data with a password
var options, encrypted;
options = {
data: new Uint8Array([0x01, 0x01, 0x01]),
passwords: ['secret stuff'],
armor: false
};
openpgp.encrypt(options).then(function(ciphertext) {
encrypted = ciphertext.message.packets.write();
});
options = {
message: openpgp.message.read(encrypted),
passwords: ['secret stuff'],
format: 'binary'
};
openpgp.decrypt(options).then(function(plaintext) {
return plaintext.data
});
Encrypt and decrypt String data with PGP keys
const openpgp = require('openpgp')
openpgp.initWorker({ path:'openpgp.worker.js' })
const pubkey = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`
const privkey = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`
const passphrase = `yourPassphrase`
const encryptDecryptFunction = async() => {
const privKeyObj = openpgp.key.readArmored(privkey).keys[0]
await privKeyObj.decrypt(passphrase)
const options = {
data: 'Hello, World!',
publicKeys: openpgp.key.readArmored(pubkey).keys,
privateKeys: [privKeyObj]
}
openpgp.encrypt(options).then(ciphertext => {
encrypted = ciphertext.data
return encrypted
})
.then(encrypted => {
const options = {
message: openpgp.message.readArmored(encrypted),
publicKeys: openpgp.key.readArmored(pubkey).keys,
privateKeys: [privKeyObj]
}
openpgp.decrypt(options).then(plaintext => {
console.log(plaintext.data)
return plaintext.data
})
})
}
encryptDecryptFunction()
Encrypt with compression
By default, encrypt
will not use any compression. It's possible to override that behavior in two ways:
Either set the compression
parameter in the options object when calling encrypt
.
var options, encrypted;
options = {
data: new Uint8Array([0x01, 0x02, 0x03]),
passwords: ['secret stuff'],
compression: openpgp.enums.compression.zip
};
ciphertext = await openpgp.encrypt(options);
Or, override the config to enable compression:
openpgp.config.compression = openpgp.enums.compression.zip
Where the value can be any of:
openpgp.enums.compression.zip
openpgp.enums.compression.zlib
openpgp.enums.compression.bzip2
Generate new key pair
RSA keys:
var options = {
userIds: [{ name:'Jon Smith', email:'jon@example.com' }],
numBits: 4096,
passphrase: 'super long and hard to guess secret'
};
ECC keys:
Possible values for curve are: curve25519
, ed25519
, p256
, p384
, p521
, secp256k1
,
brainpoolP256r1
, brainpoolP384r1
, or brainpoolP512r1
.
Note that options both curve25519
and ed25519
generate a primary key for signing using Ed25519
and a subkey for encryption using Curve25519.
var options = {
userIds: [{ name:'Jon Smith', email:'jon@example.com' }],
curve: "ed25519",
passphrase: 'super long and hard to guess secret'
};
openpgp.generateKey(options).then(function(key) {
var privkey = key.privateKeyArmored;
var pubkey = key.publicKeyArmored;
var revocationSignature = key.revocationSignature;
});
Revoke a key
Using a revocation signature:
var options = {
key: openpgp.key.readArmored(pubkey).keys[0],
revocationSignature: revocationSignature
};
Using the private key:
var options = {
key: openpgp.key.readArmored(privkey).keys[0]
};
openpgp.revokeKey(options).then(function(key) {
var pubkey = key.publicKeyArmored;
});
Lookup public key on HKP server
var hkp = new openpgp.HKP('https://pgp.mit.edu');
var options = {
query: 'alice@example.com'
};
hkp.lookup(options).then(function(key) {
var pubkey = openpgp.key.readArmored(key);
});
Upload public key to HKP server
var hkp = new openpgp.HKP('https://pgp.mit.edu');
var pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----';
hkp.upload(pubkey).then(function() { ... });
Sign and verify cleartext messages
var options, cleartext, validity;
var pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----';
var privkey = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----';
var passphrase = 'secret passphrase';
var privKeyObj = openpgp.key.readArmored(privkey).keys[0];
await privKeyObj.decrypt(passphrase);
options = {
data: 'Hello, World!',
privateKeys: [privKeyObj]
};
openpgp.sign(options).then(function(signed) {
cleartext = signed.data;
});
options = {
message: openpgp.cleartext.readArmored(cleartext),
publicKeys: openpgp.key.readArmored(pubkey).keys
};
openpgp.verify(options).then(function(verified) {
validity = verified.signatures[0].valid;
if (validity) {
console.log('signed by key id ' + verified.signatures[0].keyid.toHex());
}
});
Create and verify detached signatures
var options, detachedSig, validity;
var pubkey = '-----BEGIN PGP PUBLIC KEY BLOCK ... END PGP PUBLIC KEY BLOCK-----';
var privkey = '-----BEGIN PGP PRIVATE KEY BLOCK ... END PGP PRIVATE KEY BLOCK-----';
var passphrase = 'secret passphrase';
var privKeyObj = openpgp.key.readArmored(privkey).keys[0];
await privKeyObj.decrypt(passphrase);
options = {
data: 'Hello, World!',
privateKeys: [privKeyObj],
detached: true
};
openpgp.sign(options).then(function(signed) {
detachedSig = signed.signature;
});
options = {
message: openpgp.message.fromText('Hello, World!'),
signature: openpgp.signature.readArmored(detachedSig),
publicKeys: openpgp.key.readArmored(pubkey).keys
};
openpgp.verify(options).then(function(verified) {
validity = verified.signatures[0].valid;
if (validity) {
console.log('signed by key id ' + verified.signatures[0].keyid.toHex());
}
});
Documentation
A jsdoc build of our code comments is available at doc/index.html. Public calls should generally be made through the OpenPGP object doc/openpgp.html.
Security Audit
To date the OpenPGP.js code base has undergone two complete security audits from Cure53. The first audit's report has been published here.
Security recommendations
It should be noted that js crypto apps deployed via regular web hosting (a.k.a. host-based security) provide users with less security than installable apps with auditable static versions. Installable apps can be deployed as a Firefox or Chrome packaged app. These apps are basically signed zip files and their runtimes typically enforce a strict Content Security Policy (CSP) to protect users against XSS. This blogpost explains the trust model of the web quite well.
It is also recommended to set a strong passphrase that protects the user's private key on disk.
Development
To create your own build of the library, just run the following command after cloning the git repo. This will download all dependencies, run the tests and create a minified bundle under dist/openpgp.min.js
to use in your project:
npm install && npm test
For debugging browser errors, you can open test/unittests.html
in a browser or, after running the following command, open http://localhost:3000/test/unittests.html
:
grunt browsertest
How do I get involved?
You want to help, great! Go ahead and fork our repo, make your changes and send us a pull request.
License
GNU Lesser General Public License (3.0 or any later version). Please take a look at the LICENSE file for more information.
Resources
Below is a collection of resources, many of these were projects that were in someway a precursor to the current OpenPGP.js project. If you'd like to add your link here, please do so in a pull request or email to the list.