OpenPGP.js 使用指南:基于 RFC 9580 的 JavaScript OpenPGP 实现与实战示例
OpenPGP.js 使用指南:基于 RFC 9580 的 JavaScript OpenPGP 实现与实战示例
OpenPGP.js 是纯 JavaScript 实现的 OpenPGP 协议库,可在浏览器与 Node.js 中完成密钥生成、加密解密、签名验签与流式处理。本文以仓库根目录 README.md 为核心骨架,结合 src/openpgp.js 的高层 API 实现、src/config.ts 的全局配置默认值以及 test/general/openpgp.js 的单元测试,系统讲解其平台支持、算法能力、安装方式与全部官方代码示例,帮助读者快速在生产项目中落地 PGP 加解密与签名能力。
项目概览:从 RFC 4880 到 RFC 9580
OpenPGP.js 是 OpenPGP 协议的 JavaScript 实现,当前版本(仓库 package.json 中标注为 6.3.0)实现的是 RFC 9580(取代 RFC 4880 与 RFC 4880bis 草案)。RFC 9580 即 OpenPGP 的 "crypto-refresh" 刷新版本,带来了一系列新特性:
- v6 密钥 与 v6 签名(可在 src/config.ts 中通过
v6Keys: false开关控制,默认关闭以保持兼容); - AEAD 认证加密(AES-GCM / OCB / EAX)作为标准能力(此前在 v5 中仅支持 RFC 4880bis 的临时版本);
- 新的 X25519 / X448 / Ed25519 / Ed448 公钥算法标识(见 src/enums.js 中
publicKey枚举:x25519: 25、ed25519: 27等)。
该库的对外 API 由 src/index.js 统一导出:包括 encrypt、decrypt、sign、verify、generateKey、reformatKey、revokeKey、decryptKey、encryptKey、generateSessionKey、encryptSessionKey、decryptSessionKeys 等高层函数,以及 Message、CleartextMessage、PrivateKey、PublicKey、Subkey、Signature 等对象类型与 enums、config 两个配置命名空间。
平台支持与运行环境要求
各平台可用的构建产物
| 使用场景 | 构建产物 | 说明 |
|---|---|---|
| 浏览器(经典 script 标签) | dist/openpgp.min.js |
支持近期版本的 Chrome、Firefox、Edge 与 Safari 14+ |
| 浏览器(ES module) | dist/openpgp.min.mjs |
以 <script type="module"> 方式加载 |
| Node.js(ES module) | dist/node/openpgp.min.mjs |
import ... from 'openpgp' 时默认使用 |
| Node.js(CommonJS) | dist/node/openpgp.min.cjs |
require('openpgp') 时默认使用,要求 Node.js v18+ |
| Deno(实验性) | dist/openpgp.mjs |
直接以 ES6 module 导入 |
Node.js 端通过 package.json 的 exports 字段自动分流:"import" 指向 ./dist/node/openpgp.mjs,"require" 指向 ./dist/node/openpgp.min.cjs;浏览器构建则由 "browser" 字段与 "exports.browser" 指向 ./dist/openpgp.min.mjs。
两个硬性依赖:Web Crypto API 与 Web Streams API
无论运行在哪个平台,OpenPGP.js 都要求:
- Web Cryptography API 的
SubtleCrypto:在浏览器中仅在安全上下文(HTTPS 或 localhost)下可用;在受支持的 Node.js 版本中始终可用。 - Web Streams API:浏览器端使用流输入时需要
ReadableStream与TransformStream支持。
关于 Web Streams,v6 起有两个重要变化,值得特别留意:
- 不再自动 polyfill:在 v5 及更早版本中,库会自动为浏览器打上 Web Streams polyfill;从 v6 开始这一职责交由使用方,以避免 polyfill 带来的全局副作用。如果目标浏览器不支持(例如缺少
TransformStream),需要手动加载 web-streams-polyfill 这类 polyfill 库。 - Node.js 端只接受 Web Streams:v6 不再支持 Node 原生
Readable流作为输入,而是期望(并输出)Node 的 Web Streams(ReadableStream)。Node v17+ 提供了Readable.toWeb()/Readable.fromWeb()等工具用于双向转换。
另有两个容易踩坑的细节:加载 polyfill 时,全局 ReadableStream 属性(如果已存在)会被 polyfill 版本覆盖,某些边界场景(如用 ReadableStream 构造 Response 对象)需要先保存原生引用;此外还可以借助 web-streams-adapter 类库在原生流与 polyfill 流之间互相转换。
性能与密码学能力
椭圆曲线支持矩阵
自 3.0.0 版本起,OpenPGP.js 引入椭圆曲线公钥加密。相比 RSA,椭圆曲线在相同安全强度下密钥更短、运算更快。库会优先使用浏览器与 Node.js 的原生实现。目前支持的曲线如下:
| 曲线 | 加密 | 签名 | NodeCrypto | WebCrypto | 常数时间 |
|---|---|---|---|---|---|
| curve25519 | ECDH | N/A | No | No | 算法层面 |
| ed25519 | N/A | EdDSA | No | Yes* | 仅原生** |
| nistP256 | ECDH | ECDSA | Yes* | Yes* | 仅原生** |
| nistP384 | ECDH | ECDSA | Yes* | Yes* | 仅原生** |
| nistP521 | ECDH | ECDSA | Yes* | Yes* | 仅原生** |
| brainpoolP256r1 | ECDH | ECDSA | Yes* | No | 仅原生** |
| brainpoolP384r1 | ECDH | ECDSA | Yes* | No | 仅原生** |
| brainpoolP512r1 | ECDH | ECDSA | Yes* | No | 仅原生** |
| secp256k1 | ECDH | ECDSA | Yes* | No | 仅原生** |
* 表示"在可用时"使用原生实现;** 表示只有底层原生实现存在且为常数时间时,该曲线才是常数时间的。
曲线名称在 src/enums.js 的 enums.curve 枚举中定义(nistP256、nistP384、nistP521、secp256k1、brainpoolP256r1/r384r1/r512r1,以及已废弃但仍可解析的 curve25519Legacy、ed25519Legacy)。值得注意的默认行为是:curve25519 与 ed25519 选项都会生成 Ed25519 签名主密钥 + Curve25519 加密子密钥的组合。
性能设计上,库优先调用平台原生的 Web Crypto API;在 Node.js 上还会使用原生 crypto 模块以获得额外能力(如某些 AEAD 模式)。当平台原生 API 不支持某些曲线时,src/config.ts 中的 useEllipticFallback: true 会回退到 noble-curves 库(可在 src/crypto/public_key/elliptic/noble_curves.js 看到实现)。
AEAD 认证加密(RFC 9580)
OpenPGP.js 按 RFC 9580 实现了 AEAD 认证加密,支持 AES-GCM、OCB、EAX 三种模式,可显著提升对称加密在原生平台上的性能。但由于 RFC 9580 较新,其他 OpenPGP 实现可能尚未支持,开启该特性可能破坏与它们的互操作性,因此默认处于关闭状态。
开启方式:
openpgp.config.aeadProtect = true;
注意:此开关与 OpenPGP.js v5 中的同名设置效果不同。v5 实现的是 RFC 4880bis 的临时版 AEAD(
experimentalGCM,即 src/enums.js 中标记为 deprecated 的aead.experimentalGCM: 100),而 RFC 9580 已对其进行修改,两种格式不能混用。
切换 AEAD 模式(枚举值定义见 src/enums.js):
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.gcm; // 默认,WebCrypto 与 Node.js 均有原生实现
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.ocb; // 无原生实现,但在 RFC 9580 实现间兼容性最好
openpgp.config.preferredAEADAlgorithm = openpgp.enums.aead.eax; // Node.js 原生支持
从 src/config.ts 的默认值可以看到,preferredAEADAlgorithm 默认 gcm、aeadChunkSizeByte 默认 12(合法取值范围 0–56),且仅当 aeadProtect 为 true 时生效。该配置同时影响密钥生成(加密密钥偏好)、密码加密消息以及私钥加密三类场景;公钥加密消息则遵循加密密钥自身的偏好。
快速开始:安装与引入
Node.js
使用 npm 安装并保存为运行时依赖:
npm install --save openpgp
在 .mjs 文件中以 ES module 引入:
import * as openpgp from 'openpgp';
或使用 CommonJS:
const openpgp = require('openpgp');
Deno(实验性)
直接以 ES6 module 方式导入 dist/openpgp.mjs:
import * as openpgp from './openpgpjs/dist/openpgp.mjs';
浏览器(webpack 等打包器)
安装并保存为 devDependencies:
npm install --save-dev openpgp
按需导入:
import * as openpgp from 'openpgp';
也可以只导入用到的函数,配合 tree-shaking 减小打包体积:
import { readMessage, decrypt } from 'openpgp';
若希望使用更小的 lightweight 构建(体积更小,非标准曲线按需惰性加载),可导入 openpgp/lightweight:
import * as openpgp from 'openpgp/lightweight';
该入口在 package.json 的 exports 字段中声明("./lightweight" 指向 ./dist/lightweight/openpgp.min.mjs),lightweight/package.json 则是其独立的包清单。验证惰性加载是否生效,可尝试生成非标准曲线密钥:
import { generateKey } from 'openpgp/lightweight';
await generateKey({ curve: 'brainpoolP512r1', userIDs: [{ name: 'Test', email: 'test@test.com' }] });
更完整的密钥生成示例见下文"生成新密钥对"一节。官方建议默认使用
curve25519而非brainpoolP512r1。
浏览器(直接引用文件)
从 unpkg 获取 openpgp.min.js 后以 script 标签引入:
<script src="openpgp.min.js"></script>
或获取 openpgp.min.mjs 以 ES6 module 方式加载:
<script type="module">
import * as openpgp from './openpgp.min.mjs';
</script>
Web Worker 加速:为把密码学运算移出主线程,可以在应用中实现一个 Web Worker 并在其中加载 OpenPGP.js。仓库提供了可直接参考的 Worker 实现 test/worker/worker_example.js,其核心模式是:
importScripts('../../dist/openpgp.js');
onmessage = async function({ data: { action, message }, ports: [port] }) {
// 在 Worker 内读取密钥、解密私钥、执行 encrypt/decrypt/sign 等操作
};
TypeScript 支持
TypeScript 尚未完全集成进库中,TS 相关的依赖目前列在 devDependencies 中,因此编译项目时需要手动添加 @openpgp/web-stream-tools:
npm install --save-dev @openpgp/web-stream-tools
类型定义文件位于 src/index.d.ts(以及 dist/types/index.d.ts 构建产物),仓库中的 test/typescript/definitions.ts 是类型定义的一致性测试。
从旧版本升级
官方建议尽快升级到最新大版本以获得安全与性能改进。发布新大版本时,项目会同步公布上一版本的停止维护(EOL)日期;哪些库版本已被废弃、不再接收安全补丁,可查询 npm 发布页的版本列表。升级到最新版本的具体指引,参考项目 Wiki 中的"Updating from previous versions"页面。本文所有示例均基于 v6 API 编写——注意 v6 中 encrypt/decrypt/sign/verify 的参数命名发生了显著变化(如 publicKeys 改名为 encryptionKeys、privateKeys 改名为 signingKeys/decryptionKeys),在 src/openpgp.js 中可以看到对这些旧选项的显式报错提示。
官方代码示例详解
以下示例均来自仓库 README.md,并已结合源码验证。需要更完整、可运行的代码,可查阅 test/general/openpgp.js 中的 public API 单元测试。
用密码加密/解密 Uint8Array 数据
加密使用 config.preferredSymmetricAlgorithm 指定的算法(默认 aes256,见 src/config.ts),解密则使用加密时所用的算法。
(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])
})();
关键点:createMessage 会把二进制数据包装成 LiteralDataPacket(内部实现见 src/message.js);encrypt 的 format 支持 'armored'(默认)、'binary'、'object' 三档;readMessage 则接受 armoredMessage 或 binaryMessage 作为输入。decrypt 返回对象中包含 data(明文)与 signatures(签名列表)等字段。
用 PGP 密钥加密/解密 String 数据
加密使用公钥(加密子密钥)偏好的算法(OpenPGP.js 生成的密钥默认偏好 aes256),解密使用加密时所用的算法。
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);
}
})();
源码层面的支撑点:
readKey/readPrivateKey(src/key/factory.js)会先调用unarmor解 ASCII 装甲,再通过PacketList.fromBinary解析数据包,分别校验装甲类型(publicKey/privateKey)与密钥包存在性;decryptKey(src/openpgp.js)基于克隆后的私钥对象解密(不会修改原密钥),并用keyPacket.decrypt(passphrase, config)逐个尝试传入的多个 passphrase,最后调用validate校验密钥结构;decrypt(src/openpgp.js)内部依次执行message.decrypt(...)与message.verify(...),并把每个签名包映射为{ keyID, verified, signature }数组——verified是一个 Promise,无效签名时 reject,因此示例中用try/await捕获;- 常见的换行/制表符导致的粘贴错误,官方建议把密钥放在反引号(
`)模板字符串中。
加密给多个公钥
(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-----'
})();
encrypt 内部(src/openpgp.js)先把 encryptionKeys、signingKeys、passwords 等参数通过 toArray 归一化为数组,随后按 sign → compress → encrypt 的顺序处理:有签名密钥时先调用 message.sign(...),再依据加密密钥偏好选择压缩算法压缩,最后调用 message.encrypt(...) 执行会话密钥加密。
强制要求签名(expectSigned)
如果预期收到的加密消息必然使用你持有的公钥之一签名,且不想信任未经签名的解密数据,可以传入解密选项 expectSigned = true:若未找到有效签名,解密操作将直接失败。
(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!'
})();
对应源码在 src/openpgp.js:expectSigned 为真时,若 verificationKeys 为空或 signatures 为空,会分别抛出 "Verification keys are required..." 与 "Message is not signed" 错误。
对称加密时启用压缩
默认情况下,仅使用密码(不传 encryptionKeys)的对称加密不会压缩。可以通过配置改变这一行为——只对单次加密生效:
(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
});
})();
或者修改全局默认配置:
openpgp.config.preferredCompressionAlgorithm = openpgp.enums.compression.zlib
取值可以是(枚举定义见 src/enums.js):
openpgp.enums.compression.zipopenpgp.enums.compression.zlibopenpgp.enums.compression.uncompressed(默认)
说明:
enums.compression中还包含bzip2(值 3),但 README 明确列出的可选值以 zip/zlib/uncompressed 为主。encrypt接受顶层config参数并与默认配置浅合并({ ...defaultConfig, ...config }),这正是"单次加密覆盖全局配置"的机制,参见 src/openpgp.js。此外 src/config.ts 中的maxDecompressedMessageSize(默认Infinity)与enforceGrammar: true等项共同影响解压与消息解析行为。
流式加密 Uint8Array 数据(密码)
(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
}
})();
createMessage 在输入为 ReadableStream 时会产生流式 Message(message.fromStream 被标记为 true,见 src/message.js),随后 encrypt 返回的也是 ReadableStream<Uint8Array>,可以直接 for await ... of 消费。关于 ReadableStream 在浏览器与 Node.js 中的用法,可参考 Web Streams API 的相关文档。
流式加密/解密 String 数据(PGP 密钥)
(async () => {
const publicKeyArmored = `-----BEGIN PGP PUBLIC KEY BLOCK-----
...
-----END PGP PUBLIC KEY BLOCK-----`; // Public key
const privateKeyArmored = `-----BEGIN PGP PRIVATE KEY BLOCK-----
...
-----END PGP PRIVATE KEY BLOCK-----`; // Encrypted private key
const passphrase = `yourPassphrase`; // Password that 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 readableStream = new ReadableStream({
start(controller) {
controller.enqueue('Hello, world!');
controller.close();
}
});
const encrypted = await openpgp.encrypt({
message: await openpgp.createMessage({ text: readableStream }), // input as Message object
encryptionKeys: publicKey,
signingKeys: privateKey // optional
});
console.log(encrypted); // ReadableStream containing '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
const message = await openpgp.readMessage({
armoredMessage: encrypted // parse armored message
});
const decrypted = await openpgp.decrypt({
message,
verificationKeys: publicKey, // optional
decryptionKeys: privateKey
});
const chunks = [];
for await (const chunk of decrypted.data) {
chunks.push(chunk);
}
const plaintext = chunks.join('');
console.log(plaintext); // 'Hello, World!'
})();
注意流式场景下 decrypt 返回的 data 也是流,必须消费完(例如 for await)才能真正得到明文——这一特性与下方"流式签名验证"一节中"必须读取 verificationResult.data 才会触发验证"的原理一致(见 src/openpgp.js 中 linkStreams 对流的链接与错误转发)。
生成新密钥对
ECC 密钥(更小、生成更快):
curve 的合法取值为:curve25519、ed25519、nistP256、nistP384、nistP521、brainpoolP256r1、brainpoolP384r1、brainpoolP512r1、secp256k1。注意 curve25519 与 ed25519 都会生成 Ed25519 签名主密钥 + Curve25519 加密子密钥的组合。
(async () => {
const { privateKey, publicKey, revocationCertificate } = await openpgp.generateKey({
type: 'ecc', // Type of the key, defaults to ECC
curve: 'curve25519', // ECC curve name, defaults to curve25519
userIDs: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs
passphrase: 'super long and hard to guess secret', // protects the private key
format: 'armored' // output key format, defaults to 'armored' (other options: 'binary' or 'object')
});
console.log(privateKey); // '-----BEGIN PGP PRIVATE KEY BLOCK ... '
console.log(publicKey); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
console.log(revocationCertificate); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
})();
RSA 密钥(兼容性更好):
(async () => {
const { privateKey, publicKey } = await openpgp.generateKey({
type: 'rsa', // Type of the key
rsaBits: 4096, // RSA key size (defaults to 4096 bits)
userIDs: [{ name: 'Jon Smith', email: 'jon@example.com' }], // you can pass multiple user IDs
passphrase: 'super long and hard to guess secret' // protects the private key
});
})();
generateKey 的实现细节(src/openpgp.js):
- 参数校验:v4 密钥必须提供
userIDs(否则抛出 "UserIDs are required for V4 keys");RSA 的rsaBits不得低于config.minRSABits(默认 2047,历史原因是为兼容旧版可能生成 2047 位密钥的 bug,见 src/config.ts); format支持'armored'(默认)/'binary'/'object'三种输出;返回对象为{ privateKey, publicKey, revocationCertificate },其中吊销证书始终为 armored 字符串;- 内部通过 src/key/factory.js 的
generate生成密钥包,并用checkKeyRequirements校验密钥用途(flags)。
此外,generateKey 还支持 date、keyExpirationTime(秒,默认 0 表示永不过期)、subkeys(如 [{sign: true, passphrase: '123'}])、signatureNotations 等高级选项。
撤销密钥
使用吊销证书(revocationCertificate 在 generateKey 时随私钥一起生成,务必妥善保管):
(async () => {
const { publicKey: revokedKeyArmored } = await openpgp.revokeKey({
key: await openpgp.readKey({ armoredKey: publicKeyArmored }),
revocationCertificate,
format: 'armored' // output armored keys
});
console.log(revokedKeyArmored); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
})();
使用私钥直接撤销:
(async () => {
const { publicKey: revokedKeyArmored } = await openpgp.revokeKey({
key: await openpgp.readKey({ armoredKey: privateKeyArmored }),
format: 'armored' // output armored keys
});
console.log(revokedKeyArmored); // '-----BEGIN PGP PUBLIC KEY BLOCK ... '
})();
revokeKey(src/openpgp.js)的逻辑是:传了 revocationCertificate 就走 key.applyRevocationCertificate(...),否则走 key.revoke(reasonForRevocation, ...);返回值取决于输入密钥类型——私钥返回 { privateKey, publicKey },公钥返回 { privateKey: null, publicKey }。
明文消息(Cleartext)签名与验证
(async () => {
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 unsignedMessage = await openpgp.createCleartextMessage({ text: 'Hello, World!' });
const cleartextMessage = await openpgp.sign({
message: unsignedMessage, // CleartextMessage or Message object
signingKeys: privateKey
});
console.log(cleartextMessage); // '-----BEGIN PGP SIGNED MESSAGE ... END PGP SIGNATURE-----'
const signedMessage = await openpgp.readCleartextMessage({
cleartextMessage // parse armored message
});
const verificationResult = await openpgp.verify({
message: signedMessage,
verificationKeys: publicKey
});
const { verified, keyID } = verificationResult.signatures[0];
try {
await verified; // throws on invalid signature
console.log('Signed by key id ' + keyID.toHex());
} catch (e) {
throw new Error('Signature could not be verified: ' + e.message);
}
})();
Cleartext 签名(-----BEGIN PGP SIGNED MESSAGE-----)的特点是明文本身可读、签名附于其后,非常适合邮件正文等场景。src/cleartext.js 中的 readCleartextMessage 会解析装甲头(Hash: 头与签名中的哈希算法必须匹配,否则抛 "Hash algorithm mismatch"),verify 返回的 keyID 对象可通过 toHex() 输出十六进制指纹。
创建与验证分离式(detached)签名
(async () => {
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 message = await openpgp.createMessage({ text: 'Hello, World!' });
const detachedSignature = await openpgp.sign({
message, // Message object
signingKeys: privateKey,
detached: true
});
console.log(detachedSignature);
const signature = await openpgp.readSignature({
armoredSignature: detachedSignature // parse detached signature
});
const verificationResult = await openpgp.verify({
message, // Message object
signature,
verificationKeys: publicKey
});
const { verified, keyID } = verificationResult.signatures[0];
try {
await verified; // throws on invalid signature
console.log('Signed by key id ' + keyID.toHex());
} catch (e) {
throw new Error('Signature could not be verified: ' + e.message);
}
})();
分离式签名的意义在于签名与数据分离传输/存储(如软件发布场景的 .sig 文件)。src/openpgp.js 中 sign({ detached: true }) 走 message.signDetached(...) 分支;验证时通过 openpgp.readSignature 单独解析签名对象,再传给 verify({ signature })。注意 readSignature 与 verify 均在 src/signature.js / src/openpgp.js 中导出。
流式签名与验证 Uint8Array 数据
(async () => {
var readableStream = new ReadableStream({
start(controller) {
controller.enqueue(new Uint8Array([0x01, 0x02, 0x03]));
controller.close();
}
});
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 privateKey = await openpgp.decryptKey({
privateKey: await openpgp.readPrivateKey({ armoredKey: privateKeyArmored }),
passphrase
});
const message = await openpgp.createMessage({ binary: readableStream }); // or createMessage({ text: ReadableStream<String> })
const signatureArmored = await openpgp.sign({
message,
signingKeys: privateKey
});
console.log(signatureArmored); // ReadableStream containing '-----BEGIN PGP MESSAGE ... END PGP MESSAGE-----'
const verificationResult = await openpgp.verify({
message: await openpgp.readMessage({ armoredMessage: signatureArmored }), // parse armored signature
verificationKeys: await openpgp.readKey({ armoredKey: publicKeyArmored })
});
for await (const chunk of verificationResult.data) {}
// Note: you *have* to read `verificationResult.data` in some way or other,
// even if you don't need it, as that is what triggers the
// verification of the data.
try {
await verificationResult.signatures[0].verified; // throws on invalid signature
console.log('Signed by key id ' + verificationResult.signatures[0].keyID.toHex());
} catch (e) {
throw new Error('Signature could not be verified: ' + e.message);
}
})();
流式验证的关键约束:即使不需要明文数据,也必须以某种方式消费 verificationResult.data——因为流的消费才是触发签名校验的驱动力(数据边读边验)。这在 test/general/openpgp.js 的大量流式用例(如 expectSigned=true 的流式加解密、ReadableStream 分块验证)中均有覆盖,可以当作可运行的参考。
文档、测试与开发
文档
完整的 API 文档(JSDoc 生成)发布在官方文档站,仓库根目录的 docs 目录中也可以看到生成后的 HTML 文档(如 Message.html、Key.html、config 模块、enums 模块 等),适合离线查阅各类型与方法的详细签名。
安全审计
截至目前,OpenPGP.js 代码库已经历 Cure53 的两轮完整安全审计,第一轮审计报告已在项目 Wiki 上公开。
安全建议
- 通过常规 Web 托管部署的 JS 加密应用(即"基于主机的安全"模型)为用户提供的安全性低于可安装且可审计静态版本的应用。可安装应用可以打包为 Firefox 或 Chrome 打包应用——它们本质上是签名的 zip 文件,运行时通常强制实施严格的 Content Security Policy(CSP)以抵御 XSS 攻击。
- 强烈建议为磁盘上的私钥设置一个强 passphrase 加以保护。
从源码构建与本地开发
克隆仓库后,执行以下命令即可完成依赖安装、运行全部测试,并在 dist/openpgp.min.js 生成可用于项目的压缩构建:
npm install && npm test
调试浏览器端错误时,运行:
npm run browsertest
仓库 package.json 中与开发相关的常用脚本还包括:
| 命令 | 作用 |
|---|---|
npm run build |
用 rollup 构建各平台产物 |
npm run build-types |
生成 TypeScript 类型定义(dist/types) |
npm test |
通过 mocha 运行 Node 端单元测试(test/unittests.js) |
npm run test-type-definitions |
校验 TypeScript 类型定义 |
npm run test-browser |
用 Playwright 在 chromium/firefox/webkit 上跑浏览器测试 |
npm run test-browser:ci |
无头模式浏览器测试(CI 友好) |
npm run test-browserstack |
基于 BrowserStack 的跨浏览器测试 |
npm run benchmark-time / npm run benchmark-memory-usage |
运行 test/benchmarks 下的性能/内存基准 |
npm run coverage |
生成测试覆盖率 |
npm run lint |
ESLint 全量检查 |
npm run docs |
重新生成 JSDoc 文档到 docs/ |
单元测试的公开 API 用例集中在 test/general/openpgp.js(涵盖 generateKey、revokeKey、decryptKey、encryptKey、decrypt、verify、sign、encrypt、encryptSessionKey、decryptSessionKeys 以及集成测试),是学习各 API 边界条件与流式行为的最佳范本。
开源许可
OpenPGP.js 采用 GNU Lesser General Public License(LGPL)3.0 或更高版本授权,完整许可文本见仓库根目录 LICENSE 文件。参与贡献时,建议先在 Gitter 频道与维护者沟通以避免重复劳动,然后 fork 仓库、提交修改并发起 Pull Request。