or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

encryption-decryption.mdindex.mdkey-management.mdpacket-api.mdsession-keys.mdsigning-verification.md

encryption-decryption.mddocs/

0

# Encryption and Decryption

1

2

Message encryption and decryption using public keys, passwords, or session keys. Supports both streaming and non-streaming operations with integrity protection, compression, and digital signatures.

3

4

## Capabilities

5

6

### Message Creation

7

8

Create message objects from text or binary data before encryption.

9

10

```javascript { .api }

11

/**

12

* Create a message from text data

13

* @param options - Message creation options

14

* @returns Promise resolving to Message object

15

*/

16

function createMessage(options: {

17

text: string | ReadableStream<string>,

18

filename?: string,

19

date?: Date,

20

format?: enums.literalFormatNames

21

}): Promise<Message>;

22

23

/**

24

* Create a message from binary data

25

* @param options - Message creation options

26

* @returns Promise resolving to Message object

27

*/

28

function createMessage(options: {

29

binary: Uint8Array | ReadableStream<Uint8Array>,

30

filename?: string,

31

date?: Date,

32

format?: enums.literalFormatNames

33

}): Promise<Message>;

34

35

/**

36

* Read a message from armored data

37

* @param options - Message reading options

38

* @returns Promise resolving to Message object

39

*/

40

function readMessage(options: {

41

armoredMessage: string | ReadableStream<string>,

42

config?: PartialConfig

43

}): Promise<Message>;

44

45

/**

46

* Read a message from binary data

47

* @param options - Message reading options

48

* @returns Promise resolving to Message object

49

*/

50

function readMessage(options: {

51

binaryMessage: Uint8Array | ReadableStream<Uint8Array>,

52

config?: PartialConfig

53

}): Promise<Message>;

54

```

55

56

### Message Encryption

57

58

Encrypt messages using public keys, passwords, or both with optional signing.

59

60

```javascript { .api }

61

/**

62

* Encrypt a message with public keys, passwords, or both

63

* @param options - Encryption options

64

* @returns Promise resolving to encrypted message

65

*/

66

function encrypt(options: EncryptOptions): Promise<string | Uint8Array>;

67

68

interface EncryptOptions {

69

/** Message to be encrypted */

70

message: Message;

71

/** Public keys for encryption */

72

encryptionKeys?: PublicKey | PublicKey[];

73

/** Private keys for signing */

74

signingKeys?: PrivateKey | PrivateKey[];

75

/** Passwords for encryption */

76

passwords?: string | string[];

77

/** Session key for encryption */

78

sessionKey?: SessionKey;

79

/** Output format */

80

format?: 'armored' | 'binary' | 'object';

81

/** Detached signature to add */

82

signature?: Signature;

83

/** Use wildcard key ID */

84

wildcard?: boolean;

85

/** Key IDs for signing */

86

signingKeyIDs?: KeyID | KeyID[];

87

/** Key IDs for encryption */

88

encryptionKeyIDs?: KeyID | KeyID[];

89

/** Override signature date */

90

date?: Date;

91

/** User IDs for signing */

92

signingUserIDs?: UserID | UserID[];

93

/** User IDs for encryption */

94

encryptionUserIDs?: UserID | UserID[];

95

/** Signature notations */

96

signatureNotations?: RawNotation | RawNotation[];

97

/** Custom configuration */

98

config?: PartialConfig;

99

}

100

```

101

102

**Usage Examples:**

103

104

```javascript

105

import { createMessage, encrypt, generateKey } from 'openpgp';

106

107

// Basic encryption with public key

108

const message = await createMessage({ text: 'Hello, World!' });

109

const encrypted = await encrypt({

110

message,

111

encryptionKeys: publicKey,

112

format: 'armored'

113

});

114

115

// Encrypt and sign

116

const encryptedAndSigned = await encrypt({

117

message,

118

encryptionKeys: recipientPublicKey,

119

signingKeys: senderPrivateKey,

120

format: 'armored'

121

});

122

123

// Password-based encryption

124

const passwordEncrypted = await encrypt({

125

message,

126

passwords: ['super-secret-password'],

127

format: 'armored'

128

});

129

130

// Multiple recipients

131

const multiRecipient = await encrypt({

132

message,

133

encryptionKeys: [publicKey1, publicKey2, publicKey3],

134

signingKeys: senderPrivateKey

135

});

136

```

137

138

### Message Decryption

139

140

Decrypt messages with private keys, session keys, or passwords with signature verification.

141

142

```javascript { .api }

143

/**

144

* Decrypt a message and verify signatures

145

* @param options - Decryption options

146

* @returns Promise resolving to decrypted data and verification results

147

*/

148

function decrypt(options: DecryptOptions): Promise<DecryptMessageResult>;

149

150

interface DecryptOptions {

151

/** Encrypted message to decrypt */

152

message: Message;

153

/** Private keys for decryption */

154

decryptionKeys?: PrivateKey | PrivateKey[];

155

/** Passwords for decryption */

156

passwords?: string | string[];

157

/** Session keys for decryption */

158

sessionKeys?: SessionKey | SessionKey[];

159

/** Public keys for signature verification */

160

verificationKeys?: PublicKey | PublicKey[];

161

/** Require signed message */

162

expectSigned?: boolean;

163

/** Output format */

164

format?: 'utf8' | 'binary';

165

/** Detached signature for verification */

166

signature?: Signature;

167

/** Date for verification */

168

date?: Date;

169

/** Custom configuration */

170

config?: PartialConfig;

171

}

172

173

interface DecryptMessageResult {

174

/** Decrypted data */

175

data: string | Uint8Array | ReadableStream<string> | ReadableStream<Uint8Array>;

176

/** Signature verification results */

177

signatures: VerificationResult[];

178

/** Original filename */

179

filename: string;

180

}

181

182

interface VerificationResult {

183

/** Key ID that created the signature */

184

keyID: KeyID;

185

/** Promise that resolves if signature is valid */

186

verified: Promise<true>;

187

/** Promise that resolves to the signature object */

188

signature: Promise<Signature>;

189

}

190

```

