or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

asn1.mdasymmetric-cryptography.mdindex.mdlogging.mdmessage-digests.mdnetwork-http.mdpkcs.mdpki.mdrandom.mdsymmetric-encryption.mdtls.mdutilities.mdweb-forms.md

asymmetric-cryptography.mddocs/

0

# Asymmetric Cryptography

1

2

RSA and Ed25519 implementations for key generation, encryption/decryption, and digital signatures. Node-forge provides comprehensive asymmetric cryptography support with both pure JavaScript implementations and native optimizations where available.

3

4

## Capabilities

5

6

### RSA Key Generation

7

8

Generate RSA key pairs for encryption and digital signatures.

9

10

```javascript { .api }

11

/**

12

* Generate an RSA key pair

13

* @param bits - Key size in bits (recommended: 2048, 3072, or 4096)

14

* @param e - Public exponent (default: 0x10001 = 65537)

15

* @param options - Generation options

16

* @param callback - Optional callback for async generation

17

* @returns Key pair object or void if callback provided

18

*/

19

forge.pki.rsa.generateKeyPair(

20

bits: number,

21

e?: number,

22

options?: KeyGenerationOptions,

23

callback?: (err: Error | null, keypair: KeyPair) => void

24

): KeyPair | void;

25

26

interface KeyPair {

27

/** RSA private key for decryption and signing */

28

privateKey: PrivateKey;

29

/** RSA public key for encryption and verification */

30

publicKey: PublicKey;

31

}

32

33

interface KeyGenerationOptions {

34

/** Custom PRNG for key generation */

35

prng?: any;

36

/** Prime generation algorithm (default: 'PRIMEINC') */

37

algorithm?: string;

38

/** Number of workers for async generation */

39

workers?: number;

40

/** Work load size per worker */

41

workLoad?: number;

42

}

43

```

44

45

**Usage Examples:**

46

47

```javascript

48

const forge = require('node-forge');

49

50

// Synchronous key generation

51

const keypair = forge.pki.rsa.generateKeyPair(2048);

52

console.log('Generated key pair:', keypair);

53

54

// Asynchronous key generation (recommended for larger keys)

55

forge.pki.rsa.generateKeyPair(4096, 0x10001, (err, keypair) => {

56

if (err) {

57

console.error('Key generation failed:', err);

58

return;

59

}

60

console.log('Generated key pair async:', keypair);

61

});

62

63

// Custom options

64

const customKeypair = forge.pki.rsa.generateKeyPair(2048, 0x10001, {

65

algorithm: 'PRIMEINC',

66

prng: forge.random.createInstance()

67

});

68

```

69

70

### RSA Public Key Operations

71

72

Encrypt data and verify signatures using RSA public keys.

73

74

```javascript { .api }

75

interface PublicKey {

76

/** RSA modulus (n) */

77

n: any;

78

/** Public exponent (e) */

79

e: any;

80

81

/**

82

* Encrypt data using RSA public key

83

* @param data - Binary data to encrypt

84

* @param scheme - Padding scheme ('RSAES-PKCS1-V1_5', 'RSA-OAEP')

85

* @param schemeOptions - Options for padding scheme

86

* @returns Encrypted data as binary string

87

*/

88

encrypt(data: string, scheme?: string, schemeOptions?: any): string;

89

90

/**

91

* Verify a signature using RSA public key

92

* @param digest - Message digest that was signed

93

* @param signature - Signature to verify as binary string

94

* @param scheme - Signature scheme ('RSASSA-PSS', 'RSASSA-PKCS1-V1_5')

95

* @returns True if signature is valid

96

*/

97

verify(digest: string, signature: string, scheme?: string): boolean;

98

}

99

```

100

101

**Usage Examples:**

102

103

```javascript

104

// Encrypt data with public key

105

const message = 'Hello, World!';

106

const encrypted = keypair.publicKey.encrypt(message, 'RSAES-PKCS1-V1_5');

107

108

// RSA-OAEP encryption with custom options

109

const oaepEncrypted = keypair.publicKey.encrypt(message, 'RSA-OAEP', {

110

md: forge.md.sha256.create(),

111

mgf1: {

112

md: forge.md.sha256.create()

113

}

114

});

115

116

// Verify signature

117

const md = forge.md.sha256.create();

118

md.update(message);

119

const signature = keypair.privateKey.sign(md);

120

const isValid = keypair.publicKey.verify(md.digest().getBytes(), signature);

121

```

122

123

### RSA Private Key Operations

124

125

Decrypt data and create signatures using RSA private keys.

126

127

