#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdarg.h>
#include <time.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/types.h>
#include "stdint.h"
#include "ld_sha.h"
#include "sha2.h"
//void SHA256_Init(SHA256_CTX *);
//void SHA256_Update(SHA256_CTX*, const uint8_t*, size_t);
//void SHA256_Final(uint8_t[SHA256_DIGEST_LENGTH], SHA256_CTX*);
//char* SHA256_End(SHA256_CTX*, char[SHA256_DIGEST_STRING_LENGTH]);


//#include "base64.h"

#ifdef WIN32
#define vsnprintf _vsnprintf
#define snprintf _snprintf
#endif

static const char sha256_salt_prefix[] = "$5$";
static const char sha256_rounds_prefix[] = "rounds=";
#define MAX(a,b) ((a)<(b)) ? (b) : (a)
#define MIN(a,b) ((a)>(b)) ? (b) : (a)

/* Maximum salt string length.  */
#define SALT_LEN_MAX 16
/* Default number of rounds if not explicitly specified.  */
#define ROUNDS_DEFAULT 5000
/* Minimum number of rounds.  */
#define ROUNDS_MIN 1000
/* Maximum number of rounds.  */
#define ROUNDS_MAX 999999999

/* Table with characters for base64 transformation.  */
static const char b64t[64] =
"./0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
#define bool int
#ifdef WIN32
#define alloca _alloca
#define ALIGN32 __declspec( align( 32 ) )
#define ALIGN32X 
#define ALIGNINT 4
#define myassert(x) if (x) abort();
#else
#define myassert(x) if (x) abort();
#define ALIGNINT __alignof__ (uint32_t)
#define ALIGN32X __attribute__ ((__aligned__ (__alignof__ (uint32_t))))
#define ALIGN32 

#endif



#define false 0
#define true (!false)
char *__stpncpy (char *dst, const char *src, size_t len)
{
  size_t n = strlen (src);
  if (n > len)
    n = len;
  return strncpy (dst, src, len) + n;
}


void *zmempcpy (char *dest, char *src, int len)
{
	memcpy(dest,src,len);
	return dest+len;
}
void b64_from_24bit (unsigned int b2, unsigned int b1, unsigned int b0,	       int n,int *pbuflen, char **pcp )
{
	unsigned int w = (b2 << 16) | (b1 << 8) | b0;
	while (n-- > 0 && (*pbuflen) > 0)
	{
		*(*pcp)++ = b64t[w & 0x3f];
		--(*pbuflen);
		w >>= 6;
	}
}


