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
//! Obz - Flexible z-tier codec with runtime format selection
//!
//! ⚠️ **WARNING**: Z-tier schemes provide NO cryptographic security.
//! Use only for obfuscation, never for actual encryption.

#![cfg(feature = "ztier")]

#[cfg(feature = "keyless")]
use crate::constants::HARDCODED_SECRET_BYTES;
use crate::{format::IntoFormat, Encoding, Error, Format, ObtextCodec, Scheme};

use super::zdec_auto;
use super::zsecret::ZSecret;

/// A flexible z-tier codec with runtime format selection.
///
/// `Obz` is the z-tier equivalent of `Ob`, allowing runtime format selection
/// for obfuscation-only schemes (zrbcx, legacy).
///
/// **WARNING**: Z-tier schemes provide NO cryptographic security.
/// Use only for obfuscation, never for actual encryption.
///
/// # Examples
///
/// ## Basic usage with immutable format
///
/// ```rust
/// # fn main() -> Result<(), oboron::Error> {
/// # #[cfg(feature = "zrbcx")]
/// # {
/// # use oboron::ztier::Obz;
/// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; // 43 chars
/// let obz = Obz::new("zrbcx.b64", secret)?;
/// let ot = obz.enc("hello")?;
/// let pt2 = obz.dec(&ot)?;
/// assert_eq!(pt2, "hello");
/// # }
/// # Ok(())
/// # }
/// ```
///
/// ## Dynamic format switching
///
/// ```rust
/// # fn main() -> Result<(), oboron::Error> {
/// # #[cfg(all(feature = "zrbcx", feature = "zmock"))]
/// # {
/// # use oboron::ztier::Obz;
/// # use oboron::{Scheme, Encoding, Format};
/// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
/// let mut obz = Obz::new("zrbcx.c32", secret)?;
/// let ot1 = obz.enc("hello")?;
///
/// // Change format at runtime
/// obz.set_scheme(Scheme::Zmock1)?;
/// let ot2 = obz.enc("hello")?; // now zmock1.c32
///
/// // Change encoding
/// obz.set_encoding(Encoding::B64)?; // now zmock1.b64
///
/// // Set entire format at once
/// obz.set_format("zrbcx.hex")?; // now zrbcx.hex
/// # }
/// # Ok(())
/// # }
/// ```
pub struct Obz {
    zsecret: ZSecret,
    format: Format,
}

