oboron 0.7.0

Encryption and encoding library for developer ergonomics: prefix entropy, compact outputs, high performance
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
#[cfg(feature = "keyless")]
use crate::constants::HARDCODED_KEY_BYTES;
use crate::{format::IntoFormat, Encoding, Error, Format, MasterKey, ObtextCodec, Scheme};

/// A flexible ObtextCodec implementation with runtime format selection.
///
/// `Ob` allows you to specify any format at runtime via constructor parameters,
/// and provides methods to change the format after construction if needed.
///
/// This provides a unified interface for all runtime format needs, from
/// immutable configurations to dynamic format switching.
///
/// # Examples
///
/// ## Basic usage with immutable format
///
/// ```rust
/// # fn main() -> Result<(), oboron::Error> {
/// # #[cfg(feature = "aasv")]
/// # {
/// # use oboron::{Ob, generate_key};
/// # let key = generate_key();
/// let ob = Ob::new("aasv.b64", &key)?;
/// let ot = ob.enc("hello")?; // obtext
/// let pt2 = ob.dec(&ot)?; // recovered plaintext
/// assert_eq!(pt2, "hello");
/// # }
/// # Ok(())
/// # }
/// ```
///
/// ## Dynamic format switching
///
/// ```rust
/// # fn main() -> Result<(), oboron::Error> {
/// # #[cfg(all(feature = "aasv", feature = "mock"))]
/// # {
/// # use oboron::{Ob, Scheme, Encoding, Format, AASV_B64};
/// # let key = oboron::generate_key();
/// let mut ob = Ob::new("aasv.c32", &key)?;
/// let ot1 = ob.enc("hello")?; // aasv.c32 format
///
/// // Change format at runtime
/// ob.set_scheme(Scheme::Mock1)?;
/// let ot2 = ob.enc("hello")?; // mock1.c32 format
///
/// // Change encoding
/// ob.set_encoding(Encoding::B64)?; // now mock1.b64
///
/// // Set entire format at once
/// ob.set_format("aasv.hex")?; // now aasv.hex
/// ob.set_format(AASV_B64)?;   // now aasv.b64 (using constant)
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Ob {
    masterkey: MasterKey,
    format: Format,
}

