Branch: Tag:

2016-01-26

2016-01-26 13:27:26 by Martin Nilsson <nilsson@fastmail.com>

Encrypt directly into result buffer.

260:    CVAR struct sha256_ctx sha_ctx;    CVAR uint8_t *key;    CVAR uint8_t *ctr; -  CVAR uint8_t *data; +        DECLARE_STORAGE;   
268:   #define AES256_KEY_SIZE (256>>3)   #endif    -  static void fortuna_generate(void) +  static void fortuna_generate(uint8_t *data)    { -  aes_encrypt(&THIS->aes_ctx, 16, THIS->data, THIS->ctr); +  aes_encrypt(&THIS->aes_ctx, 16, data, THIS->ctr);    INCREMENT(16, THIS->ctr);    }       static void fortuna_rekey(void)    { -  fortuna_generate(); -  memcpy(THIS->key, THIS->data, 16); -  fortuna_generate(); -  memcpy(THIS->key+16, THIS->data, 16); +  fortuna_generate(THIS->key); +  fortuna_generate(THIS->key+16);    aes_set_encrypt_key(&THIS->aes_ctx, AES256_KEY_SIZE, THIS->key);    }   
305:    PIKEFUN string(8bit) random_string(int len)    {    int stored = 0; -  struct string_builder s; +        if(len<0) Pike_error("Length has to be positive.\n"); -  init_string_builder_alloc(&s, len, 0); -  -  while( stored < len ) +  struct pike_string *s = begin_shared_string(len); +  uint8_t *str = (uint8_t *)s->str; +  while( (len-stored) >= 16 )    { -  fortuna_generate(); -  string_builder_binary_strcat(&s, (const char *)THIS->data, -  MINIMUM(16, (len-stored))); -  -  /* This should really be MINIMUM(16, (len-stored)) instead of -  16, but it is only less than 16 in the last round, so it -  doesn't matter if we rekey here or not. */ +  fortuna_generate(str);    stored += 16; -  +  str += 16;       if( !(stored % (1<<20)) )    fortuna_rekey();    }    -  /* Inverse of the above conditional, to avoid having fortuna_rekey -  applied twice in the rare condition that the string length is a -  multiple of 1<<20. */ -  if( (stored % (1<<20)) ) +  if( len>stored ) +  { +  uint8_t *buf = alloca(16); +  fortuna_generate(buf); +  memcpy(str, buf, len-stored); +  } +     fortuna_rekey();    -  RETURN finish_string_builder(&s); +  RETURN end_shared_string(s);    }       INIT
340:    THIS->key = xcalloc(1,32);    aes_set_encrypt_key(&THIS->aes_ctx, AES256_KEY_SIZE, THIS->key);    sha256_init(&THIS->sha_ctx); -  THIS->data = xalloc(16); +     }       EXIT
348:    {    free(THIS->ctr);    free(THIS->key); -  free(THIS->data); +     }   }