wecanencrypt 0.9.0

Simple Rust OpenPGP library for encryption, signing, and key management.
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
//! Encryption functions.
//!
//! This module provides functions for encrypting data to one or more
//! OpenPGP recipients.

use std::io::{BufReader, Cursor, Read};
use std::path::Path;

use pgp::armor::Dearmor;
use pgp::composed::{MessageBuilder, SignedPublicKey};
use pgp::crypto::aead::{AeadAlgorithm, ChunkSize};
use pgp::crypto::sym::SymmetricKeyAlgorithm;
use pgp::packet::{Packet, PacketParser, PublicKeyEncryptedSessionKey};
use pgp::types::KeyDetails;
use rand::thread_rng;

use crate::error::{Error, Result};
use crate::internal::{can_subkey_encrypt, is_subkey_valid, parse_public_key};

/// Encrypt bytes to a single recipient.
///
/// Uses SEIPD v1 (RFC 4880, integrity-protected with MDC). For AEAD encryption
/// with V6 keys, use [`encrypt_bytes_v2`].
///
/// Encrypts the plaintext to the recipient's public key. The message can only
/// be decrypted by someone with the corresponding secret key.
///
/// # Arguments
/// * `recipient_cert` - The recipient's public key (armored or binary)
/// * `plaintext` - The data to encrypt
/// * `armor` - If true, output ASCII-armored; otherwise binary
///
/// # Returns
/// The encrypted message.
///
/// # Example
///
/// ```no_run
/// use wecanencrypt::{create_key_simple, encrypt_bytes, decrypt_bytes, get_pub_key};
///
/// // Create a key pair
/// let key = create_key_simple("password", &["Alice <alice@example.com>"]).unwrap();
/// let public_key = get_pub_key(&key.secret_key).unwrap();
///
/// // Encrypt a message
/// let ciphertext = encrypt_bytes(public_key.as_bytes(), b"Secret message", true).unwrap();
///
/// // Decrypt it
/// let plaintext = decrypt_bytes(&key.secret_key, &ciphertext, "password").unwrap();
/// assert_eq!(plaintext, b"Secret message");
/// ```
pub fn encrypt_bytes(recipient_cert: &[u8], plaintext: &[u8], armor: bool) -> Result<Vec<u8>> {
    encrypt_bytes_to_multiple(&[recipient_cert], plaintext, armor)
}

/// Encrypt bytes to a single recipient using SEIPD v2 (RFC 9580, AEAD).
///
/// Like [`encrypt_bytes`], but uses SEIPD v2 (AES-256-OCB) for AEAD-based
/// authenticated encryption. Requires recipients with V6 key support.
///
/// # Arguments
/// * `recipient_cert` - The recipient's public key (armored or binary)
/// * `plaintext` - The data to encrypt
/// * `armor` - If true, output ASCII-armored; otherwise binary
pub fn encrypt_bytes_v2(recipient_cert: &[u8], plaintext: &[u8], armor: bool) -> Result<Vec<u8>> {
    encrypt_bytes_to_multiple_v2(&[recipient_cert], plaintext, armor)
}

/// Encrypt bytes to multiple recipients.
///
/// Uses SEIPD v1 (RFC 4880, integrity-protected with MDC). For AEAD encryption
/// with V6 keys, use [`encrypt_bytes_to_multiple_v2`].
///
/// Encrypts the plaintext so that any of the recipients can decrypt it.
/// Each recipient only needs their own secret key to decrypt.
///
/// # Arguments
/// * `recipient_certs` - Slice of recipient public keys (armored or binary)
/// * `plaintext` - The data to encrypt
/// * `armor` - If true, output ASCII-armored; otherwise binary
///
/// # Returns
/// The encrypted message that can be decrypted by any of the recipients.
///
/// # Example
///
/// ```no_run
/// use wecanencrypt::{create_key_simple, encrypt_bytes_to_multiple, decrypt_bytes, get_pub_key};
///
/// // Create two recipients
/// let alice = create_key_simple("alice_pw", &["Alice <alice@example.com>"]).unwrap();
/// let bob = create_key_simple("bob_pw", &["Bob <bob@example.com>"]).unwrap();
///
/// let alice_pub = get_pub_key(&alice.secret_key).unwrap();
/// let bob_pub = get_pub_key(&bob.secret_key).unwrap();
///
/// // Encrypt to both
/// let ciphertext = encrypt_bytes_to_multiple(
///     &[alice_pub.as_bytes(), bob_pub.as_bytes()],
///     b"Group message",
///     true,
/// ).unwrap();
///
/// // Either can decrypt
/// let plain_alice = decrypt_bytes(&alice.secret_key, &ciphertext, "alice_pw").unwrap();
/// let plain_bob = decrypt_bytes(&bob.secret_key, &ciphertext, "bob_pw").unwrap();
/// assert_eq!(plain_alice, plain_bob);
/// ```
pub fn encrypt_bytes_to_multiple(
    recipient_certs: &[&[u8]],
    plaintext: &[u8],
    armor: bool,
) -> Result<Vec<u8>> {
    encrypt_bytes_to_multiple_with_algo(
        recipient_certs,
        plaintext,
        armor,
        SymmetricKeyAlgorithm::AES256,
    )
}

