0
# Low-Level Packet API
1
2
Direct access to OpenPGP packet system for advanced use cases, custom implementations, and protocol-level operations. This API provides fine-grained control over OpenPGP packet creation, manipulation, and processing.
3
4
## Core Packet System
5
6
### Base Packet Class
7
8
```javascript { .api }
9
abstract class BasePacket {
10
/** Packet type identifier */
11
static readonly tag: enums.packet;
12
13
/** Read packet data from bytes */
14
read(bytes: Uint8Array): void;
15
/** Write packet to binary format */
16
write(): Uint8Array;
17
}
18
```
19
20
### Packet List Container
21
22
```javascript { .api }
23
class PacketList<T> extends Array<T> {
24
/** Create packet list from binary data */
25
static fromBinary(
26
bytes: Uint8Array | ReadableStream<Uint8Array>,
27
allowedPackets: Map<enums.packet, any>,
28
config?: Config
29
): PacketList<any>;
30
31
/** Read packets from binary data */
32
read(
33
bytes: Uint8Array | ReadableStream<Uint8Array>,
34
allowedPackets: Map<enums.packet, any>,
35
config?: Config
36
): void;
37
38
/** Write all packets to binary */
39
write(): Uint8Array;
40
41
/** Filter packets by type */
42
filterByTag(...tags: enums.packet[]): PacketList<T>;
43
44
/** Find index of packets by type */
45
indexOfTag(...tags: enums.packet[]): number[];
46
47
/** Find first packet of type */
48
findPacket(tag: enums.packet): T | undefined;
49
}
50
```
51
52
### Unparseable Packet Handling
53
54
```javascript { .api }
55
class UnparseablePacket {
56
/** Packet type tag */
57
tag: enums.packet;
58
/** Write packet data */
59
write(): Uint8Array;
60
}
61
```
62
63
## Key Packets
64
65
### Public Key Packets
66
67
```javascript { .api }
68
abstract class BasePublicKeyPacket extends BasePacket {
69
/** Public key algorithm */
70
algorithm: enums.publicKey;
71
/** Key creation date */
72
created: Date;
73
/** Key version */
74
version: number;
75
/** Public key parameters */
76
publicParams: object;
77
78
/** Get algorithm information */
79
getAlgorithmInfo(): AlgorithmInfo;
80
/** Get key fingerprint */
81
getFingerprint(): string;
82
/** Get fingerprint as bytes */
83
getFingerprintBytes(): Uint8Array | null;
84
/** Check if fingerprint matches another key */
85
hasSameFingerprintAs(other: BasePublicKeyPacket): boolean;
86
/** Get key creation time */
87
getCreationTime(): Date;
88
/** Get key ID */
89
getKeyID(): KeyID;
90
/** Check if key is decrypted */
91
isDecrypted(): boolean;
92
}
93
94
class PublicKeyPacket extends BasePublicKeyPacket {
95
static readonly tag: enums.packet.publicKey;
96
}
97
98
class PublicSubkeyPacket extends BasePublicKeyPacket {
99
static readonly tag: enums.packet.publicSubkey;
100
}
101
```
102
103
### Secret Key Packets
104
105
```javascript { .api }
106
abstract class BaseSecretKeyPacket extends BasePublicKeyPacket {
107
/** Private key parameters (null if encrypted) */
108
privateParams: object | null;
109
110
/** Encrypt private key with passphrase */
111
encrypt(passphrase: string, config?: Config): Promise<void>;
112
/** Decrypt private key with passphrase */
113
decrypt(passphrase: string): Promise<void>;
114
/** Validate private key parameters */
115
validate(): Promise<void>;
116
/** Check if key is a dummy key */
117
isDummy(): boolean;
118
/** Check if secret key material is missing */
119
isMissingSecretKeyMaterial(): boolean;
120
/** Convert to dummy key */
121
makeDummy(config?: Config): void;
122
}
123
124
class SecretKeyPacket extends BaseSecretKeyPacket {
125
static readonly tag: enums.packet.secretKey;
126
}
127
128
class SecretSubkeyPacket extends BaseSecretKeyPacket {
129
static readonly tag: enums.packet.secretSubkey;
130
}
131
```
132
133
**Usage Examples:**
134
135
```javascript
136
import { PublicKeyPacket, SecretKeyPacket, enums } from 'openpgp';
137
138
// Work with key packets directly
139
const keyPacket = new PublicKeyPacket();
140
keyPacket.algorithm = enums.publicKey.rsaEncryptSign;
141
keyPacket.created = new Date();
142
keyPacket.version = 4;
143
144
console.log('Key ID:', keyPacket.getKeyID().toHex());
145
console.log('Fingerprint:', keyPacket.getFingerprint());
146
console.log('Algorithm:', keyPacket.getAlgorithmInfo());
147
148
// Check if secret key is encrypted
149
const secretKey = new SecretKeyPacket();
150
if (!secretKey.isDecrypted()) {
151
await secretKey.decrypt('passphrase');
152
}
153
```
154
155
## Data Packets
156
157
### Literal Data Packet
158
159
```javascript { .api }
160
class LiteralDataPacket extends BasePacket {
161
static readonly tag: enums.packet.literalData;
162
163
/** Get text data */
164
private getText(clone?: boolean): string | ReadableStream<string>;
165
/** Get binary data */
166
private getBytes(clone?: boolean): Uint8Array | ReadableStream<Uint8Array>;
167
/** Set text data */
168
private setText(text: string | ReadableStream<string>, format?: enums.literal): void;
169
/** Set binary data */
170
private setBytes(bytes: Uint8Array | ReadableStream<Uint8Array>, format: enums.literal): void;
171
/** Set filename */
172
private setFilename(filename: string): void;
173
/** Get filename */
174
private getFilename(): string;
175
/** Write packet header */
176
private writeHeader(): Uint8Array;
177
}
178
```
179
180
### Compressed Data Packet
181
182
```javascript { .api }
183
class CompressedDataPacket extends BasePacket {
184
static readonly tag: enums.packet.compressedData;
185
186
/** Compress packet data */
187
private compress(): void;
188
/** Decompress packet data */
189
private decompress(config?: Config): void;
190
}
191
```
192
193
### Encrypted Data Packets
194
195
```javascript { .api }
196
class SymmetricallyEncryptedDataPacket extends BasePacket {
197
static readonly tag: enums.packet.symmetricallyEncryptedData;
198
199
/** Decrypt data */
200
private decrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
201
/** Encrypt data */
202
private encrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
203
}
204
205
class SymEncryptedIntegrityProtectedDataPacket extends BasePacket {
206
static readonly tag: enums.packet.symEncryptedIntegrityProtectedData;
207
}
208
209
class AEADEncryptedDataPacket extends BasePacket {
210
static readonly tag: enums.packet.aeadEncryptedData;
211
212
/** Decrypt AEAD data */
213
private decrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
214
/** Encrypt AEAD data */
215
private encrypt(sessionKeyAlgorithm: enums.symmetric, sessionKey: Uint8Array, config?: Config): void;
216
/** Generic crypt operation */
217
private crypt(fn: Function, sessionKey: Uint8Array, data: Uint8Array | ReadableStream<Uint8Array>): Uint8Array | ReadableStream<Uint8Array>;
218
}
219
```
220
221
## Session Key Packets
222
223
### Public Key Encrypted Session Key
224
225
```javascript { .api }
226
class PublicKeyEncryptedSessionKeyPacket extends BasePacket {
227
static readonly tag: enums.packet.publicKeyEncryptedSessionKey;
228
229
/** Decrypt session key with private key */
230
private decrypt(keyPacket: SecretKeyPacket): void;
231
/** Encrypt session key with public key */
232
private encrypt(keyPacket: PublicKeyPacket): void;
233
}
234
```
235
236
### Symmetric Encrypted Session Key
237
238
```javascript { .api }
239
class SymEncryptedSessionKeyPacket extends BasePacket {
240
static readonly tag: enums.packet.symEncryptedSessionKey;
241
242
/** Decrypt session key with password */
243
private decrypt(passphrase: string): Promise<void>;
244
/** Encrypt session key with password */
245
private encrypt(passphrase: string, config?: Config): Promise<void>;
246
}
247
```
248
249
## Signature Packets
250
251
### Signature Packet
252
253
```javascript { .api }
254
class SignaturePacket extends BasePacket {
255
static readonly tag: enums.packet.signature;
256
257
/** Signature version */
258
version: number;
259
/** Signature type */
260
signatureType: enums.signature | null;
261
/** Hash algorithm used */
262
hashAlgorithm: enums.hash | null;
263
/** Public key algorithm used */
264
publicKeyAlgorithm: enums.publicKey | null;
265
/** Signature data */
266
signatureData: Uint8Array | null;
267
/** Unhashed subpackets */
268
unhashedSubpackets: RawSubpacket[];
269
/** Unknown subpackets */
270
unknownSubpackets: RawSubpacket[];
271
/** Signed hash value */
272
signedHashValue: Uint8Array | null;
273
/** Signature creation time */
274
created: Date | null;
275
/** Signature expiration time in seconds */
276
signatureExpirationTime: number | null;
277
/** Whether signature never expires */
278
signatureNeverExpires: boolean;
279
/** Whether signature is exportable */
280
exportable: boolean | null;
281
/** Trust level */
282
trustLevel: number | null;
283
/** Trust amount */
284
trustAmount: number | null;
285
/** Regular expression for trust */
286
regularExpression: number | null;
287
/** Whether signature is revocable */
288
revocable: boolean | null;
289
/** Key expiration time in seconds */
290
keyExpirationTime: number | null;
291
/** Whether key never expires */
292
keyNeverExpires: boolean | null;
293
/** Preferred symmetric algorithms */
294
preferredSymmetricAlgorithms: enums.symmetric[] | null;
295
/** Revocation key class */
296
revocationKeyClass: number | null;
297
/** Revocation key algorithm */
298
revocationKeyAlgorithm: enums.publicKey | null;
299
/** Revocation key fingerprint */
300
revocationKeyFingerprint: Uint8Array | null;
301
/** Issuer key ID */
302
issuerKeyID: KeyID;
303
/** Notation data */
304
notation: { [name: string]: string } | null;
305
/** Preferred hash algorithms */
306
preferredHashAlgorithms: enums.hash[] | null;
307
/** Preferred compression algorithms */
308
preferredCompressionAlgorithms: enums.compression[] | null;
309
/** Key server preferences */
310
keyServerPreferences: number[] | null;
311
/** Preferred key server */
312
preferredKeyServer: string | null;
313
/** Whether this is primary user ID */
314
isPrimaryUserID: boolean | null;
315
/** Policy URI */
316
policyURI: string | null;
317
/** Key flags */
318
keyFlags: Uint8Array | null;
319
/** Signer's user ID */
320
signersUserID: string | null;
321
/** Reason for revocation flag */
322
reasonForRevocationFlag: enums.reasonForRevocation | null;
323
/** Reason for revocation string */
324
reasonForRevocationString: string | null;
325
/** Feature flags */
326
features: Uint8Array | null;
327
/** Signature target public key algorithm */
328
signatureTargetPublicKeyAlgorithm: enums.publicKey | null;
329
/** Signature target hash algorithm */
330
signatureTargetHashAlgorithm: enums.hash | null;
331
/** Signature target hash */
332
signatureTargetHash: string | null;
333
/** Embedded signature */
334
embeddedSignature: SignaturePacket | null;
335
/** Issuer key version */
336
issuerKeyVersion: number | null;
337
/** Issuer fingerprint */
338
issuerFingerprint: Uint8Array | null;
339
/** Preferred AEAD algorithms */
340
preferredAEADAlgorithms: enums.aead[] | null;
341
/** Whether signature is revoked */
342
revoked: boolean | null;
343
/** Raw notation data */
344
rawNotations: RawNotation[];
345
346
/** Sign data with key */
347
sign(key: SecretKeyPacket | SecretSubkeyPacket, data: Uint8Array, date?: Date, detached?: boolean): Promise<void>;
348
/** Verify signature */
349
verify(key: BasePublicKeyPacket, signatureType: enums.signature, data: Uint8Array | object, date?: Date, detached?: boolean, config?: Config): Promise<void>;
350
/** Check if signature is expired */
351
isExpired(date?: Date): boolean;
352
/** Get signature expiration time */
353
getExpirationTime(): Date | typeof Infinity;
354
}
355
```
356
357
### One-Pass Signature Packet
358
359
```javascript { .api }
360
class OnePassSignaturePacket extends BasePacket {
361
static readonly tag: enums.packet.onePassSignature;
362
363
/** Corresponding signature packet */
364
correspondingSig?: Promise<SignaturePacket>;
365
/** Verify method (same as SignaturePacket.verify) */
366
private verify: SignaturePacket['verify'];
367
}
368
```
369
370
## User Packets
371
372
### User ID Packet
373
374
```javascript { .api }
375
class UserIDPacket extends BasePacket {
376
static readonly tag: enums.packet.userID;
377
378
/** User's name */
379
readonly name: string;
380
/** User's comment */
381
readonly comment: string;
382
/** User's email */
383
readonly email: string;
384
/** Complete user ID string */
385
readonly userID: string;
386
387
/** Create from UserID object */
388
static fromObject(userID: UserID): UserIDPacket;
389
}
390
```
391
392
### User Attribute Packet
393
394
```javascript { .api }
395
class UserAttributePacket extends BasePacket {
396
static readonly tag: enums.packet.userAttribute;
397
398
/** Check equality with another user attribute */
399
private equals(packet: UserAttributePacket): boolean;
400
}
401
```
402
403
## Utility Packets
404
405
### Marker Packet
406
407
```javascript { .api }
408
class MarkerPacket extends BasePacket {
409
static readonly tag: enums.packet.marker;
410
}
411
```
412
413
### Trust Packet
414
415
```javascript { .api }
416
class TrustPacket extends BasePacket {
417
static readonly tag: enums.packet.trust;
418
}
419
```
420
421
## Advanced Packet Operations
422
423
### Custom Packet Creation
424
425
```javascript
426
import { PacketList, SignaturePacket, enums } from 'openpgp';
427
428
// Create custom signature packet
429
const sigPacket = new SignaturePacket();
430
sigPacket.version = 4;
431
sigPacket.signatureType = enums.signature.binary;
432
sigPacket.hashAlgorithm = enums.hash.sha256;
433
sigPacket.publicKeyAlgorithm = enums.publicKey.rsaEncryptSign;
434
sigPacket.created = new Date();
435
436
// Create packet list
437
const packetList = new PacketList();
438
packetList.push(sigPacket);
439
440
// Write to binary
441
const binaryData = packetList.write();
442
```
443
444
### Packet Parsing and Analysis
445
446
```javascript
447
import { PacketList, enums } from 'openpgp';
448
449
// Parse binary OpenPGP data
450
const allowedPackets = new Map([
451
[enums.packet.signature, SignaturePacket],
452
[enums.packet.publicKey, PublicKeyPacket],
453
[enums.packet.userID, UserIDPacket]
454
]);
455
456
const packets = PacketList.fromBinary(binaryData, allowedPackets);
457
458
// Analyze packet structure
459
console.log('Total packets:', packets.length);
460
461
const signatures = packets.filterByTag(enums.packet.signature);
462
console.log('Signature packets:', signatures.length);
463
464
const publicKeys = packets.filterByTag(enums.packet.publicKey);
465
console.log('Public key packets:', publicKeys.length);
466
467
// Find specific packet types
468
const userIDPacket = packets.findPacket(enums.packet.userID);
469
if (userIDPacket) {
470
console.log('User ID:', userIDPacket.userID);
471
}
472
```
473
474
### Raw Packet Data Access
475
476
```javascript
477
import { readMessage } from 'openpgp';
478
479
// Access raw packet data from message
480
const message = await readMessage({ armoredMessage: messageData });
481
482
// Iterate through all packets
483
for (const packet of message.packets) {
484
console.log('Packet type:', packet.constructor.tag);
485
console.log('Packet data:', packet.write());
486
487
if (packet instanceof SignaturePacket) {
488
console.log('Signature created:', packet.created);
489
console.log('Hash algorithm:', packet.hashAlgorithm);
490
}
491
}
492
```
493
494
## Type Definitions
495
496
```javascript { .api }
497
interface RawSubpacket {
498
/** Subpacket type */
499
type: number;
500
/** Whether subpacket is critical */
501
critical: boolean;
502
/** Subpacket body data */
503
body: Uint8Array;
504
}
505
506
interface RawNotation {
507
/** Notation name */
508
name: string;
509
/** Notation value */
510
value: Uint8Array;
511
/** Whether notation is human readable */
512
humanReadable: boolean;
513
/** Whether notation is critical */
514
critical: boolean;
515
}
516
517
type AnyPacket = BasePacket | UnparseablePacket;
518
type AnySecretKeyPacket = SecretKeyPacket | SecretSubkeyPacket;
519
type AnyKeyPacket = BasePublicKeyPacket;
520
```