impl Obz {
    /// Create a new Obz with the specified format and base64 secret.
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "zrbcx")]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::{Format, Scheme, Encoding};
    /// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    /// // Using format string
    /// let obz1 = Obz::new("zrbcx.b64", secret)?;
    ///
    /// // Using Format instance
    /// let format = Format::new(Scheme::Zrbcx, Encoding::B64);
    /// let obz2 = Obz::new(format, secret)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn new(format: impl IntoFormat, secret: &str) -> Result<Self, Error> {
        let format = format.into_format()?;
        validate_ztier_scheme(format.scheme())?;
        Ok(Self {
            zsecret: ZSecret::from_base64(secret)?,
            format,
        })
    }

    /// Get the current format.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(feature = "zrbcx")]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::{Scheme, Encoding};
    /// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    /// let obz = Obz::new("zrbcx.b64", secret)?;
    /// let format = obz.format();
    /// assert_eq!(format.scheme(), Scheme::Zrbcx);
    /// assert_eq!(format.encoding(), Encoding::B64);
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn format(&self) -> Format {
        self.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 = "zrbcx", feature = "legacy"))]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::{Format, Scheme, Encoding};
    /// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    /// let mut obz = Obz::new("zrbcx.c32", secret)?;
    /// obz.set_format("legacy")?; // switch using string
    /// obz.set_format(Format::new(Scheme::Zrbcx, Encoding::Hex))?; // switch using Format
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_format(&mut self, format: impl IntoFormat) -> Result<(), Error> {
        let format = format.into_format()?;
        validate_ztier_scheme(format.scheme())?;
        self.format = format;
        Ok(())
    }

    /// Set the scheme while keeping the current encoding.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "zrbcx", feature = "legacy"))]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::Scheme;
    /// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    /// let mut obz = Obz::new("zrbcx.c32", secret)?;
    /// obz.set_scheme(Scheme::Legacy)?; // switch to legacy, keeping c32 encoding
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    pub fn set_scheme(&mut self, scheme: Scheme) -> Result<(), Error> {
        validate_ztier_scheme(scheme)?;
        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 = "zrbcx")]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::Encoding;
    /// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    /// let mut obz = Obz::new("zrbcx.c32", secret)?;
    /// obz.set_encoding(Encoding::B64)?; // switch to b64, keeping zrbcx 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 scheme autodetection.
    ///
    /// Uses the current encoding but automatically detects the scheme from the payload.
    /// Falls back to legacy decoding if scheme detection fails.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "zrbcx"))]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
    /// let mut obz = Obz::new("zrbcx.b64", secret)?;
    /// let ot = obz.enc("test")?;
    /// let pt2 = obz.autodec(&ot)?;
    /// assert_eq!(pt2, "test");
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[inline]
    pub fn autodec(&self, obtext: &str) -> Result<String, Error> {
        // Fast path: try current encoding first
        if let Ok(result) =
            zdec_auto::dec_any_scheme_ztier(&self.zsecret, self.format.encoding(), obtext)
        {
            return Ok(result);
        }
        zdec_auto::dec_any_format_ztier(&self.zsecret, obtext)
    }

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

    /// Create a new Obz with hardcoded secret (testing only).
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "zrbcx", feature = "keyless"))]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::{Format, Scheme, Encoding};
    /// // Using format string
    /// let obz1 = Obz::new_keyless("zrbcx.c32")?;
    ///
    /// // Using Format instance
    /// let format = Format::new(Scheme::Zrbcx, Encoding::C32);
    /// let obz2 = Obz::new_keyless(format)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "keyless")]
    pub fn new_keyless(format: impl IntoFormat) -> Result<Self, Error> {
        let format = format.into_format()?;
        validate_ztier_scheme(format.scheme())?;
        Ok(Self {
            zsecret: ZSecret::from_bytes(&HARDCODED_SECRET_BYTES)?,
            format,
        })
    }

    /// Create a new Obz with the specified format and hex secret.
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "zrbcx", feature = "hex-keys"))]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::{Format, Scheme, Encoding};
    /// let secret_hex = "0". repeat(64); // 32 bytes as hex
    /// // Using format string
    /// let obz1 = Obz::from_hex_key("zrbcx.b64", &secret_hex)?;
    ///
    /// // Using Format instance
    /// let format = Format::new(Scheme::Zrbcx, Encoding::B64);
    /// let obz2 = Obz::from_hex_key(format, &secret_hex)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "hex-keys")]
    pub fn from_hex_key(format: impl IntoFormat, secret_hex: &str) -> Result<Self, Error> {
        let format = format.into_format()?;
        validate_ztier_scheme(format.scheme())?;
        Ok(Self {
            zsecret: ZSecret::from_hex(secret_hex)?,
            format,
        })
    }

    /// Create a new Obz from the specified format and raw secret bytes.
    ///
    /// Accepts either a format string (`&str`) or a `Format` instance.
    ///
    /// # Examples
    ///
    /// ```rust
    /// # fn main() -> Result<(), oboron::Error> {
    /// # #[cfg(all(feature = "zrbcx", feature = "bytes-keys"))]
    /// # {
    /// # use oboron::ztier::Obz;
    /// # use oboron::{Format, Scheme, Encoding};
    /// let secret_bytes = [0u8; 32];
    /// let obz1 = Obz::from_bytes("zrbcx.b64", &secret_bytes)?; // using format string
    /// let format = Format::new(Scheme::Zrbcx, Encoding::B64); // using Format
    /// let obz2 = Obz::from_bytes(format, &secret_bytes)?;
    /// # }
    /// # Ok(())
    /// # }
    /// ```
    #[cfg(feature = "bytes-keys")]
    pub fn from_bytes(format: impl IntoFormat, secret: &[u8; 32]) -> Result<Self, Error> {
        let format = format.into_format()?;
        validate_ztier_scheme(format.scheme())?;
        Ok(Self {
            zsecret: ZSecret::from_bytes(secret)?,
            format,
        })
    }

    /// Get the secret as base64 (z-tier specific, 32 bytes)
    #[inline]
    pub fn secret(&self) -> String {
        self.zsecret.secret_base64()
    }

    /// Get the secret as hex (z-tier specific, 32 bytes)
    #[inline]
    #[cfg(feature = "hex-keys")]
    pub fn secret_hex(&self) -> String {
        self.zsecret.secret_hex()
    }

    /// Get the secret as bytes (z-tier specific, 32 bytes)
    #[inline]
    #[cfg(feature = "bytes-keys")]
    pub fn secret_bytes(&self) -> &[u8; 32] {
        self.zsecret.secret_bytes()
    }
}