/// Encrypt bytes to multiple recipients using SEIPD v2 (RFC 9580, AEAD).
///
/// Like [`encrypt_bytes_to_multiple`], but uses SEIPD v2 (AES-256-OCB) for
/// AEAD-based authenticated encryption. Requires recipients with V6 key support.
///
/// # Arguments
/// * `recipient_certs` - Slice of recipient public keys (armored or binary)
/// * `plaintext` - The data to encrypt
/// * `armor` - If true, output ASCII-armored; otherwise binary
///
/// # Returns
/// The encrypted message using SEIPD v2 format.
pub fn encrypt_bytes_to_multiple_v2(
    recipient_certs: &[&[u8]],
    plaintext: &[u8],
    armor: bool,
) -> Result<Vec<u8>> {
    encrypt_bytes_to_multiple_seipd_v2(
        recipient_certs,
        plaintext,
        armor,
        SymmetricKeyAlgorithm::AES256,
    )
}

/// Encrypt bytes to multiple recipients with a specific symmetric algorithm.
///
/// Uses SEIPD v1 (RFC 4880, integrity-protected with MDC).
/// Like [`encrypt_bytes_to_multiple`], but allows choosing the symmetric cipher.
/// RFC 9580 requires implementations to support both AES-128 and AES-256.
///
/// # Arguments
/// * `recipient_certs` - Slice of recipient public keys (armored or binary)
/// * `plaintext` - The data to encrypt
/// * `armor` - If true, output ASCII-armored; otherwise binary
/// * `sym_algo` - The symmetric algorithm to use (e.g., AES128, AES256)
///
/// # Returns
/// The encrypted message that can be decrypted by any of the recipients.
pub fn encrypt_bytes_to_multiple_with_algo(
    recipient_certs: &[&[u8]],
    plaintext: &[u8],
    armor: bool,
    sym_algo: SymmetricKeyAlgorithm,
) -> Result<Vec<u8>> {
    validate_sym_algo(sym_algo)?;

    if recipient_certs.is_empty() {
        return Err(Error::InvalidInput("No recipients specified".to_string()));
    }

    let mut rng = thread_rng();

    let encryption_keys = collect_encryption_keys(recipient_certs)?;

    // Build the encrypted message using SEIPD v1 (MDC)
    let mut builder =
        MessageBuilder::from_bytes("", plaintext.to_vec()).seipd_v1(&mut rng, sym_algo);

    // Add all encryption keys as recipients
    for key in &encryption_keys {
        builder
            .encrypt_to_key(&mut rng, key)
            .map_err(|e| Error::Crypto(e.to_string()))?;
    }

    // Produce the output
    if armor {
        let armored = builder
            .to_armored_string(&mut rng, None.into())
            .map_err(|e| Error::Crypto(e.to_string()))?;
        Ok(armored.into_bytes())
    } else {
        builder
            .to_vec(&mut rng)
            .map_err(|e| Error::Crypto(e.to_string()))
    }
}

