jks 0.3.3

Java KeyStore (JKS) and PKCS12 encoder/decoder for Rust
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
# jks

[![Rust](https://img.shields.io/badge/rust-1.70%2B-orange.svg)](https://www.rust-lang.org)
[![License: MIT](https://img.shields.io/badge/License-MIT-blue.svg)](LICENSE)
[![Crates.io](https://img.shields.io/crates/v/jks)](https://crates.io/crates/jks)

Java KeyStore (JKS) and PKCS12 encoder/decoder for Rust. Supports WebAssembly (WASM).

## About

`jks` is a pure Rust library for reading and writing Java KeyStore (JKS) and PKCS12 files. It provides compatibility with Java's `keytool` and Android keystores, and can be used to:

- Read JKS files (keystores, truststores)
- Read PKCS12 files (Android `.keystore`, `.p12`, `.pfx`)
- Create new JKS files with private keys and certificates
- Extract private keys and certificates from keystores
- Convert keystores to PEM format and vice versa

**Note:** Private keys are assumed to be PKCS#8 encoded.

## Features

- **Read JKS files** - Load existing Java keystores
-**Read PKCS12 files** - Load Android keystores, `.p12`, `.pfx` files (pure Rust, no OpenSSL)
-**Auto-detect format** - Automatically detects JKS vs PKCS12 format
-**Write JKS files** - Create new keystores compatible with Java
-**Password-based encryption** - Private keys encrypted using password (XOR + SHA-1)
-**Private Key entries** - Support for private keys with certificate chains
-**Trusted Certificate entries** - Support for trusted certificates
-**Case-insensitive aliases** - Alias matching is case-insensitive by default
-**Ordered aliases** - Optional alphabetical sorting of aliases
-**Custom password validation** - Configurable minimum password length
-**WASM Support** - Full JKS and PKCS12 support in WebAssembly

## Installation

Add to your `Cargo.toml`:

```toml
[dependencies]
jks = "0.3.3"
```

### Features

- **default** - Includes `rand` and `pkcs12` (PKCS12 support)
- **rand** - Enable random number generation for JKS encryption
- **pkcs12** - Enable PKCS12 support (for Android keystores) - uses pure Rust `p12-keystore`
- **wasm** - Build for WebAssembly (enables `getrandom/js` for WASM environments)

To disable PKCS12 support (reduce dependencies):

```toml
[dependencies]
jks = { version = "0.3", default-features = false, features = ["rand"] }
```

For WASM builds:

```toml
[dependencies]
jks = { version = "0.3", default-features = false, features = ["pkcs12"] }
getrandom = { version = "0.3", features = ["wasm_js"] }
```

## Quick Start

### Reading a Keystore

```rust
use jks::KeyStore;
use std::fs::File;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Open and read keystore
    let mut file = File::open("keystore.jks")?;
    let mut ks = KeyStore::new();
    ks.load(&mut file, b"password")?;

    // List all aliases
    for alias in ks.aliases() {
        println!("{}", alias);
    }

    Ok(())
}
```

### Creating a New Keystore

```rust
use jks::{KeyStore, PrivateKeyEntry, Certificate};
use std::fs::File;
use std::time::SystemTime;

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let mut ks = KeyStore::new();

    // Create a private key entry
    let entry = PrivateKeyEntry {
        creation_time: SystemTime::now(),
        private_key: /* PKCS#8 private key bytes */ vec![],
        certificate_chain: vec![
            Certificate {
                cert_type: "X509".to_string(),
                content: /* DER encoded certificate */ vec![],
            }
        ],
    };

    // Add to keystore (private key will be encrypted)
    ks.set_private_key_entry("myalias", entry, b"password")?;

    // Save to file
    let mut file = File::create("keystore.jks")?;
    ks.store(&mut file, b"password")?;

    Ok(())
}
```

## API Reference

### `KeyStore`

Main struct for working with Java keystores.

#### Creating a Keystore

```rust
use jks::KeyStore;

// Default options
let ks = KeyStore::new();

// With custom options
let ks = KeyStore::with_options(KeyStoreOptions {
    ordered_aliases: true,
    case_exact_aliases: false,
    min_password_len: 6,
    ..Default::default()
});
```

#### Loading & Saving

```rust
use jks::KeyStore;
use std::fs::File;

let mut ks = KeyStore::new();

// Load from file (JKS format)
let mut file = File::open("keystore.jks")?;
ks.load(&mut file, b"password")?;

// Auto-detect format (JKS or PKCS12)
let mut file = File::open("keystore.jks")?;
ks.load_auto_detect(&mut file, b"password")?;

// Load PKCS12 file (Android .keystore, .p12, .pfx)
let mut file = File::open("android.keystore")?;
ks.load_pkcs12(&mut file, b"password")?;

// Save to file
let mut file = File::create("keystore.jks")?;
ks.store(&mut file, b"password")?;
```

#### PKCS12 Support (Android Keystores)

```rust
use jks::KeyStore;
use std::fs::File;

let mut ks = KeyStore::new();

// Load Android keystore (PKCS12 format)
let mut file = File::open("my-release-key.keystore")?;
ks.load_pkcs12(&mut file, b"password")?;

// Or use auto-detect (works for both JKS and PKCS12)
let mut file = File::open("my-release-key.keystore")?;
ks.load_auto_detect(&mut file, b"password")?;

// Get private key entry (already decrypted for PKCS12)
let alias = ks.aliases().first().unwrap().clone();
if ks.is_private_key_entry(&alias) {
    // For PKCS12, use get_raw_private_key_entry() since keys are already decrypted
    let entry = ks.get_raw_private_key_entry(&alias)?;

    // Access certificate chain
    for cert in &entry.certificate_chain {
        println!("Certificate: {} bytes", cert.content.len());
    }
}
```

**Note:** PKCS12 files (like Android keystores) are supported via the pure Rust `p12-keystore` library. The private keys from PKCS12 are already decrypted, so use `get_raw_private_key_entry()` instead of `get_private_key_entry()`.

#### Private Key Entries

```rust
use jks::{KeyStore, PrivateKeyEntry, Certificate};

let mut ks = KeyStore::new();

// Add a private key entry
let entry = PrivateKeyEntry {
    creation_time: SystemTime::now(),
    private_key: private_key_bytes, // PKCS#8 encoded
    certificate_chain: vec![certificate],
};

// Private key will be encrypted before storing
ks.set_private_key_entry("mykey", entry, b"password")?;

// Retrieve and decrypt
let entry = ks.get_private_key_entry("mykey", b"password")?;

// Get certificate chain only
let chain = ks.get_private_key_entry_certificate_chain("mykey")?;

// Check if entry exists
if ks.is_private_key_entry("mykey") {
    println!("Found private key entry");
}
```

#### Trusted Certificate Entries

```rust
use jks::{KeyStore, TrustedCertificateEntry, Certificate};

let mut ks = KeyStore::new();

// Add a trusted certificate
let entry = TrustedCertificateEntry {
    creation_time: SystemTime::now(),
    certificate: Certificate {
        cert_type: "X509".to_string(),
        content: cert_bytes,
    },
};

ks.set_trusted_certificate_entry("mycert", entry)?;

// Retrieve
let entry = ks.get_trusted_certificate_entry("mycert")?;

// Check if entry exists
if ks.is_trusted_certificate_entry("mycert") {
    println!("Found trusted certificate");
}
```

#### Working with Aliases

```rust
use jks::KeyStore;

let ks = KeyStore::new();

// Get all aliases
let aliases = ks.aliases();

// Check number of entries
let count = ks.len();
let empty = ks.is_empty();

// Delete an entry
ks.delete_entry("oldalias");

// Case sensitivity
let ks = KeyStore::with_options(KeyStoreOptions {
    case_exact_aliases: true,  // "MyKey" != "mykey"
    ..Default::default()
});
```

### Types

#### `PrivateKeyEntry`

Represents a private key with its certificate chain.

```rust
pub struct PrivateKeyEntry {
    /// When this entry was created
    pub creation_time: SystemTime,

    /// Private key in PKCS#8 format (encrypted when stored)
    pub private_key: Vec<u8>,

    /// Certificate chain (end-entity first, then intermediates)
    pub certificate_chain: Vec<Certificate>,
}
```

#### `TrustedCertificateEntry`

Represents a trusted certificate without a private key.

```rust
pub struct TrustedCertificateEntry {
    /// When this entry was created
    pub creation_time: SystemTime,

    /// The trusted certificate
    pub certificate: Certificate,
}
```

#### `Certificate`

Represents a single certificate.

```rust
pub struct Certificate {
    /// Certificate type (e.g., "X509")
    pub cert_type: String,

    /// Raw DER-encoded certificate content
    pub content: Vec<u8>,
}
```

#### `KeyStoreOptions`

Configuration options for keystore behavior.

```rust
pub struct KeyStoreOptions {
    /// Order aliases alphabetically when iterating
    pub ordered_aliases: bool,

    /// Preserve original case of aliases (default: case-insensitive)
    pub case_exact_aliases: bool,

    /// Minimum password length
    pub min_password_len: usize,

    /// Custom random number generator for salt generation
    pub rng: Box<dyn RandomReader>,

    /// Custom password bytes transformation
    pub password_bytes: fn(&[u8]) -> Vec<u8>,
}
```

### Error Handling

All operations return `Result<T, KeyStoreError>`:

```rust
pub enum KeyStoreError {
    EntryNotFound,
    WrongEntryType,
    EmptyPrivateKey,
    EmptyCertificateType,
    EmptyCertificateContent,
    ShortPassword,
    InvalidMagic,
    InvalidDigest,
    UnknownVersion(u32),
    UnknownEntryTag(u32),
    UnsupportedAlgorithm,
    ExtraDataInEncryptedKey,
    InvalidEntry,
    Io(std::io::Error),
    Asn1(String),
    Other(String),
}
```

## Examples

The library includes several examples demonstrating common usage:

### 1. PEM to JKS

Convert PEM files to a JKS keystore:

```bash
cargo run --example pem -- --help
```

### 2. Read Keystore

Read and display entries from a keystore:

```bash
cargo run --example keypass -- examples/data/agus_key.jks password
```

### 3. Read Truststore

Read Java's cacerts truststore:

```bash
cargo run --example truststore -- /path/to/cacerts changeit
```

### 4. JKS to PEM

Convert a JKS keystore to separate PEM files:

```bash
# Convert to separate PEM files
cargo run --example jks_to_pem -- keystore.jks password myalias output

# Output files:
#   output_private_key.pem     - Private key (PKCS#8)
#   output_certificate.pem     - End-entity certificate
#   output_chain.pem           - Full certificate chain
```

### 5. JKS to PEM Bundle

Convert a JKS keystore to a single combined PEM bundle:

```bash
# Convert to single bundle file
cargo run --example jks_to_pem_bundle -- keystore.jks password myalias bundle.pem

# Bundle contains:
#   -----BEGIN PRIVATE KEY-----
#   -----END PRIVATE KEY-----
#   -----BEGIN CERTIFICATE-----
#   -----END CERTIFICATE-----
```

### 6. Compare Keystores

Test deterministic keystore output:

```bash
cargo run --example compare
```

## Password Security

**Important:** Always zero out passwords after use:

```rust
let mut password = b"mysecret".to_vec();

// Use password...
ks.store(&mut file, &password)?;

// Zero out sensitive data
jks::zeroing(&mut password);
```

## JKS Format Details

This library implements the JKS (Java KeyStore) format:

| Component | Value |
|-----------|-------|
| Magic Number | `0xfeedfeed` |
| Version | 2 (latest) |
| Digest Algorithm | SHA-1 |
| Key Encryption | Password-based XOR + SHA-1 |
| Salt Length | 20 bytes |
| Byte Order | Big-endian |

### Private Key Encryption

Private keys are encrypted using:

1. Generate 20-byte random salt
2. Derive encryption key using SHA-1(password + salt) iterated
3. XOR private key with derived key
4. Append SHA-1 digest for verification

### Entry Tags

| Tag | Type | Description |
|-----|------|-------------|
| 1 | Private Key | Private key with certificate chain |
| 2 | Trusted Certificate | Trusted certificate without private key |

## Testing

Run the test suite:

```bash
# Run all tests
cargo test

# Run library tests
cargo test --lib

# Run specific example
cargo run --example pem
```

## WebAssembly (WASM) Support

This library fully supports WebAssembly for use in browser environments or Node.js. Both JKS and PKCS12 formats are supported in WASM.

### Building for WASM

Using wasm-pack (recommended):

```bash
# Install wasm-pack
cargo install wasm-pack

# Build for Node.js
wasm-pack build --target nodejs

# Build for web browsers
wasm-pack build --target web
```

Or using cargo directly:

```bash
# Build the library for WASM
cargo build --target wasm32-unknown-unknown --lib --no-default-features --features pkcs12
```

### Using in Your Project

Add to your `Cargo.toml`:

```toml
[dependencies]
jks = { version = "0.3", default-features = false, features = ["pkcs12"] }
wasm-bindgen = "0.2"
getrandom = { version = "0.3", features = ["wasm_js"] }
```

### Providing a Custom RNG for WASM

For JKS write operations, you need to provide a custom RNG since the default RNG isn't available in WASM:

```rust
use jks::{KeyStore, KeyStoreOptions, common::RandomReader};
use std::io::{self, Write};

struct BrowserRng;

impl RandomReader for BrowserRng {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<()> {
        // Use browser's crypto API or provide your own implementation
        // In browsers: window.crypto.getRandomValues()
        // In Node.js: require('crypto').randomFillSync()
        Ok(())
    }
}

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let options = KeyStoreOptions {
        rng: Box::new(BrowserRng),
        ..Default::default()
    };
    let mut ks = KeyStore::with_options(options);
    // ...
}
```

### WASM Runtime Testing

The library has been verified working in WebAssembly runtime environment:

```bash
# Build the WASM test module
cd tests/wasm
wasm-pack build --target nodejs

# Run tests with Node.js
node test.js
```

**Test Results (verified):**
- ✅ Basic operations - PASSED
- ✅ Load JKS file - PASSED
- ✅ Load PKCS12 (.keystore) file - PASSED
- ✅ Get PKCS12 private key info - PASSED
- ✅ Auto-detect JKS format - PASSED
- ✅ Auto-detect PKCS12 format - PASSED
- ✅ Get JKS private key info (with decryption) - PASSED

**All 7 tests PASSED** for both JKS and PKCS12 in WASM!

### Compatibility

- ✅ Java KeyStore (JKS) format
- ✅ PKCS12 format (.p12, .pfx, .keystore)
- ✅ Java `keytool` generated keystores
- ✅ Android keystores
- ✅ Java cacerts truststore
- ✅ OpenSSL generated certificates
- ✅ PKCS#8 private keys
- ✅ WebAssembly (WASM)

## Requirements

- Rust 1.70 or later
- **No external C dependencies** - Pure Rust implementation

## License

MIT License - see [LICENSE](LICENSE) for details.

## Acknowledgments

This library is a Rust port of the excellent Go implementation:

[keystore-go](https://github.com/pavlo-v-chernykh/keystore-go) by Pavlo Chernykh

PKCS12 support is powered by [p12-keystore](https://github.com/ancwrd1/p12-keystore) by Dmitry Pankratov.

## Author

[agusibrahim](https://github.com/agusibrahim)

## Contributing

Contributions are welcome! Please feel free to submit a Pull Request.