Skip to content

Commit a1ea4ce

Browse files
committed
Address feedback from rozzbb
1 parent 7019866 commit a1ea4ce

File tree

11 files changed

+796
-340
lines changed

11 files changed

+796
-340
lines changed

MODULE.bazel.lock

Lines changed: 368 additions & 96 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

rust/Cargo.lock

Lines changed: 235 additions & 64 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

rust/Cargo.toml

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -8,11 +8,15 @@ edition = '2024'
88
name="floe"
99
path="floe/src/lib.rs"
1010

11+
[features]
12+
default = ["getrandom"]
13+
getrandom = []
14+
1115
[dependencies]
12-
aead = { version = "0.5.2", features = ["std"] }
13-
aes-gcm = "0.10.3"
16+
aead = { version = "0.5.2", default-features = false }
17+
aes-gcm = { version = "0.10.3", default-features = false, features = ["aes", "zeroize"] }
1418
sha2 = "0.10.8"
15-
rand = "0.9.1"
19+
rand = "0.10.0"
1620
hmac = "0.12.1"
1721
subtle = "2.6"
1822
zeroize = { version = "1.8.2", features = ["zeroize_derive"] }

rust/bench/src/main.rs

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,7 @@ use criterion::profiler::Profiler;
2121

2222
use std::{time::Duration, alloc::{GlobalAlloc, System}, sync::atomic::{AtomicUsize, Ordering}};
2323

24-
use rand::rngs::{OsRng};
24+
use rand::rngs::SysRng;
2525
use rand::TryRngCore;
2626