191

192

**Usage Examples:**

193

194

```javascript

195

import { readMessage, decrypt } from 'openpgp';

196

197

// Basic decryption

198

const message = await readMessage({ armoredMessage: encryptedData });

199

const decrypted = await decrypt({

200

message,

201

decryptionKeys: privateKey,

202

verificationKeys: senderPublicKey

203

});

204

205

console.log('Decrypted message:', decrypted.data);

206

console.log('Filename:', decrypted.filename);

207

208

// Verify signatures

209

for (const result of decrypted.signatures) {

210

try {

211

await result.verified;

212

console.log('Valid signature from:', result.keyID.toHex());

213

} catch (error) {

214

console.log('Invalid signature from:', result.keyID.toHex());

215

}

216

}

217

218

// Password-based decryption

219

const passwordDecrypted = await decrypt({

220

message,

221

passwords: ['super-secret-password']

222

});

223

224

// Require signed message

225

const decryptedSigned = await decrypt({

226

message,

227

decryptionKeys: privateKey,

228

verificationKeys: senderPublicKey,

229

expectSigned: true // Will throw if not signed

230

});

231

```

232

233

### Streaming Operations

234

235

OpenPGP.js supports streaming for large data processing.

236

237

```javascript

238

import { createMessage, encrypt, decrypt } from 'openpgp';

239

240

// Stream encryption

241

const stream = new ReadableStream({

242

start(controller) {

243

controller.enqueue('Large data chunk 1\n');

244

controller.enqueue('Large data chunk 2\n');

245

controller.close();

246

}

247

});

248

249

const message = await createMessage({ text: stream });

250

const encryptedStream = await encrypt({

251

message,

252

encryptionKeys: publicKey,

253

format: 'armored'

254

});

255

256

// encryptedStream is a ReadableStream<string>

257

const reader = encryptedStream.getReader();

258

while (true) {

259

const { done, value } = await reader.read();

260

if (done) break;

261

console.log('Encrypted chunk:', value);

262

}

263

```

264

265

## Message Class

266

267

```javascript { .api }

268

class Message {

269

/** Packet list containing message data */

270

readonly packets: PacketList<any>;

271

272

constructor(packetlist: PacketList<any>);

273

274

/** Get binary representation */

275

write(): Uint8Array | ReadableStream<Uint8Array>;

276

/** Get ASCII armored representation */

277

armor(config?: Config): string;

278

/** Decrypt the message */

279

decrypt(

280

decryptionKeys?: PrivateKey[],

281

passwords?: string[],

282

sessionKeys?: SessionKey[],

283

date?: Date,

284

config?: Config

285

): Promise<Message>;

286

/** Encrypt the message */

287

encrypt(

288

encryptionKeys?: PublicKey[],

289

passwords?: string[],

290

sessionKeys?: SessionKey[],

291

wildcard?: boolean,

292

encryptionKeyIDs?: KeyID[],

293

date?: Date,

294

userIDs?: UserID[],

295

config?: Config

296

): Promise<Message>;

297

/** Get encryption key IDs */

298

getEncryptionKeyIDs(): KeyID[];

299

/** Get literal data */

300

getLiteralData(): Uint8Array | ReadableStream<Uint8Array> | null;

301

/** Get signing key IDs */

302

getSigningKeyIDs(): KeyID[];

303

/** Get text data */

304

getText(): string | ReadableStream<string> | null;

305

/** Get filename */

306

getFilename(): string | null;

307

/** Sign the message */

308

sign(

309

signingKeys: PrivateKey[],

310

signature?: Signature,

311

signingKeyIDs?: KeyID[],

312

date?: Date,

313

userIDs?: UserID[],

314

notations?: RawNotation[],

315

config?: Config

316

): Promise<Message>;

317

/** Verify message signatures */

318

verify(verificationKeys: PublicKey[], date?: Date, config?: Config): Promise<VerificationResult[]>;

319

/** Append detached signature */

320

appendSignature(detachedSignature: string | Uint8Array, config?: Config): Promise<void>;

321

}

322

```

323

324

## Supporting Types

325

326

```javascript { .api }

327

interface SessionKey {

328

/** Session key data */

329

data: Uint8Array;

330

/** Symmetric algorithm name */

331

algorithm: string;

332

/** AEAD algorithm name */

333

aeadAlgorithm?: string;

334

}

335

336

interface RawNotation {

337

/** Notation name */

338

name: string;

339

/** Notation value */

340

value: Uint8Array;

341

/** Whether notation is human readable */

342

humanReadable: boolean;

343

/** Whether notation is critical */

344

critical: boolean;

345

}

346

347

type MaybeStream<T> = T | ReadableStream<T>;

348

```