• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

openpgpjs/openpgpjs: OpenPGP implementation for JavaScript

原作者: [db:作者] 来自: 网络 收藏 邀请

开源软件名称:

openpgpjs/openpgpjs

开源软件地址:

https://github.com/openpgpjs/openpgpjs

开源编程语言:

JavaScript 99.1%

开源软件介绍:

OpenPGP.js BrowserStack Status Join the chat on Gitter

OpenPGP.js is a JavaScript implementation of the OpenPGP protocol. It implements RFC4880 and parts of RFC4880bis.

Table of Contents

Platform Support

  • The dist/openpgp.min.js bundle works well with recent versions of Chrome, Firefox, Safari and Edge.

  • The dist/node/openpgp.min.js bundle works well in Node.js. It is used by default when you require('openpgp') in Node.js.

  • Currently, Chrome, Safari and Edge have partial implementations of the Streams specification, and Firefox has a partial implementation behind feature flags. Chrome is the only browser that implements TransformStreams, which we need, so we include a polyfill for all other browsers. Please note that in those browsers, the global ReadableStream property gets overwritten with the polyfill version if it exists. In some edge cases, you might need to use the native ReadableStream (for example when using it to create a Response object), in which case you should store a reference to it before loading OpenPGP.js. There is also the web-streams-adapter library to convert back and forth between them.

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. Elliptic curve cryptography provides stronger security per bits of key, which allows for much faster operations. Currently the following curves are supported:

    Curve Encryption Signature NodeCrypto WebCrypto Constant-Time
    curve25519 ECDH N/A No No Algorithmically**
    ed25519 N/A EdDSA No No Algorithmically**
    p256 ECDH ECDSA Yes* Yes* If native***
    p384 ECDH ECDSA Yes* Yes* If native***
    p521 ECDH ECDSA Yes* Yes* If native***
    brainpoolP256r1 ECDH ECDSA Yes* No If native***
    brainpoolP384r1 ECDH ECDSA Yes* No If native***
    brainpoolP512r1 ECDH ECDSA Yes* No If native***
    secp256k1 ECDH ECDSA Yes* No If native***

    * when available
    ** the curve25519 and ed25519 implementations are algorithmically constant-time, but may not be constant-time after optimizations of the JavaScript compiler
    *** these curves are only constant-time if the underlying native implementation is available and constant-time

  • 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.

  • 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.aeadProtect = true.

    You can change the AEAD mode by setting one of the following options:

    openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax // Default, native
    openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb // Non-native
    openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.experimentalGCM // **Non-standard**, fastest
    
  • For environments that don't provide native crypto, the library falls back to asm.js implementations of AES, SHA-1, and SHA-256.

Getting started

Node.js

Install OpenPGP.js using npm and save it in your dependencies:

npm install --save openpgp

And import it as a CommonJS module:

const openpgp = require('openpgp');

Or as an ES6 module, from an .mjs file:

import * as openpgp from 'openpgp';

Deno (experimental)

Import as an ES6 module, using /dist/openpgp.mjs.

import * as openpgp from './openpgpjs/dist/openpgp.mjs';

Browser (webpack)

Install OpenPGP.js using npm and save it in your devDependencies:

npm install --save-dev openpgp

And import it as an ES6 module:

import * as openpgp from 'openpgp';

You can also only import the functions you need, as follows:

import { readMessage, decrypt } from 'openpgp';

Or, if you want to use the lightweight build (which is smaller, and lazily loads non-default curves on demand):

import * as openpgp from 'openpgp/lightweight';

To test whether the lazy loading works, try to generate a key with a non-standard curve:

import { generateKey } from 'openpgp/lightweight';
await generateKey({ curve: 'brainpoolP512r1',  userIDs: [{ name: 'Test', email: '[email protected]' }] });

For more examples of how to generate a key, see Generate new key pair. It is recommended to use curve25519 instead of brainpoolP512r1 by default.

Browser (plain files)

Grab openpgp.min.js from unpkg.com/openpgp/dist, and load it in a script tag:

<script src="openpgp.min.js"></script>

Or, to load OpenPGP.js as an ES6 module, grab openpgp.min.mjs from unpkg.com/openpgp/dist, and import it as follows:

<script type="module">
import * as openpgp from './openpgp.min.mjs';
</script>

To offload cryptographic operations off the main thread, you can implement a Web Worker in your application and load OpenPGP.js from there. For an example Worker implementation, see test/worker/worker_example.js.

Examples

Here are some examples of how to use OpenPGP.js v5. For more elaborate examples and working code, please check out the public API unit tests. If you're upgrading from v4 it might help to check out the changelog and documentation.

Encrypt and decrypt Uint8Array data with a password

Encryption will use the algorithm specified in config.preferredSymmetricAlgorithm (defaults to aes256), and decryption will use the algorithm used for encryption.

(async () => {
    const message = await openpgp.createMessage({ binary: new Uint8Array([0x01, 0x01, 0x01]) });
    const encrypted = await openpgp.encrypt({
        message, // input as Message object
        passwords: ['secret stuff'], // multiple passwords possible
        format: 'binary' // don't ASCII armor (for Uint8Array output)
    });
    console.log(encrypted); // Uint8Array

    const encryptedMessage = await openpgp.readMessage({
        binaryMessage: encrypted // parse encrypted bytes
    });
    const { data: decrypted } = await openpgp.decrypt({
        message: encryptedMessage,
        passwords: ['secret stuff'], // decrypt with password
        format: 'binary' // output as Uint8Array
    });
    console.log(decrypted); // Uint8Array([0x01, 0x01, 0x01])
})();