impl Ob {
    /// Create a new Ob with the specified format and base64 key.
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron::{Ob, Format, Scheme, Encoding};
    /// # let key = oboron::generate_key();
    /// // Using format string
    /// let ob1 = Ob::new("aasv.b64", &key)?;
    ///
    /// // Using Format instance
    /// let format = Format::new(Scheme::Aasv, Encoding::B64);
    /// let ob2 = Ob::new(format, &key)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(format: impl IntoFormat, key: &str) -> Result<Self, Error> {
        let format = format.into_format()?;
        Ok(Self {
            masterkey: MasterKey::from_base64(key)?,
            format,
        })
    }

    /// Set the format to a new value.
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature = "mock"))]
    /// # {
    /// # use oboron::{Ob, Format, Scheme, Encoding};
    /// # let key = oboron::generate_key();
    /// let mut ob = Ob::new("aasv.c32", &key)?;
    /// ob.set_format("mock1.b64")?; // switch using string
    /// ob.set_format(Format::new(Scheme::Mock2, Encoding:: Hex))?; // switch using Format
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_format(&mut self, format: impl IntoFormat) -> Result<(), Error> {
        self.format = format.into_format()?;
        Ok(())
    }

    /// Set the scheme while keeping the current encoding.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature = "mock"))]
    /// # {
    /// # use oboron::{Ob, Scheme};
    /// # let key = oboron::generate_key();
    /// let mut ob = Ob::new("aasv.c32", &key)?;
    /// ob.set_scheme(Scheme::Mock1)?; // switch to mock1, keeping c32 encoding
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_scheme(&mut self, scheme: Scheme) -> Result<(), Error> {
        self.format = Format::new(scheme, self.format.encoding());
        Ok(())
    }

    /// Set the encoding while keeping the current scheme.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron::{Ob, Encoding};
    /// # let key = oboron::generate_key();
    /// let mut ob = Ob::new("aasv.c32", &key)?;
    /// ob.set_encoding(Encoding::B64)?; // switch to b64, keeping aasv scheme
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_encoding(&mut self, encoding: Encoding) -> Result<(), Error> {
        self.format = Format::new(self.format.scheme(), encoding);
        Ok(())
    }

    /// Decode and decrypt obtext with automatic format detection.
    ///
    /// Tries to decode using the instance's current encoding first (fast path),
    /// then falls back to full format autodetection if that fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature = "mock"))]
    /// # {
    /// # use oboron:: Ob;
    /// # let key = oboron::generate_key();
    /// let mut ob = Ob::new("aasv.b64", &key)?;
    /// let ot = ob.enc("test")?;
    ///
    /// // Change scheme - autodec will still work
    /// ob.set_scheme(oboron::Scheme::Mock1)?;
    /// let pt2 = ob.autodec(&ot)?;
    /// assert_eq!(pt2, "test");
    ///
    /// // Works even with different encoding (slower fallback path)
    /// ob.set_encoding(oboron::Encoding:: Hex)?;
    /// let pt3 = ob.autodec(&ot)?; // Falls back to full autodetection
    /// assert_eq!(pt3, "test");
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn autodec(&self, obtext: &str) -> Result<String, Error> {
        // Fast path: try current encoding first
        if let Ok(result) =
            crate::dec_auto::dec_any_scheme(&self.masterkey, self.format.encoding(), obtext)
        {
            return Ok(result);
        }

        // Fallback:  full format autodetection (encoding + scheme)
        crate::dec_auto::dec_any_format(&self.masterkey, obtext)
    }

    // Alt constructors ================================================

    /// Create a new Ob with hardcoded key (testing only).
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature="keyless"))]
    /// # {
    /// # use oboron::{Ob, Format, Scheme, Encoding};
    /// // Using format string
    /// let ob1 = Ob::new_keyless("aasv.c32")?;
    ///
    /// // Using Format instance
    /// let format = Format::new(Scheme::Aasv, Encoding::C32);
    /// let ob2 = Ob:: new_keyless(format)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "keyless")]
    pub fn new_keyless(format: impl IntoFormat) -> Result<Self, Error> {
        let format = format.into_format()?;
        Ok(Self {
            masterkey: MasterKey::from_bytes(&HARDCODED_KEY_BYTES)?,
            format,
        })
    }

    /// Create a new Ob with the specified format and hex key.
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature = "hex-keys"))]
    /// # {
    /// # use oboron::{Ob, Format, Scheme, Encoding};
    /// let key_hex = oboron::generate_key_hex();
    /// // Using format string
    /// let ob1 = Ob::from_hex_key("aasv.b64", &key_hex)?;
    ///
    /// // Using Format instance
    /// let format = Format::new(Scheme::Aasv, Encoding::B64);
    /// let ob2 = Ob::from_hex_key(format, &key_hex)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "hex-keys")]
    pub fn from_hex_key(format: impl IntoFormat, key_hex: &str) -> Result<Self, Error> {
        let format = format.into_format()?;
        Ok(Self {
            masterkey: MasterKey::from_hex(key_hex)?,
            format,
        })
    }

    /// Create a new Ob from the specified format and raw key bytes.
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature = "bytes-keys"))]
    /// # {
    /// # use oboron::{Ob, Format, Scheme, Encoding};
    /// let key_bytes = oboron::generate_key_bytes();
    /// let ob1 = Ob::from_bytes("aasv.b64", &key_bytes)?; // using format string
    /// let format = Format::new(Scheme:: Aasv, Encoding:: B64); // using Format
    /// let ob2 = Ob::from_bytes(format, &key_bytes)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "bytes-keys")]
    pub fn from_bytes(format: impl IntoFormat, key: &[u8; 64]) -> Result<Self, Error> {
        let format = format.into_format()?;
        Ok(Self {
            masterkey: MasterKey::from_bytes(key)?,
            format,
        })
    }

    /// Get the key as a base64 string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron:: Ob;
    /// # let key = oboron::generate_key();
    /// let ob = Ob::new("aasv.b64", &key)?;
    /// let key_retrieved = ob.key();
    /// assert_eq!(key_retrieved, key);
    /// assert_eq!(key_retrieved.len(), 86); // 64 bytes = 86 base64 chars
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn key(&self) -> String {
        self.masterkey.key_base64()
    }

    /// Get the key as a hex string.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature = "hex-keys"))]
    /// # {
    /// # use oboron::Ob;
    /// # let key = oboron::generate_key();
    /// let ob = Ob::new("aasv.b64", &key)?;
    /// let key_hex = ob.key_hex();
    /// assert_eq!(key_hex. len(), 128); // 64 bytes = 128 hex chars
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "hex-keys")]
    #[inline]
    pub fn key_hex(&self) -> String {
        self.masterkey.key_hex()
    }

    /// Get the key as raw bytes.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "aasv", feature = "bytes-keys"))]
    /// # {
    /// # use oboron::Ob;
    /// let key_bytes = oboron::generate_key_bytes();
    /// let ob = Ob::from_bytes("aasv.b64", &key_bytes)?;
    /// let retrieved = ob.key_bytes();
    /// assert_eq!(retrieved, &key_bytes);
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "bytes-keys")]
    #[inline]
    pub fn key_bytes(&self) -> &[u8; 64] {
        self.masterkey.key_bytes()
    }
}