/// Encrypt bytes to multiple recipients using SEIPD v2 (RFC 9580, AEAD) with a
/// specific symmetric algorithm.
///
/// Uses AEAD with OCB mode for authenticated encryption. Requires recipients
/// with V6 key support.
///
/// # Arguments
/// * `recipient_certs` - Slice of recipient public keys (armored or binary)
/// * `plaintext` - The data to encrypt
/// * `armor` - If true, output ASCII-armored; otherwise binary
/// * `sym_algo` - The symmetric algorithm to use (e.g., AES128, AES256)
///
/// # Returns
/// The encrypted message using SEIPD v2 format.
pub fn encrypt_bytes_to_multiple_seipd_v2(
    recipient_certs: &[&[u8]],
    plaintext: &[u8],
    armor: bool,
    sym_algo: SymmetricKeyAlgorithm,
) -> Result<Vec<u8>> {
    validate_sym_algo(sym_algo)?;

    if recipient_certs.is_empty() {
        return Err(Error::InvalidInput("No recipients specified".to_string()));
    }

    let mut rng = thread_rng();

    let encryption_keys = collect_encryption_keys(recipient_certs)?;

    // Build the encrypted message using SEIPD v2 (AEAD with OCB)
    let mut builder = MessageBuilder::from_bytes("", plaintext.to_vec()).seipd_v2(
        &mut rng,
        sym_algo,
        AeadAlgorithm::Ocb,
        ChunkSize::default(),
    );

    // Add all encryption keys as recipients
    for key in &encryption_keys {
        builder
            .encrypt_to_key(&mut rng, key)
            .map_err(|e| Error::Crypto(e.to_string()))?;
    }

    // Produce the output
    if armor {
        let armored = builder
            .to_armored_string(&mut rng, None.into())
            .map_err(|e| Error::Crypto(e.to_string()))?;
        Ok(armored.into_bytes())
    } else {
        builder
            .to_vec(&mut rng)
            .map_err(|e| Error::Crypto(e.to_string()))
    }
}

/// Reject deprecated/insecure symmetric algorithms per RFC 9580 ยง9.3.
fn validate_sym_algo(sym_algo: SymmetricKeyAlgorithm) -> Result<()> {
    match sym_algo {
        SymmetricKeyAlgorithm::AES128
        | SymmetricKeyAlgorithm::AES192
        | SymmetricKeyAlgorithm::AES256
        | SymmetricKeyAlgorithm::Twofish
        | SymmetricKeyAlgorithm::Camellia128
        | SymmetricKeyAlgorithm::Camellia192
        | SymmetricKeyAlgorithm::Camellia256 => Ok(()),
        _ => Err(Error::InvalidInput(format!(
            "Symmetric algorithm {:?} is not allowed for encryption per RFC 9580",
            sym_algo
        ))),
    }
}

/// Parse recipient certs and collect valid encryption subkeys.
fn collect_encryption_keys(
    recipient_certs: &[&[u8]],
) -> Result<Vec<pgp::composed::SignedPublicSubKey>> {
    let mut encryption_keys = Vec::new();
    for cert_data in recipient_certs {
        let public_key = parse_public_key(cert_data)?;
        let subkeys = find_valid_encryption_subkeys(&public_key)?;
        encryption_keys.extend(subkeys);
    }

    if encryption_keys.is_empty() {
        return Err(Error::NoEncryptionSubkey);
    }

    Ok(encryption_keys)
}

/// Encrypt a file to a single recipient.
///
/// Reads the input file, encrypts it, and writes the result to the output file.
///
/// # Arguments
/// * `recipient_cert` - The recipient's public key (armored or binary)
/// * `input` - Path to the input file
/// * `output` - Path to the output file
/// * `armor` - If true, output ASCII-armored; otherwise binary
///
/// # Example
///
/// ```no_run
/// use wecanencrypt::encrypt_file;
///
/// let public_key = std::fs::read("recipient.asc").unwrap();
/// encrypt_file(&public_key, "document.pdf", "document.pdf.gpg", true).unwrap();
/// ```
pub fn encrypt_file(
    recipient_cert: &[u8],
    input: impl AsRef<Path>,
    output: impl AsRef<Path>,
    armor: bool,
) -> Result<()> {
    encrypt_file_to_multiple(&[recipient_cert], input, output, armor)
}

/// Encrypt a file to multiple recipients.
///
/// # Arguments
/// * `recipient_certs` - Slice of recipient public keys (armored or binary)
/// * `input` - Path to the input file
/// * `output` - Path to the output file
/// * `armor` - If true, output ASCII-armored; otherwise binary
///
/// # Example
///
/// ```no_run
/// use wecanencrypt::encrypt_file_to_multiple;
///
/// let alice_key = std::fs::read("alice.asc").unwrap();
/// let bob_key = std::fs::read("bob.asc").unwrap();
///
/// encrypt_file_to_multiple(
///     &[&alice_key, &bob_key],
///     "document.pdf",
///     "document.pdf.gpg",
///     true,
/// ).unwrap();
/// ```
pub fn encrypt_file_to_multiple(
    recipient_certs: &[&[u8]],
    input: impl AsRef<Path>,
    output: impl AsRef<Path>,
    armor: bool,
) -> Result<()> {
    let plaintext = std::fs::read(input.as_ref())?;
    let ciphertext = encrypt_bytes_to_multiple(recipient_certs, &plaintext, armor)?;
    std::fs::write(output.as_ref(), ciphertext)?;
    Ok(())
}