2727
use aead::{Aead, Payload, KeyInit};
@@ -35,18 +35,18 @@ pub fn criterion_benchmark(c: &mut Criterion) {
3535
let _run_time = Duration::from_secs(30);
3636

3737
let mut aad = vec![0u8; 32];
38-
OsRng.try_fill_bytes(&mut aad).unwrap();
38+
SysRng.try_fill_bytes(&mut aad).unwrap();
3939
let key = FloeKey::new_random(GCM256_IV256_4K).unwrap();
4040
let mut raw_gcm_key = vec![0u8; 32];
41-
OsRng.try_fill_bytes(&mut raw_gcm_key).unwrap();
41+
SysRng.try_fill_bytes(&mut raw_gcm_key).unwrap();
4242
let gcm_key = Aes256Gcm::new_from_slice(&raw_gcm_key).unwrap();
4343
// let pt_lengths = [1024_usize, 2048, 4096, 8192, 1024*16, 1024*128, 1024*1024, 1024*1024*2, 1024*1024*16];
4444
let pt_lengths = [1024_usize*1024*16];
4545
// group.warm_up_time(_run_time);
4646
// group.measurement_time(_run_time);
4747
for pt_len in pt_lengths {
4848
let mut pt = vec![0u8; pt_len];
49-
OsRng.try_fill_bytes(&mut pt).unwrap();
49+
SysRng.try_fill_bytes(&mut pt).unwrap();
5050
group.throughput(Throughput::Bytes(pt_len as u64));
5151
let ct = floe_encrypt(&pt, &aad, &key).unwrap();
5252
group.bench_function(format!("Encrypt {}", pt_len), |b| b.iter(|| floe_encrypt(&pt, &aad, &key)));
@@ -58,7 +58,7 @@ pub fn criterion_benchmark(c: &mut Criterion) {
5858
// gcm_group.measurement_time(_run_time);
5959
for pt_len in pt_lengths {
6060
let mut pt = vec![0u8; pt_len];
61-
OsRng.try_fill_bytes(&mut pt).unwrap();
61+
SysRng.try_fill_bytes(&mut pt).unwrap();
6262
gcm_group.throughput(Throughput::Bytes(pt_len as u64));
6363
let ct = gcm_encrypt(&pt, &aad, &gcm_key).unwrap();
6464
gcm_group.bench_function(format!("Encrypt {}", pt_len), |b| b.iter(|| gcm_encrypt(&pt, &aad, &gcm_key)));
@@ -72,17 +72,17 @@ pub fn heap_benchmark(c: &mut Criterion) {
7272
let _run_time = Duration::from_secs(30);
7373

7474
let mut aad = vec![0u8; 32];
75-
OsRng.try_fill_bytes(&mut aad).unwrap();
75+
SysRng.try_fill_bytes(&mut aad).unwrap();
7676
let key = FloeKey::new_random(GCM256_IV256_4K).unwrap();
7777
let mut raw_gcm_key = vec![0u8; 32];
78-
OsRng.try_fill_bytes(&mut raw_gcm_key).unwrap();
78+
SysRng.try_fill_bytes(&mut raw_gcm_key).unwrap();
7979
let gcm_key = Aes256Gcm::new_from_slice(&raw_gcm_key).unwrap();
8080
let pt_lengths = [1024_usize]; //, 2048, 4096, 8192, ];// 1024*16, 1024*128, 1024*1024]; //, 1024*1024*2, 1024*1024*16];
8181
// group.warm_up_time(_run_time);
8282
// group.measurement_time(_run_time);
8383
for pt_len in pt_lengths {
8484
let mut pt = vec![0u8; pt_len];
85-
OsRng.try_fill_bytes(&mut pt).unwrap();
85+
SysRng.try_fill_bytes(&mut pt).unwrap();
8686
// group.throughput(Throughput::Bytes(pt_len as u64));
8787
let ct = floe_encrypt(&pt, &aad, &key).unwrap();
8888
group.bench_function(format!("Encrypt {}", pt_len), |b| b.iter(|| floe_encrypt(&pt, &aad, &key)));
@@ -94,7 +94,7 @@ pub fn heap_benchmark(c: &mut Criterion) {
9494
// gcm_group.measurement_time(_run_time);
9595
for pt_len in pt_lengths {
9696
let mut pt = vec![0u8; pt_len];
97-
OsRng.try_fill_bytes(&mut pt).unwrap();
97+
SysRng.try_fill_bytes(&mut pt).unwrap();
9898
// gcm_group.throughput(Throughput::Bytes(pt_len as u64));
9999
let ct = gcm_encrypt(&pt, &aad, &gcm_key).unwrap();
100100
gcm_group.bench_function(format!("Encrypt {}", pt_len), |b| b.iter(|| gcm_encrypt(&pt, &aad, &gcm_key)));
@@ -163,7 +163,7 @@ fn gcm_encrypt(
163163
key: &Aes256Gcm
164164
) -> Result<Vec<u8>> {
165165
let mut nonce = [0u8; 12];
166-
OsRng.try_fill_bytes(&mut nonce).unwrap();
166+
SysRng.try_fill_bytes(&mut nonce).unwrap();
167167

168168
let payload = Payload { msg: pt, aad };
169169
let mut ct = vec![];
@@ -232,4 +232,4 @@ impl Profiler for MemoryProfiler {
232232
let size = ALLOC.count() / 1024;
233233
println!("; allocated {} KiB <<<<<<<<<<<<<<<<<<<<<<", size);
234234
}
235-
}
235+
}

rust/floe/src/floe_result.rs

Lines changed: 11 additions & 47 deletions
Original file line numberDiff line numberDiff line change
@@ -13,8 +13,6 @@
1313
// See the License for the specific language governing permissions and
1414
// limitations under the License.
1515

16-
use std::{array::TryFromSliceError, num::TryFromIntError, slice::GetDisjointMutError};
17-
1816
use hmac::digest::InvalidLength;
1917

2018
/// Result type used for all FLOE operations
@@ -28,16 +26,11 @@ pub enum Error {
2826
* This is always a result of buggy calling code.
2927
*/
3028
InvalidInput,
31-
/**
32-
* The FLOE library encountered an internal error which should not be possible.
33-
* This is always a result of a bug in FLOE.
34-
*/
35-
UnexpectedInternalError(Option<Box<dyn std::error::Error>>),
3629
/**
3730
* A dependency returned an unexpected error.
3831
* This is always a result of a bug in FLOE or one of FLOE's dependencies.
3932
*/
40-
UnexpectedDependencyError(Box<dyn std::error::Error>),
33+
UnexpectedDependencyError,
4134
/**
4235
* FLOE expected more segments but did not receive them.
4336
*/
@@ -72,64 +65,35 @@ pub enum Error {
7265
BadTag,
7366
}
7467

75-
impl Error {
76-
#[cfg(test)]
77-
pub(crate) fn internal<E: std::error::Error + 'static>(err: E) -> Error {
78-
Error::UnexpectedInternalError(Some(Box::new(err)))
79-
}
80-
}
81-
8268
impl std::error::Error for Error {
8369
fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
84-
match self {
85-
Self::UnexpectedDependencyError(err) => Some(err.as_ref()),
86-
Self::UnexpectedInternalError(err) => err.as_deref(),
87-
_ => None,
88-
}
70+
None
8971
}
9072
}
9173

9274
impl From<aead::Error> for Error {
93-
fn from(err: aead::Error) -> Self {
94-
Error::UnexpectedDependencyError(Box::new(err))
75+
fn from(_: aead::Error) -> Self {
76+
Error::UnexpectedDependencyError
9577
}
9678
}
9779

9880
impl From<InvalidLength> for Error {
99-
fn from(err: InvalidLength) -> Self {
100-
Error::UnexpectedDependencyError(Box::new(err))
81+
fn from(_: InvalidLength) -> Self {
82+
Error::UnexpectedDependencyError
10183
}
10284
}
10385

104-
impl From<TryFromSliceError> for Error {
105-
fn from(err: TryFromSliceError) -> Self {
106-
Error::UnexpectedInternalError(Some(Box::new(err)))
86+
impl From<rand::rngs::SysError> for Error {
87+
fn from(_: rand::rngs::SysError) -> Self {
88+
Error::UnexpectedDependencyError
10789
}
108-
// This error has got to be our own fault
109-
}
110-
111-
impl From<GetDisjointMutError> for Error {
112-
fn from(err: GetDisjointMutError) -> Self {
113-
Error::UnexpectedInternalError(Some(Box::new(err)))
114-
}
115-
// This error has got to be our own fault
116-
}
117-
118-
impl From<TryFromIntError> for Error {
119-
fn from(err: TryFromIntError) -> Self {
120-
Error::UnexpectedInternalError(Some(Box::new(err)))
121-
}
122-
// This error has got to be our own fault
12390
}
12491

12592
impl std::fmt::Display for Error {
12693
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
12794
match self {
128-
Error::UnexpectedInternalError(err) => {
129-
write!(f, "An unexpected internal error occurred {err:?}")
130-
}
131-
Error::UnexpectedDependencyError(err) => {
132-
write!(f, "An unexpected dependency error occurred: {err}")
95+
Error::UnexpectedDependencyError => {
96+
write!(f, "An unexpected dependency error occurred")
13397
}
13498
Error::InvalidInput => write!(f, "Invalid input"),
13599
Error::Truncated => write!(f, "Input truncated. Final segment not found."),

rust/floe/src/implementation.rs

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -175,7 +175,9 @@ impl FloeSequentialCryptor for FloeSequentialDecryptor {
175175
});
176176
}
177177
let segment_length_header =
178-
u32::from_be_bytes(input[..SEGMENT_LENGTH_PREFIX_LENGTH].try_into()?);
178+
u32::from_be_bytes(input[..SEGMENT_LENGTH_PREFIX_LENGTH].try_into().expect(
179+
"This is safe because SEGMENT_LENGTH_PREFIX_LENGTH is the proper length for u32",
180+
));
179181
if (segment_length_header as usize) == input.len() {
180182
// We've hit the last segment and our caller hasn't noticed.
181183
return self.process_last_segment(input, output);
@@ -204,7 +206,7 @@ impl FloeSequentialCryptor for FloeSequentialDecryptor {
204206
expected: self.get_output_size(),
205207
});
206208
}
207-
let input_size = u32::from_be_bytes(input[..SEGMENT_LENGTH_PREFIX_LENGTH].try_into()?);
209+
let input_size = u32::from_be_bytes(input[..SEGMENT_LENGTH_PREFIX_LENGTH].try_into().expect("This is safe because we know that SEGMENT_LENGTH_PREFIX_LENGTH is the proper length for u32"));
208210
if (input_size as usize) != input.len() {
209211
return Err(Error::MalformedSegment);
210212
}

rust/floe/src/interface.rs

Lines changed: 9 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ use crate::{FloeParameterSpec, Result};
2020
* Specific implementations may be *more* flexible in what they accept.
2121
* ```rust
2222
* use floe::{Error, FloeKey, FloeSequentialCryptor, FloeSequentialDecryptor, FloeSequentialEncryptor, GCM256_IV256_1M, Result};
23-
*
23+
*
2424
* // Normally you'd save your key in some safe location. But for the demo we'll generate a random one
2525
* // GCM256_IV256_1M is a generally useful chunk size
2626
* let sample_key = FloeKey::new_random(GCM256_IV256_1M);
@@ -29,18 +29,18 @@ use crate::{FloeParameterSpec, Result};
2929
* // We'll just use an all one plaintext for the demo and large enough to be multiple segments
3030
* let plaintext = vec![1u8; 3 * 1024 * 1024 + 512];
3131
* let aad = b"This is some aad";
32-
*
33-
* let ciphertext = encryptData(&sample_key, &plaintext, aad);
32+
*
33+
* let ciphertext = encrypt_data(&sample_key, &plaintext, aad);
3434
* assert!(ciphertext.is_ok());
3535
* let ciphertext = ciphertext.unwrap();
36-
*
36+
*
3737
* // Finally, decrypt the result
38-
* let decrypted = decryptData(&sample_key, &ciphertext, aad);
38+
* let decrypted = decrypt_data(&sample_key, &ciphertext, aad);
3939
* //assert!(decrypted.is_ok());
4040
* let decrypted = decrypted.unwrap();
4141
* assert_eq!(decrypted, plaintext);
42-
*
43-
* fn encryptData(key: &FloeKey, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
42+
*
43+
* fn encrypt_data(key: &FloeKey, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
4444
* let mut encryptor = FloeSequentialEncryptor::new(key, aad)?;
4545
* let mut result = encryptor.get_header().to_vec();
4646
* let mut buff = vec![0u8; encryptor.get_output_size()];
@@ -63,8 +63,8 @@ use crate::{FloeParameterSpec, Result};
6363
* }
6464
* Ok(result)
6565
* }
66-
*
67-
* fn decryptData(key: &FloeKey, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
66+
*
67+
* fn decrypt_data(key: &FloeKey, data: &[u8], aad: &[u8]) -> Result<Vec<u8>> {
6868
* let header_length = key.get_parameters().get_header_length();
6969
* let header = &data[..header_length];
7070
* let ciphertext = &data[header_length..];

rust/floe/src/lib.rs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,12 +20,12 @@
2020
//! It is described in greater detail both in the primary specification repository
2121
//! at [github.com/Snowflake-Labs/floe-specification](https://www.github.com/Snowflake-Labs/floe-specification)
2222
//! and at [c2sp.org/FLOE](https://c2sp.org/FLOE).
23-
//!
23+
//!
2424
//! We recommend that most developers use the streaming interfaces as implemented by
2525
//! [FloeSequentialEncryptor] and [FloeSequentialDecryptor] as they are much harder to misuse.
2626
//! More advanced users can directly use [FloeEncryptor] and [FloeDecryptor] if full random-access
2727
//! authenticated encryption is needed.
28-
//!
28+
//!
2929
//! <div class="warning">The random-access APIs do not directly protect you against truncation attacks
3030
//! or prevent you from incorrectly encrypting the same segment multiple times.</div>
3131

0 commit comments

Comments
 (0)