1pub use crate::crypto::buffer::SecretBytes;
2
3#[derive(Clone, Debug, PartialEq, Eq)]
5pub struct Encrypted {
6 pub(crate) buffer: SecretBytes,
7 pub(crate) tag_pos: usize,
8 pub(crate) nonce_pos: usize,
9}
10
11impl Encrypted {
12 pub(crate) fn new(buffer: SecretBytes, tag_pos: usize, nonce_pos: usize) -> Self {
13 Self {
14 buffer,
15 tag_pos,
16 nonce_pos,
17 }
18 }
19
20 pub fn into_vec(self) -> Vec<u8> {
22 self.buffer.into_vec()
23 }
24
25 pub fn ciphertext(&self) -> &[u8] {
27 &self.buffer[0..(self.tag_pos)]
28 }
29
30 pub fn nonce(&self) -> &[u8] {
32 &self.buffer[(self.nonce_pos)..]
33 }
34
35 pub fn tag(&self) -> &[u8] {
37 &self.buffer[(self.tag_pos)..(self.nonce_pos)]
38 }
39}
40
41impl AsRef<[u8]> for Encrypted {
42 fn as_ref(&self) -> &[u8] {
43 self.buffer.as_ref()
44 }
45}
46
47impl From<Encrypted> for SecretBytes {
48 fn from(e: Encrypted) -> Self {
49 e.buffer
50 }
51}
52
53#[derive(Clone, Copy, Debug)]
54pub struct ToDecrypt<'d> {
56 pub ciphertext: &'d [u8],
58 pub tag: &'d [u8],
60}
61
62impl ToDecrypt<'_> {
63 #[allow(clippy::len_without_is_empty)]
65 #[inline]
66 pub fn len(&self) -> usize {
67 self.ciphertext.len() + self.tag.len()
68 }
69
70 pub(crate) fn into_secret(self) -> SecretBytes {
71 if self.tag.is_empty() {
72 SecretBytes::from_slice(self.ciphertext)
73 } else {
74 let mut buf = SecretBytes::with_capacity(self.len());
75 buf.extend_from_slice(self.ciphertext);
76 buf.extend_from_slice(self.tag);
77 buf
78 }
79 }
80}
81
82impl<'d> From<&'d [u8]> for ToDecrypt<'d> {
83 fn from(ciphertext: &'d [u8]) -> Self {
84 Self {
85 ciphertext,
86 tag: &[],
87 }
88 }
89}
90
91impl<'d> From<(&'d [u8], &'d [u8])> for ToDecrypt<'d> {
92 fn from(split: (&'d [u8], &'d [u8])) -> Self {
93 Self {
94 ciphertext: split.0,
95 tag: split.1,
96 }
97 }
98}
99
100impl<'d> From<&'d Encrypted> for ToDecrypt<'d> {
101 fn from(enc: &'d Encrypted) -> Self {
102 Self {
103 ciphertext: enc.ciphertext(),
104 tag: enc.tag(),
105 }
106 }
107}