@@ -6,6 +6,7 @@ use chacha20poly1305::{
6
6
} ;
7
7
use lazy_static:: lazy_static;
8
8
use pin_project:: pin_project;
9
+ use rayon:: prelude:: * ;
9
10
use secrecy:: { ExposeSecret , SecretVec } ;
10
11
use std:: cmp;
11
12
use std:: convert:: TryInto ;
@@ -53,9 +54,9 @@ impl Nonce {
53
54
self . 0 = u128:: from ( val) << 8 ;
54
55
}
55
56
56
- fn increment_counter ( & mut self ) {
57
+ fn increment_counter ( & mut self , by : usize ) {
57
58
// Increment the 11-byte counter
58
- self . 0 += 1 << 8 ;
59
+ self . 0 += ( by as u128 ) << 8 ;
59
60
if self . 0 >> ( 8 * 12 ) != 0 {
60
61
panic ! ( "We overflowed the nonce!" ) ;
61
62
}
@@ -196,26 +197,29 @@ impl Stream {
196
197
let num_chunks = chunks. len ( ) ;
197
198
let mut encrypted = vec ! [ 0 ; chunks_len + TAG_SIZE * num_chunks] ;
198
199
199
- for ( i , ( encrypted , chunk ) ) in encrypted
200
+ encrypted
200
201
. chunks_mut ( ENCRYPTED_CHUNK_SIZE )
201
202
. zip ( chunks)
202
203
. enumerate ( )
203
- {
204
- if i + 1 == num_chunks {
205
- self . nonce . set_last ( last) . unwrap ( ) ;
206
- }
204
+ . par_bridge ( )
205
+ . for_each_with ( self . nonce , |nonce, ( i, ( encrypted, chunk) ) | {
206
+ nonce. increment_counter ( i) ;
207
+ if i + 1 == num_chunks {
208
+ nonce. set_last ( last) . unwrap ( ) ;
209
+ }
207
210
208
- let ( buffer, tag) = encrypted. split_at_mut ( chunk. len ( ) ) ;
209
- buffer. copy_from_slice ( chunk) ;
210
- tag. copy_from_slice (
211
- self . aead
212
- . encrypt_in_place_detached ( & self . nonce . to_bytes ( ) . into ( ) , & [ ] , buffer)
213
- . expect ( "we will never hit chacha20::MAX_BLOCKS because of the chunk size" )
214
- . as_slice ( ) ,
215
- ) ;
211
+ let ( buffer, tag) = encrypted. split_at_mut ( chunk. len ( ) ) ;
212
+ buffer. copy_from_slice ( chunk) ;
213
+ tag. copy_from_slice (
214
+ self . aead
215
+ . encrypt_in_place_detached ( & nonce. to_bytes ( ) . into ( ) , & [ ] , buffer)
216
+ . expect ( "we will never hit chacha20::MAX_BLOCKS because of the chunk size" )
217
+ . as_slice ( ) ,
218
+ ) ;
219
+ } ) ;
216
220
217
- self . nonce . increment_counter ( ) ;
218
- }
221
+ self . nonce . increment_counter ( num_chunks ) ;
222
+ self . nonce . set_last ( last ) . unwrap ( ) ;
219
223
220
224
Ok ( encrypted)
221
225
}
@@ -250,7 +254,7 @@ impl Stream {
250
254
)
251
255
. map_err ( |_| io:: Error :: new ( io:: ErrorKind :: InvalidData , "decryption error" ) ) ?;
252
256
253
- self . nonce . increment_counter ( ) ;
257
+ self . nonce . increment_counter ( 1 ) ;
254
258
}
255
259
256
260
Ok ( SecretVec :: new ( decrypted) )
0 commit comments