char * sha256_crypt_r (char *key, char *salt, char *buffer, int buflen)
{
ALIGN32  unsigned char alt_result[32] ALIGN32X;
ALIGN32  unsigned char temp_result[32] ALIGN32X;
  size_t salt_len;
  size_t key_len;
  size_t cnt;
  char *cp;
  char *copied_key = NULL;
  char *copied_salt = NULL;
  char *p_bytes;
  char *s_bytes;
  /* Default number of rounds.  */
  size_t rounds = ROUNDS_DEFAULT;
  bool rounds_custom = false;
  size_t alloca_used = 0;
  char *free_key = NULL;
  char *free_pbytes = NULL;
  SHA256_CTX ctx;
  SHA256_CTX alt_ctx;

  /* Find beginning of salt string.  The prefix should normally always
     be present.  Just in case it is not.  */
  if (strncmp (sha256_salt_prefix, salt, sizeof (sha256_salt_prefix) - 1) == 0)
    /* Skip salt prefix.  */
    salt += sizeof (sha256_salt_prefix) - 1;

  if (strncmp (salt, sha256_rounds_prefix, sizeof (sha256_rounds_prefix) - 1)
      == 0)
    {
      const char *num = salt + sizeof (sha256_rounds_prefix) - 1;
      char *endp;
      unsigned long int srounds = strtoul (num, &endp, 10);
      if (*endp == '$')
	{
	  salt = endp + 1;
	  rounds = MAX (ROUNDS_MIN, MIN (srounds, ROUNDS_MAX));
	  rounds_custom = true;
	}
    }

  salt_len = MIN (strcspn (salt, "$"), SALT_LEN_MAX);
  key_len = strlen (key);

  if ((key - (char *) 0) % ALIGNINT != 0)
    {
      char *tmp;

	{
	  free_key = tmp = (char *) malloc (key_len + ALIGNINT);
	  if (tmp == NULL)
	    return NULL;
	}

      key = copied_key =
	memcpy (tmp + ALIGNINT
		- (tmp - (char *) 0) % ALIGNINT,
		key, key_len);
      myassert ((key - (char *) 0) % ALIGNINT == 0);
    }

  if ((salt - (char *) 0) % ALIGNINT != 0)
    {
      char *tmp = (char *) alloca (salt_len + ALIGNINT);
      alloca_used += salt_len + ALIGNINT;
      salt = copied_salt =
	memcpy (tmp + ALIGNINT
		- (tmp - (char *) 0) % ALIGNINT,
		salt, salt_len);
      myassert ((salt - (char *) 0) % ALIGNINT == 0);
    }
// AFTER HERE

  /* Prepare for the real work.  */
  SHA256_Init(&ctx);

  /* Add the key string.  */
  SHA256_Update (&ctx,key, key_len);

  /* The last part is the salt string.  This must be at most 16
     characters and it ends at the first `$' character.  */
  SHA256_Update (&ctx,salt, salt_len);


  /* Compute alternate SHA256 sum with input KEY, SALT, and KEY.  The
     final result will be added to the first context.  */
  SHA256_Init(&alt_ctx);

  /* Add key.  */
  SHA256_Update (&alt_ctx,key, key_len);

  /* Add salt.  */
  SHA256_Update (&alt_ctx,salt, salt_len);

  /* Add key again.  */
  SHA256_Update (&alt_ctx,key, key_len);

  /* Now get result of this (32 bytes) and add it to the other
     context.  */
  SHA256_Final(alt_result,&alt_ctx); // ,alt_result);


  /* Add for any character in the key one byte of the alternate sum.  */
  for (cnt = key_len; cnt > 32; cnt -= 32)
    SHA256_Update(&ctx,alt_result, 32);

  SHA256_Update (&ctx,alt_result, cnt);

  /* Take the binary representation of the length of the key and for every
     1 add the alternate sum, for every 0 the key.  */
  for (cnt = key_len; cnt > 0; cnt >>= 1)
    if ((cnt & 1) != 0)
      SHA256_Update (&ctx,alt_result, 32);
    else
      SHA256_Update (&ctx,key, key_len);

  /* Create intermediate result.  */
  SHA256_Final (alt_result,&ctx);

  /* Start computation of P byte sequence.  */
  SHA256_Init( &alt_ctx);

  /* For every character in the password add the entire password.  */
  for (cnt = 0; cnt < key_len; ++cnt)
    SHA256_Update (&alt_ctx,key, key_len);

  /* Finish the digest.  */
  SHA256_Final(temp_result,&alt_ctx);

  /* Create byte sequence P.  */
      free_pbytes = cp = p_bytes = (char *)malloc (key_len);
      if (free_pbytes == NULL)
	{
	  free (free_key);
	  return NULL;
	}

  for (cnt = key_len; cnt >= 32; cnt -= 32)
    cp = zmempcpy (cp, (char*) temp_result, 32);
  memcpy (cp, temp_result, cnt);

  /* Start computation of S byte sequence.  */
  SHA256_Init (&alt_ctx);

  /* For every character in the password add the entire password.  */
	  for (cnt = 0; cnt < (size_t) (16 + alt_result[0]); ++cnt) {
	  
	    SHA256_Update (&alt_ctx,salt, salt_len);
	  
	  }

	  
  /* Finish the digest.  */
  SHA256_Final (temp_result,&alt_ctx);

	  
  /* Create byte sequence S.  */
  cp = s_bytes = alloca (salt_len);
  for (cnt = salt_len; cnt >= 32; cnt -= 32)
    cp = zmempcpy (cp, temp_result, 32);
  memcpy (cp, temp_result, cnt);

  /* Repeatedly run the collected hash value through SHA256 to burn
     CPU cycles.  */
	  

//return NULL; // finding bug..
  for (cnt = 0; cnt < rounds; ++cnt)
    {
      /* New context.  */
      SHA256_Init(&ctx);

	  
      /* Add key or last result.  */
      if ((cnt & 1) != 0)
	SHA256_Update (&ctx,p_bytes, key_len);
      else
	SHA256_Update(&ctx,alt_result, 32);

      /* Add salt for numbers not divisible by 3.  */
      if (cnt % 3 != 0)
	SHA256_Update (&ctx,s_bytes, salt_len);

	  
      /* Add key for numbers not divisible by 7.  */
      if (cnt % 7 != 0)
	SHA256_Update (&ctx,p_bytes, key_len);

      /* Add key or last result.  */
      if ((cnt & 1) != 0)
	SHA256_Update (&ctx,alt_result, 32);
      else
	SHA256_Update (&ctx,p_bytes, key_len);

      /* Create intermediate result.  */
      SHA256_Final(alt_result,&ctx);
    }


  /* Now we can construct the result string.  It consists of three
     parts.  */
  cp = __stpncpy (buffer, sha256_salt_prefix, MAX (0, buflen));
  buflen -= sizeof (sha256_salt_prefix) - 1;

  if (rounds_custom)
    {
      int n = snprintf (cp, MAX (0, buflen), "%s%zu$",
			sha256_rounds_prefix, rounds);
      cp += n;
      buflen -= n;
    }

  cp = __stpncpy (cp, salt, MIN ((size_t) MAX (0, (size_t) buflen), salt_len));
  buflen -= MIN ((size_t) MAX (0, (size_t) buflen), salt_len);

  if (buflen > 0)
    {
      *cp++ = '$';
      --buflen;
    }

  b64_from_24bit (alt_result[0], alt_result[10], alt_result[20], 4,&buflen,&cp);
  b64_from_24bit (alt_result[21], alt_result[1], alt_result[11], 4,&buflen,&cp);
  b64_from_24bit (alt_result[12], alt_result[22], alt_result[2], 4,&buflen,&cp);
  b64_from_24bit (alt_result[3], alt_result[13], alt_result[23], 4,&buflen,&cp);
  b64_from_24bit (alt_result[24], alt_result[4], alt_result[14], 4,&buflen,&cp);
  b64_from_24bit (alt_result[15], alt_result[25], alt_result[5], 4,&buflen,&cp);
  b64_from_24bit (alt_result[6], alt_result[16], alt_result[26], 4,&buflen,&cp);
  b64_from_24bit (alt_result[27], alt_result[7], alt_result[17], 4,&buflen,&cp);
  b64_from_24bit (alt_result[18], alt_result[28], alt_result[8], 4,&buflen,&cp);
  b64_from_24bit (alt_result[9], alt_result[19], alt_result[29], 4,&buflen,&cp);
  b64_from_24bit (0, alt_result[31], alt_result[30], 3,&buflen,&cp);
  if (buflen <= 0)
    {
      //__set_errno (ERANGE);
      errno = (ERANGE);
      buffer = NULL;
    }
  else
    *cp = '\0';		/* Terminate the string.  */

  /* Clear the buffer for the intermediate result so that people
     attaching to processes or reading core dumps cannot get any
     information.  We do it in this way to clear correct_words[]
     inside the SHA256 implementation as well.  */
#ifndef USE_NSS
  SHA256_Init(&ctx);
  SHA256_Final(alt_result,&ctx);
  memset (&ctx, '\0', sizeof (ctx));
  memset (&alt_ctx, '\0', sizeof (alt_ctx));
#endif
  memset (temp_result, '\0', sizeof (temp_result));
  memset (p_bytes, '\0', key_len);
  memset (s_bytes, '\0', salt_len);
  if (copied_key != NULL)
    memset (copied_key, '\0', key_len);
  if (copied_salt != NULL)
    memset (copied_salt, '\0', salt_len);

  free (free_key);
  free (free_pbytes);
  return buffer;
}