```javascript { .api }

128

interface PrivateKey {

129

/** RSA modulus (n) */

130

n: any;

131

/** Public exponent (e) */

132

e: any;

133

/** Private exponent (d) */

134

d: any;

135

/** Prime factor p */

136

p?: any;

137

/** Prime factor q */

138

q?: any;

139

/** d mod (p-1) */

140

dP?: any;

141

/** d mod (q-1) */

142

dQ?: any;

143

/** q^(-1) mod p */

144

qInv?: any;

145

146

/**

147

* Decrypt data using RSA private key

148

* @param data - Encrypted data as binary string

149

* @param scheme - Padding scheme ('RSAES-PKCS1-V1_5', 'RSA-OAEP')

150

* @param schemeOptions - Options for padding scheme

151

* @returns Decrypted data as binary string

152

*/

153

decrypt(data: string, scheme?: string, schemeOptions?: any): string;

154

155

/**

156

* Sign a message digest using RSA private key

157

* @param messageDigest - Message digest object to sign

158

* @param scheme - Signature scheme ('RSASSA-PSS', 'RSASSA-PKCS1-V1_5')

159

* @returns Signature as binary string

160

*/

161

sign(messageDigest: MessageDigest, scheme?: string): string;

162

}

163

```

164

165

**Usage Examples:**

166

167

```javascript

168

// Decrypt data with private key

169

const decrypted = keypair.privateKey.decrypt(encrypted, 'RSAES-PKCS1-V1_5');

170

console.log('Decrypted:', decrypted); // "Hello, World!"

171

172

// RSA-OAEP decryption

173

const oaepDecrypted = keypair.privateKey.decrypt(oaepEncrypted, 'RSA-OAEP', {

174

md: forge.md.sha256.create(),

175

mgf1: {

176

md: forge.md.sha256.create()

177

}

178

});

179

180

// Sign message digest

181

const md = forge.md.sha256.create();

182

md.update('Message to sign');

183

const signature = keypair.privateKey.sign(md, 'RSASSA-PKCS1-V1_5');

184

185

// PSS signing

186

const pssSignature = keypair.privateKey.sign(md, 'RSASSA-PSS', {

187

md: forge.md.sha256.create(),

188

mgf: forge.mgf.mgf1.create(forge.md.sha256.create()),

189

saltLength: 32

190

});

191

```

192

193

### RSA Key Creation

194

195

Create RSA keys from existing parameters or convert between formats.

196

197

```javascript { .api }

198

/**

199

* Create RSA public key from modulus and exponent

200

* @param n - Modulus as BigInteger or hex string

201

* @param e - Public exponent as BigInteger or hex string

202

* @returns RSA public key object

203

*/

204

forge.pki.rsa.setPublicKey(n: any, e: any): PublicKey;

205

206

/**

207

* Create RSA private key from parameters

208

* @param n - Modulus

209

* @param e - Public exponent

210

* @param d - Private exponent

211

* @param p - Prime factor p (optional)

212

* @param q - Prime factor q (optional)

213

* @param dP - d mod (p-1) (optional)

214

* @param dQ - d mod (q-1) (optional)

215

* @param qInv - q^(-1) mod p (optional)

216

* @returns RSA private key object

217

*/

218

forge.pki.rsa.setPrivateKey(

219

n: any, e: any, d: any,

220

p?: any, q?: any, dP?: any, dQ?: any, qInv?: any

221

): PrivateKey;

222

```

223

224

**Usage Examples:**

225

226

```javascript

227

// Create public key from hex strings

228

const publicKey = forge.pki.rsa.setPublicKey(

229

'00c4e3f7ba46b13d...', // modulus in hex

230

'010001' // exponent (65537) in hex

231

);

232

233

// Create private key with all parameters

234

const privateKey = forge.pki.rsa.setPrivateKey(

235

n, e, d, p, q, dP, dQ, qInv

236

);

237

```

238

239

### Ed25519 Digital Signatures

240

241

Ed25519 elliptic curve digital signatures for high-performance authentication.

242

243

```javascript { .api }

244

/**

245

* Generate Ed25519 key pair

246

* @param options - Generation options

247

* @returns Ed25519 key pair

248

*/

249

forge.pki.ed25519.generateKeyPair(options?: any): Ed25519KeyPair;

250

251

interface Ed25519KeyPair {

252

/** Ed25519 private key */

253

privateKey: Ed25519PrivateKey;

254

/** Ed25519 public key */

255

publicKey: Ed25519PublicKey;

256

}

257

258

interface Ed25519PrivateKey {

259

/** Sign message with Ed25519 private key */

260

sign(message: string | Uint8Array): Uint8Array;

261

}

262

263

interface Ed25519PublicKey {

264

/** Verify Ed25519 signature */

265

verify(message: string | Uint8Array, signature: Uint8Array): boolean;

266

}

267

```