impl ObtextCodec for Obz {
    fn enc(&self, plaintext: &str) -> Result<String, Error> {
        #[cfg(feature = "legacy")]
        if self.format.scheme() == Scheme::Legacy {
            let legacy = super::legacy::Legacy::from_master_secret(self.zsecret.master_secret())?;
            return <super::legacy::Legacy as ObtextCodec>::enc(&legacy, plaintext);
        }
        // Pass full 32-byte secret - z-tier enc function uses it directly
        crate::ztier::enc_to_format_ztier(plaintext, self.format, self.zsecret.master_secret())
    }

    fn dec(&self, obtext: &str) -> Result<String, Error> {
        #[cfg(feature = "legacy")]
        if self.format.scheme() == Scheme::Legacy {
            let legacy = super::legacy::Legacy::from_master_secret(self.zsecret.master_secret())?;
            return <super::legacy::Legacy as ObtextCodec>::dec(&legacy, obtext);
        }
        // Pass full 32-byte secret - z-tier dec function uses it directly
        crate::ztier::dec_from_format_ztier(obtext, self.format, self.zsecret.master_secret())
    }

    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 Obz {
    /// Encrypt and encode plaintext
    #[inline]
    pub fn enc(&self, plaintext: &str) -> Result<String, Error> {
        <Self as ObtextCodec>::enc(self, plaintext)
    }

    /// Decode and decrypt obtext (no scheme autodetection)
    #[inline]
    pub fn dec(&self, obtext: &str) -> Result<String, Error> {
        <Self as ObtextCodec>::dec(self, obtext)
    }

    /// Get the scheme
    #[inline]
    pub fn scheme(&self) -> Scheme {
        <Self as ObtextCodec>::scheme(self)
    }

    /// Get the encoding
    #[inline]
    pub fn encoding(&self) -> Encoding {
        <Self as ObtextCodec>::encoding(self)
    }
}

/// Helper function to validate that a scheme is a z-tier scheme
fn validate_ztier_scheme(scheme: Scheme) -> Result<(), Error> {
    match scheme {
        #[cfg(feature = "zrbcx")]
        Scheme::Zrbcx => Ok(()),
        #[cfg(feature = "zmock")]
        Scheme::Zmock1 => Ok(()),
        #[cfg(feature = "legacy")]
        Scheme::Legacy => Ok(()),
        _ => Err(Error::InvalidScheme),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    #[cfg(feature = "zrbcx")]
    fn test_obz_basic() {
        let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"; // 43 chars
        let obz = Obz::new("zrbcx.b64", secret).unwrap();

        let plaintext = "hello world";
        let ot = obz.enc(plaintext).unwrap();
        let pt2 = obz.dec(&ot).unwrap();

        assert_eq!(pt2, plaintext);
    }

    #[test]
    #[cfg(feature = "zrbcx")]
    fn test_obz_format_switching() {
        let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
        let mut obz = Obz::new("zrbcx.c32", secret).unwrap();

        assert_eq!(obz.encoding(), Encoding::C32);

        obz.set_encoding(Encoding::B64).unwrap();
        assert_eq!(obz.encoding(), Encoding::B64);
    }

    #[test]
    #[cfg(all(feature = "zrbcx", feature = "legacy"))]
    fn test_obz_scheme_switching() {
        let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";
        let mut obz = Obz::new("zrbcx.b64", secret).unwrap();

        assert_eq!(obz.scheme(), Scheme::Zrbcx);

        obz.set_scheme(Scheme::Legacy).unwrap();
        assert_eq!(obz.scheme(), Scheme::Legacy);
    }

    #[test]
    #[cfg(feature = "zrbcx")]
    fn test_obz_rejects_non_ztier_scheme() {
        let secret = "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA";

        #[cfg(feature = "aasv")]
        {
            let result = Obz::new("aasv.b64", secret);
            assert!(result.is_err());
        }
    }
}