/// Encrypt data from a reader to a file.
///
/// # Arguments
/// * `recipient_certs` - Slice of recipient public keys
/// * `reader` - Source of plaintext data
/// * `output` - Path to the output file
/// * `armor` - If true, output ASCII-armored
pub fn encrypt_reader_to_file<R: Read>(
    recipient_certs: &[&[u8]],
    mut reader: R,
    output: impl AsRef<Path>,
    armor: bool,
) -> Result<()> {
    let mut plaintext = Vec::new();
    reader.read_to_end(&mut plaintext)?;
    let ciphertext = encrypt_bytes_to_multiple(recipient_certs, &plaintext, armor)?;
    std::fs::write(output.as_ref(), ciphertext)?;
    Ok(())
}

/// Get the key IDs that a message was encrypted for.
///
/// # Arguments
/// * `ciphertext` - The encrypted message (armored or binary)
///
/// # Returns
/// A list of key IDs (hex strings) that can decrypt this message.
pub fn bytes_encrypted_for(ciphertext: &[u8]) -> Result<Vec<String>> {
    let mut key_ids = Vec::new();

    // Try to dearmor if it looks armored
    let data = if ciphertext.starts_with(b"-----BEGIN PGP") {
        let cursor = Cursor::new(ciphertext);
        let dearmor = Dearmor::new(cursor);
        let mut buf = Vec::new();
        let mut reader = BufReader::new(dearmor);
        reader.read_to_end(&mut buf)?;
        buf
    } else {
        ciphertext.to_vec()
    };

    // Parse packets and look for PKESK
    let parser = PacketParser::new(Cursor::new(&data));

    for packet_result in parser {
        match packet_result {
            Ok(packet) => {
                if let Packet::PublicKeyEncryptedSessionKey(pkesk) = packet {
                    let key_id = match pkesk {
                        PublicKeyEncryptedSessionKey::V3 { id, .. } => {
                            // KeyId uses Display with lowercase hex, convert to uppercase
                            format!("{}", id).to_uppercase()
                        }
                        PublicKeyEncryptedSessionKey::V6 { fingerprint, .. } => {
                            // V6 PKESK uses fingerprint
                            if let Some(fp) = fingerprint {
                                format!("{}", fp).to_uppercase()
                            } else {
                                // Anonymous recipient
                                continue;
                            }
                        }
                        PublicKeyEncryptedSessionKey::Other { .. } => {
                            // Unknown version, skip
                            continue;
                        }
                    };
                    key_ids.push(key_id);
                }
            }
            Err(_) => {
                // Stop on parsing error (we've probably hit encrypted data)
                break;
            }
        }
    }

    Ok(key_ids)
}

/// Get the key IDs that a file was encrypted for.
///
/// # Arguments
/// * `path` - Path to the encrypted file
///
/// # Returns
/// A list of key IDs (hex strings) that can decrypt this file.
pub fn file_encrypted_for(path: impl AsRef<Path>) -> Result<Vec<String>> {
    let ciphertext = std::fs::read(path.as_ref())?;
    bytes_encrypted_for(&ciphertext)
}

/// Helper to find valid encryption subkeys from a public key.
fn find_valid_encryption_subkeys(
    key: &SignedPublicKey,
) -> Result<Vec<pgp::composed::SignedPublicSubKey>> {
    let mut valid_keys = Vec::new();

    for subkey in &key.public_subkeys {
        // Check if the subkey can encrypt
        if !subkey.key.algorithm().can_encrypt() {
            continue;
        }

        // Check key flags in most recent binding signature (RFC 4880 ยง5.2.3.3)
        if !can_subkey_encrypt(subkey) {
            continue;
        }

        // Check if subkey is valid (not revoked, not expired)
        if !is_subkey_valid(subkey, false) {
            continue;
        }

        valid_keys.push(subkey.clone());
    }

    if valid_keys.is_empty() {
        return Err(Error::NoEncryptionSubkey);
    }

    Ok(valid_keys)
}

#[cfg(test)]
mod tests {
    // Tests would require key fixtures
}