268

269

**Usage Examples:**

270

271

```javascript

272

// Generate Ed25519 key pair

273

const ed25519Keypair = forge.pki.ed25519.generateKeyPair();

274

275

// Sign message

276

const message = 'Message to sign';

277

const signature = ed25519Keypair.privateKey.sign(message);

278

279

// Verify signature

280

const isValid = ed25519Keypair.publicKey.verify(message, signature);

281

console.log('Ed25519 signature valid:', isValid);

282

```

283

284

### Padding Schemes

285

286

RSA padding schemes for secure encryption and signatures.

287

288

```javascript { .api }

289

// RSA Encryption Schemes

290

'RSAES-PKCS1-V1_5' // PKCS#1 v1.5 padding (legacy)

291

'RSA-OAEP' // Optimal Asymmetric Encryption Padding (recommended)

292

293

// RSA Signature Schemes

294

'RSASSA-PKCS1-V1_5' // PKCS#1 v1.5 signatures (widely compatible)

295

'RSASSA-PSS' // Probabilistic Signature Scheme (recommended)

296

297

interface RSAOAEPOptions {

298

/** Message digest for OAEP (default: SHA-1) */

299

md?: MessageDigest;

300

/** MGF1 options */

301

mgf1?: {

302

md?: MessageDigest;

303

};

304

/** Optional label */

305

label?: string;

306

}

307

308

interface RSAPSSOptions {

309

/** Message digest for PSS */

310

md?: MessageDigest;

311

/** Mask generation function */

312

mgf?: any;

313

/** Salt length in bytes */

314

saltLength?: number;

315

}

316

```

317

318

**Usage Examples:**

319

320

```javascript

321

// RSA-OAEP encryption with SHA-256

322

const oaepOptions = {

323

md: forge.md.sha256.create(),

324

mgf1: {

325

md: forge.md.sha256.create()

326

}

327

};

328

const encrypted = publicKey.encrypt(message, 'RSA-OAEP', oaepOptions);

329

330

// PSS signing with custom parameters

331

const pssOptions = {

332

md: forge.md.sha256.create(),

333

mgf: forge.mgf.mgf1.create(forge.md.sha256.create()),

334

saltLength: 32

335

};

336

const signature = privateKey.sign(messageDigest, 'RSASSA-PSS', pssOptions);

337

```

338

339

### Key Size and Security

340

341

Recommended key sizes and security considerations.

342

343

```javascript { .api }

344

// RSA Key Sizes (bits)

345

RSA_2048_BITS = 2048; // Minimum recommended (equivalent to 112-bit security)

346

RSA_3072_BITS = 3072; // Medium security (equivalent to 128-bit security)

347

RSA_4096_BITS = 4096; // High security (equivalent to 150+ bit security)

348

349

// Public Exponents

350

RSA_EXPONENT_3 = 3; // Small exponent (faster verification)

351

RSA_EXPONENT_65537 = 0x10001; // Common exponent (recommended)

352

```

353

354

**Security Recommendations:**

355

356

```javascript

357

// Recommended secure key generation

358

const secureKeypair = forge.pki.rsa.generateKeyPair(2048, 0x10001);

359

360

// Use RSA-OAEP for encryption (not PKCS#1 v1.5)

361

const encrypted = publicKey.encrypt(data, 'RSA-OAEP');

362

363

// Use PSS for signatures when possible

364

const signature = privateKey.sign(digest, 'RSASSA-PSS');

365

366

// Always use secure hash functions (SHA-256 or better)

367

const md = forge.md.sha256.create();

368

md.update(message);

369

const signature = privateKey.sign(md);

370

```

371

372

### Error Handling

373

374

Common error conditions in asymmetric cryptography operations.

375

376

```javascript

377

try {

378

// Key generation

379

const keypair = forge.pki.rsa.generateKeyPair(2048);

380

381

// Encryption

382

const encrypted = keypair.publicKey.encrypt(message, 'RSA-OAEP');

383

384

// Decryption

385

const decrypted = keypair.privateKey.decrypt(encrypted, 'RSA-OAEP');

386

387

} catch (error) {

388

// Handle errors:

389

// - Key generation failures (insufficient randomness, invalid parameters)

390

// - Encryption failures (message too long, invalid padding)

391

// - Decryption failures (invalid ciphertext, padding errors)

392

// - Signature verification failures (invalid signature, wrong key)

393

// - Unsupported schemes or algorithms

394

console.error('RSA operation failed:', error.message);

395

}

396

```