Encrypt and decrypt String data with PGP keys

Encryption will use the algorithm preferred by the public (encryption) key (defaults to aes256 for keys generated in OpenPGP.js), and decryption will use the algorithm used for encryption.

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

(async () => {
    // put keys in backtick (``) to avoid errors caused by spaces or tabs
    const publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`;
    const privateKeyArmored = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
    const passphrase = `yourPassphrase`; // what the private key is encrypted with

    const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });

    const privateKey = await openpgp.decryptKey({
        privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
        passphrase
    });

    const encrypted = await openpgp.encrypt({
        message: await openpgp.createMessage({ text: 'Hello, World!' }), // input as Message object
        encryptionKeys: publicKey,
        signingKeys: privateKey // optional
    });
    console.log(encrypted); // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'

    const message = await openpgp.readMessage({
        armoredMessage: encrypted // parse armored message
    });
    const { data: decrypted, signatures } = await openpgp.decrypt({
        message,
        verificationKeys: publicKey, // optional
        decryptionKeys: privateKey
    });
    console.log(decrypted); // 'Hello, World!'
    // check signature validity (signed messages only)
    try {
        await signatures[0].verified; // throws on invalid signature
        console.log('Signature is valid');
    } catch (e) {
        throw new Error('Signature could not be verified: ' + e.message);
    }
})();

Encrypt to multiple public keys:

(async () => {
    const publicKeysArmored = [
        `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`,
        `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`
    ];
    const privateKeyArmored = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`;    // encrypted private key
    const passphrase = `yourPassphrase`; // what the private key is encrypted with
    const plaintext = 'Hello, World!';

    const publicKeys = await Promise.all(publicKeysArmored.map(armoredKey => openpgp.readKey({ armoredKey })));

    const privateKey = await openpgp.decryptKey({
        privateKey: await openpgp.readKey({ armoredKey: privateKeyArmored }),
        passphrase
    });

    const message = await openpgp.createMessage({ text: plaintext });
    const encrypted = await openpgp.encrypt({
        message, // input as Message object
        encryptionKeys: publicKeys,
        signingKeys: privateKey // optional
    });
    console.log(encrypted); // '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
})();

If you expect an encrypted message to be signed with one of the public keys you have, and do not want to trust the decrypted data otherwise, you can pass the decryption option expectSigned = true, so that the decryption operation will fail if no valid signature is found:

(async () => {
    // put keys in backtick (``) to avoid errors caused by spaces or tabs
    const publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`;
    const privateKeyArmored = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`; // encrypted private key
    const passphrase = `yourPassphrase`; // what the private key is encrypted with

    const publicKey = await openpgp.readKey({ armoredKey: publicKeyArmored });

    const privateKey = await openpgp.decryptKey({
        privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
        passphrase
    });

    const encryptedAndSignedMessage = `-----BEGIN PGP MESSAGE-----
...
-----END PGP MESSAGE-----`;

    const message = await openpgp.readMessage({
        armoredMessage: encryptedAndSignedMessage // parse armored message
    });
    // decryption will fail if all signatures are invalid or missing
    const { data: decrypted, signatures } = await openpgp.decrypt({
        message,
        decryptionKeys: privateKey,
        expectSigned: true,
        verificationKeys: publicKey, // mandatory with expectSigned=true
    });
    console.log(decrypted); // 'Hello, World!'
})();

Encrypt symmetrically with compression

By default, encrypt will not use any compression when encrypting symmetrically only (i.e. when no encryptionKeys are given). It's possible to change that behaviour by enabling compression through the config, either for the single encryption:

(async () => {
    const message = await openpgp.createMessage({ binary: new Uint8Array([0x01, 0x02, 0x03]) }); // or createMessage({ text: 'string' })
    const encrypted = await openpgp.encrypt({
        message,
        passwords: ['secret stuff'], // multiple passwords possible
        config: { preferredCompressionAlgorithm: openpgp.enums.compression.zlib } // compress the data with zlib
    });
})();

or by changing the default global configuration:

openpgp.config.preferredCompressionAlgorithm = openpgp.enums.compression.zlib

Where the value can be any of:

  • openpgp.enums.compression.zip
  • openpgp.enums.compression.zlib
  • openpgp.enums.compression.uncompressed (default)

Streaming encrypt Uint8Array data with a password

(async () => {
    const readableStream = new ReadableStream({
        start(controller) {
            controller.enqueue(new Uint8Array([0x01, 0x02, 0x03]));
            controller.close();
        }
    });

    const message = await openpgp.createMessage({ binary: readableStream });
    const encrypted = await openpgp.encrypt({
        message, // input as Message object
        passwords: ['secret stuff'], // multiple passwords possible
        format: 'binary' // don't ASCII armor (for Uint8Array output)
    });
    console.log(encrypted); // raw encrypted packets as ReadableStream<Uint8Array>

    // Either pipe the above stream somewhere, pass it to another function,
    // or read it manually as follows:
    for await (const chunk of encrypted) {
        console.log('new chunk:', chunk); // Uint8Array
    }
})();

For more information on using ReadableStreams, see the MDN Documentation on the Streams API.

You can also pass a Node.js Readable stream, in which case OpenPGP.js will return a Node.js Readable stream as well, which you can .pipe() to a Writable stream, for example.

Streaming encrypt and decrypt String data with PGP keys


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap