@@ -118,6 +118,25 @@ const STATE_WORDS: usize = 16;
118118/// State initialization constant ("expand 32-byte k")
119119const CONSTANTS : [ u32 ; 4 ] = [ 0x6170_7865 , 0x3320_646e , 0x7962_2d32 , 0x6b20_6574 ] ;
120120
121+ const DATA_LAYOUT : [ usize ; 16 ] = [ 0 , 5 , 10 , 15 , 4 , 9 , 14 , 3 , 12 , 1 , 6 , 11 , 8 , 13 , 2 , 7 ] ;
122+
123+ const DATA_LAYOUT_INVERSE : [ usize ; 16 ] = {
124+ let mut index = [ 0 ; 16 ] ;
125+ let mut i = 0 ;
126+ while i < 16 {
127+ let mut inverse = 0 ;
128+ while inverse < 16 {
129+ if DATA_LAYOUT [ inverse] == i {
130+ index[ i] = inverse;
131+ break ;
132+ }
133+ inverse += 1 ;
134+ }
135+ i += 1 ;
136+ }
137+ index
138+ } ;
139+
121140/// The Salsa20 core function.
122141pub struct SalsaCore < R : Unsigned > {
123142 /// Internal state of the core function
@@ -133,7 +152,7 @@ impl<R: Unsigned> SalsaCore<R> {
133152 /// Other users generally should not use this method.
134153 pub fn from_raw_state ( state : [ u32 ; STATE_WORDS ] ) -> Self {
135154 Self {
136- state,
155+ state : core :: array :: from_fn ( |i| state [ DATA_LAYOUT [ i ] ] ) ,
137156 rounds : PhantomData ,
138157 }
139158 }
@@ -177,7 +196,7 @@ impl<R: Unsigned> KeyIvInit for SalsaCore<R> {
177196 state[ 15 ] = CONSTANTS [ 3 ] ;
178197
179198 Self {
180- state,
199+ state : core :: array :: from_fn ( |i| state [ DATA_LAYOUT [ i ] ] ) ,
181200 rounds : PhantomData ,
182201 }
183202 }
@@ -199,13 +218,14 @@ impl<R: Unsigned> StreamCipherSeekCore for SalsaCore<R> {
199218
200219 #[ inline( always) ]
201220 fn get_block_pos ( & self ) -> u64 {
202- ( self . state [ 8 ] as u64 ) + ( ( self . state [ 9 ] as u64 ) << 32 )
221+ ( self . state [ DATA_LAYOUT_INVERSE [ 8 ] ] as u64 )
222+ + ( ( self . state [ DATA_LAYOUT_INVERSE [ 9 ] ] as u64 ) << 32 )
203223 }
204224
205225 #[ inline( always) ]
206226 fn set_block_pos ( & mut self , pos : u64 ) {
207- self . state [ 8 ] = ( pos & 0xffff_ffff ) as u32 ;
208- self . state [ 9 ] = ( ( pos >> 32 ) & 0xffff_ffff ) as u32 ;
227+ self . state [ DATA_LAYOUT_INVERSE [ 8 ] ] = ( pos & 0xffff_ffff ) as u32 ;
228+ self . state [ DATA_LAYOUT_INVERSE [ 9 ] ] = ( ( pos >> 32 ) & 0xffff_ffff ) as u32 ;
209229 }
210230}
211231
0 commit comments