11use std:: fmt;
22
3- use aes_gcm :: {
4- AeadCore , Aes256Gcm , Nonce ,
5- aead :: { generic_array :: GenericArray , Aead , KeyInit , OsRng } ,
3+ use chacha20poly1305 :: {
4+ aead :: { Aead , AeadCore , KeyInit , OsRng , generic_array :: GenericArray } ,
5+ XChaCha20Poly1305 , XNonce ,
66} ;
77use cookie:: Key ;
88use serde:: { de, ser, Deserialize , Serialize } ;
99
1010use crate :: request:: { Outcome , Request , FromRequest } ;
1111
12- const NONCE_LEN : usize = 12 ;
12+ const NONCE_LEN : usize = 24 ; // 192-bit
1313const KEY_LEN : usize = 32 ;
1414
1515#[ derive( Debug ) ]
@@ -218,14 +218,12 @@ impl SecretKey {
218218 . try_into ( )
219219 . map_err ( |_| Error :: KeyLengthError ) ?;
220220
221- // Create a new AES-256-GCM instance with the provided key
222- let aead = Aes256Gcm :: new ( GenericArray :: from_slice ( & key ) ) ;
221+ let cipher = XChaCha20Poly1305 :: new ( GenericArray :: from_slice ( & key) ) ;
222+ let nonce = XChaCha20Poly1305 :: generate_nonce ( & mut OsRng ) ;
223223
224- // Generate a random nonce
225- let nonce = Aes256Gcm :: generate_nonce ( & mut OsRng ) ;
226-
227- // Encrypt the plaintext using the nonce
228- let ciphertext = aead. encrypt ( & nonce, value. as_ref ( ) ) . map_err ( |_| Error :: EncryptionError ) ?;
224+ let ciphertext = cipher
225+ . encrypt ( & nonce, value. as_ref ( ) )
226+ . map_err ( |_| Error :: EncryptionError ) ?;
229227
230228 // Prepare a vector to hold the nonce and ciphertext
231229 let mut encrypted_data = Vec :: with_capacity ( NONCE_LEN + ciphertext. len ( ) ) ;
@@ -248,19 +246,18 @@ impl SecretKey {
248246
249247 // Split the decoded data into nonce and ciphertext
250248 let ( nonce, ciphertext) = encrypted. split_at ( NONCE_LEN ) ;
251- let nonce = Nonce :: from_slice ( nonce) ;
249+ let nonce = XNonce :: from_slice ( nonce) ;
252250
253251 // Convert the encryption key to a fixed-length array
254252 let key: [ u8 ; KEY_LEN ] = self . key
255253 . encryption ( )
256254 . try_into ( )
257255 . map_err ( |_| Error :: KeyLengthError ) ?;
258256
259- // Create a new AES-256-GCM instance with the provided key
260- let aead = Aes256Gcm :: new ( GenericArray :: from_slice ( & key) ) ;
257+ let cipher = XChaCha20Poly1305 :: new ( GenericArray :: from_slice ( & key) ) ;
261258
262259 // Decrypt the ciphertext using the nonce
263- let decrypted = aead . decrypt ( nonce, ciphertext)
260+ let decrypted = cipher . decrypt ( nonce, ciphertext)
264261 . map_err ( |_| Error :: DecryptionError ) ?;
265262
266263 Ok ( decrypted)
0 commit comments