impl ObtextCodec for Ob {
    fn enc(&self, plaintext: &str) -> Result<String, Error> {
        crate::enc::enc_to_format(plaintext, self.format, self.masterkey.key())
    }

    fn dec(&self, obtext: &str) -> Result<String, Error> {
        crate::dec::dec_from_format(obtext, self.format, self.masterkey.key())
    }

    fn format(&self) -> Format {
        self.format
    }

    fn scheme(&self) -> Scheme {
        self.format.scheme()
    }

    fn encoding(&self) -> Encoding {
        self.format.encoding()
    }
}

// Add inherent methods that delegate to trait methods
impl Ob {
    /// Encrypt and encode plaintext to obtext.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron:: Ob;
    /// # let key = oboron::generate_key();
    /// let ob = Ob::new("aasv.b64", &key)?;
    /// let ot = ob.enc("secret data")?;
    /// assert! (!ot.is_empty());
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn enc(&self, plaintext: &str) -> Result<String, Error> {
        <Self as ObtextCodec>::enc(self, plaintext)
    }

    /// Decode and decrypt obtext to plaintext.
    ///
    /// Uses the instance's configured format for decoding.  Does not perform
    /// scheme autodetection - use [`autodec`](Self::autodec) for that.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron::Ob;
    /// # let key = oboron::generate_key();
    /// let ob = Ob::new("aasv.b64", &key)?;
    /// let ot = ob.enc("secret data")?;
    /// let pt2 = ob.dec(&ot)?;
    /// assert_eq!(pt2, "secret data");
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn dec(&self, obtext: &str) -> Result<String, Error> {
        <Self as ObtextCodec>::dec(self, obtext)
    }

    /// Get the current format (scheme + encoding).
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron::{Ob, Scheme, Encoding};
    /// # let key = oboron::generate_key();
    /// let ob = Ob::new("aasv.b64", &key)?;
    /// let format = ob.format();
    /// assert_eq!(format.scheme(), Scheme::Aasv);
    /// assert_eq!(format.encoding(), Encoding::B64);
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn format(&self) -> Format {
        <Self as ObtextCodec>::format(self)
    }

    /// Get the current scheme.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron::{Ob, Scheme};
    /// # let key = oboron::generate_key();
    /// let ob = Ob:: new("aasv.b64", &key)?;
    /// assert_eq!(ob.scheme(), Scheme::Aasv);
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn scheme(&self) -> Scheme {
        <Self as ObtextCodec>::scheme(self)
    }

    /// Get the current encoding.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "aasv")]
    /// # {
    /// # use oboron::{Ob, Encoding};
    /// # let key = oboron::generate_key();
    /// let ob = Ob:: new("aasv.b64", &key)?;
    /// assert_eq!(ob.encoding(), Encoding::B64);
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn encoding(&self) -> Encoding {
        <Self as ObtextCodec>::encoding(self)
    }
}