chiark / gitweb /
missing.h : add bridge params
[elogind.git] / src / basic / siphash24.c
index 8f2f1f55348d654958ec12f7c28e18120498fe74..308e4230c5456257572df1821e153fa849370a66 100644 (file)
@@ -52,16 +52,7 @@ typedef uint8_t u8;
     (state)->v2 += (state)->v1; (state)->v1=ROTL((state)->v1,17); (state)->v1 ^= (state)->v2; (state)->v2=ROTL((state)->v2,32); \
   } while(0)
 
-struct siphash {
-  u64 v0;
-  u64 v1;
-  u64 v2;
-  u64 v3;
-  u64 padding;
-  size_t inlen;
-};
-
-static void siphash_init(struct siphash *state, const uint8_t k[16]) {
+void siphash_init(struct siphash *state, const uint8_t k[16]) {
   u64 k0, k1;
 
   k0 = U8TO64_LE( k );
@@ -76,15 +67,42 @@ static void siphash_init(struct siphash *state, const uint8_t k[16]) {
   state->inlen = 0;
 }
 
-static void siphash24_compress(const void *_in, size_t inlen, struct siphash *state) {
+void siphash24_compress(const void *_in, size_t inlen, struct siphash *state) {
   u64 m;
   const u8 *in = _in;
-  const u8 *end = in + inlen - ( inlen % sizeof( u64 ) );
-  const int left = inlen & 7;
+  const u8 *end = in + inlen;
+  int left = state->inlen & 7;
 
-  state->inlen = inlen;
+  /* update total length */
+  state->inlen += inlen;
 
-  for ( ; in != end; in += 8 )
+  /* if padding exists, fill it out */
+  if (left > 0) {
+    for ( ; in < end && left < 8; in ++, left ++ )
+      state->padding |= ( ( u64 )*in ) << (left * 8);
+
+    if (in == end && left < 8)
+      /* we did not have enough input to fill out the padding completely */
+      return;
+
+#ifdef DEBUG
+    printf( "(%3d) v0 %08x %08x\n", ( int )state->inlen, ( u32 )( state->v0 >> 32 ), ( u32 )state->v0 );
+    printf( "(%3d) v1 %08x %08x\n", ( int )state->inlen, ( u32 )( state->v1 >> 32 ), ( u32 )state->v1 );
+    printf( "(%3d) v2 %08x %08x\n", ( int )state->inlen, ( u32 )( state->v2 >> 32 ), ( u32 )state->v2 );
+    printf( "(%3d) v3 %08x %08x\n", ( int )state->inlen, ( u32 )( state->v3 >> 32 ), ( u32 )state->v3 );
+    printf( "(%3d) compress padding %08x %08x\n", ( int )state->inlen, ( u32 )( state->padding >> 32 ), ( u32 )state->padding );
+#endif
+    state->v3 ^= state->padding;
+    SIPROUND(state);
+    SIPROUND(state);
+    state->v0 ^= state->padding;
+
+    state->padding = 0;
+  }
+
+  end -= ( state->inlen % sizeof (u64) );
+
+  for ( ; in < end; in += 8 )
   {
     m = U8TO64_LE( in );
 #ifdef DEBUG
@@ -100,6 +118,8 @@ static void siphash24_compress(const void *_in, size_t inlen, struct siphash *st
     state->v0 ^= m;
   }
 
+  left = state->inlen & 7;
+
   switch( left )
   {
   case 7: state->padding |= ( ( u64 )in[ 6] )  << 48;
@@ -120,7 +140,7 @@ static void siphash24_compress(const void *_in, size_t inlen, struct siphash *st
   }
 }
 
-static u64 siphash24_finalize(struct siphash *state) {
+uint64_t siphash24_finalize(struct siphash *state) {
   u64 b;
 
   b = state->padding | (( ( u64 )state->inlen ) << 56);