//----------------------------------------------------------------------------------------------------------------------------------------------
// to compile on command line:
//
// cc -O3 -o sha256inv sha256inv.cpp
//
//----------------------------------------------------------------------------------------------------------------------------------------------
// 6/30/2017  Nathan Mariels
//            (mt autocode to C ver 0.34)
//
// input :    block <16 words>
//
// output:    input data
//            internal states of compression function for 64 rounds of sha256
//            hash of input block
//
//            internal states, rounds 1-47 reset to all zero
//
//            internal states, rounds 1-64, with 1-47 being recreated with compression inverse function
//            input data - recreated from rounds 48-64
//
//----------------------------------------------------------------------------------------------------------------------------------------------



//----------------------------------------------------------------------------------------------------------------------------------------------
// include

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

//----------------------------------------------------------------------------------------------------------------------------------------------
// macros

#define			loop(X,Y)                   for(X=0;X<(Y);X++)
#define			fill(X,Y,Z)                 for(int filltemp=0;filltemp<(Y);filltemp++) X[filltemp]=(Z)
#define			copy(X,Y,Z)                 for(int copytemp=0;copytemp<(Z);copytemp++) X[copytemp]=Y[copytemp]
#define			c_char_to_hex(X)            ((((X)>='0')&&((X)<='9'))?((X)-'0'):(((((X)|32)>='a')&&(((X)|32)<='f'))?(((X)|32)-'a'+10):0))

#define			sha256_rightrotate(X,Y)     (((X)>>(Y))|((X)<<(32-(Y))))
#define			sha256_rightshift(X,Y)      (((X)>>(Y)))
#define			sha256_ws0(X)               (sha256_rightrotate((X), 7)^sha256_rightrotate((X),18)^sha256_rightshift((X),3))
#define			sha256_ws1(X)               (sha256_rightrotate((X),17)^sha256_rightrotate((X),19)^sha256_rightshift((X),10))
#define			sha256_s0(X)                (sha256_rightrotate((X), 2)^sha256_rightrotate((X),13)^sha256_rightrotate((X),22))
#define			sha256_s1(X)                (sha256_rightrotate((X), 6)^sha256_rightrotate((X),11)^sha256_rightrotate((X),25))
#define			sha256_xa(W,X,Y,Z)          (((W)&(X))^((Y)&(Z)))

//----------------------------------------------------------------------------------------------------------------------------------------------
// types

typedef	unsigned int	uint32;

//----------------------------------------------------------------------------------------------------------------------------------------------
// const

const uint32		ivec_k[8]    = {    0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 };

const uint32	 	sha256_k[64] = {    0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
                                            0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
                                            0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
                                            0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
                                            0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
                                            0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
                                            0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
                                            0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 };

//----------------------------------------------------------------------------------------------------------------------------------------------
// structs

typedef struct mt_sha256_state {
	uint32		a[68];
	uint32		b[68];
} mt_sha256_state;

//----------------------------------------------------------------------------------------------------------------------------------------------
// globals


//----------------------------------------------------------------------------------------------------------------------------------------------
// prototypes

uint32 mt_cmd_line_get_hex (const char *ptr);
int main (int argc, const char * argv[]);
void mt_print_rounds (mt_sha256_state *hs);
void mt_print_hash (mt_sha256_state *hs);

//----------------------------------------------------------------------------------------------------------------------------------------------
// code

int main (int argc, const char * argv[])
{
	mt_sha256_state   *hs, *h1, sha_state;
	int               i;

	hs = &sha_state;
	h1 = &sha_state;
	
	// block data
	if (argc == 1) {
		printf ("\nno args - using example of \"abc\"\n");

		hs->b[4] = 0x61626380;
		loop (i, 14) hs->b[i+5] = 0;
		hs->b[19] = 0x18;
	}
	else if (argc == 17) {
		loop (i, 16) hs->b[i+4] = mt_cmd_line_get_hex (argv[i+1]);
	} else {
		printf ("\nsha256inv - computes the SHA256 hash of a single block of data in raw format,");
		printf ("\nshowing internal states, then clears first 48 rounds and recreates input data.\n\n");
		
		printf ("block : <N bits - data> <1 bit - end bit = 1> <(447 - N) bits zero padding> <64 bit - length in bits>\n\n");
		printf ("example 1: ./sha256inv 61626380 0 0 0 0 0 0 0 0 0 0 0 0 0 0 18\n");
		printf ("This will compute the SHA256 hash of the string \"abc\".  It should be: BA7816BF .... F20015AD\n\n");
		
		return 0;
	}
	
	// ivec
	loop (i, 4) {
		hs->a[i] = ivec_k [3-i];
		hs->b[i] = ivec_k [7-i];
	}

	
	printf ("\nblock: ");
	loop (i, 16) printf (" %08X", h1->b[i+4]);

	loop (i, 64) {
		if ((i > 13) && (i < 62)) hs->b[i+6]  += sha256_ws1(hs->b[i+4]);
		if ((i > 8)  && (i < 57)) hs->b[i+11] += hs->b[i+4];
		if ((i > 0)  && (i < 49)) hs->b[i+19] += sha256_ws0(hs->b[i+4]);
		if (            (i < 48)) hs->b[i+20] = hs->b[i+4];

		hs->b[i+4] = hs->b[i+4] + sha256_k[i] + hs->a[i] + hs->b[i] + sha256_s1 (hs->b[i+3]) + (hs->b[i+3] & hs->b[i+2]) + (~hs->b[i+3] & hs->b[i+1]);
		hs->a[i+4] = hs->b[i+4] - hs->a[i] + sha256_s0 (hs->a[i+3]) + ((((hs->a[i+3] ^ hs->a[i+1]) & hs->a[i+2]) ^ (hs->a[i+1] & hs->a[i+3])));
	}
	
	mt_print_rounds (hs);
	mt_print_hash (hs);
	
	//----------------------------------
	
	printf ("\n\n\n---- zero first 48 rounds ----\n");
	loop (i, 48) {
		hs->b[i] = 0;
		hs->a[i] = 0;
	}
	
	mt_print_rounds (hs);
	
	
	printf ("\n\n\n---- rebuild first 48 rounds ----\n");

	for (i=47; i>=0; i--) {
		hs->a[i] = hs->b[i+4] - hs->a[i+4] + sha256_s0 (hs->a[i+3]) + ((((hs->a[i+3] ^ hs->a[i+1]) & hs->a[i+2]) ^ (hs->a[i+1] & hs->a[i+3])));
		hs->b[i] =   sha256_s1 (hs->b[i+19])       - sha256_s1 (hs->b[i+12])        - sha256_s1 (hs->b[i+3])
                   + sha256_k[i+16]                - sha256_k[i+9]                  - sha256_k[i]
                   - hs->b[i+20]                   + hs->b[i+16]                    + hs->b[i+13]                   - hs->b[i+9]                    + hs->b[i+4]
                   + hs->a[i+16]                   - hs->a[i+9]                     - hs->a[i]
                   + ( hs->b[i+19] & hs->b[i+18])  - ( hs->b[i+12] & hs->b[i+11])   - ( hs->b[i+3]  & hs->b[i+2])
                   + (~hs->b[i+19] & hs->b[i+17])  - (~hs->b[i+12] & hs->b[i+10])   - (~hs->b[i+3]  & hs->b[i+1])
                   + sha256_ws0 (- hs->b[i+1]      - sha256_k[i+1]                  - hs->a[i+1]                    - sha256_s1 (hs->b[i+4])        - (hs->b[i+4]  & hs->b[i+3])  - (~hs->b[i+4]  & hs->b[i+2])  + hs->b[i+5])
                   + sha256_ws1 (- hs->b[i+14]     - sha256_k[i+14]                 - hs->a[i+14]                   - sha256_s1 (hs->b[i+17])       - (hs->b[i+17] & hs->b[i+16]) - (~hs->b[i+17] & hs->b[i+15]) + hs->b[i+18]);
		
	}
	mt_print_rounds (hs);
	mt_print_hash (hs);
	
	printf ("\n\n\n---- rebuild input data ----\n");

	loop (i, 16) printf (" %08X", hs->b[i+4] - hs->b[i] - sha256_k[i] - hs->a[i] - sha256_s1 (hs->b[i+3]) - (hs->b[i+3] & hs->b[i+2]) - (~hs->b[i+3] & hs->b[i+1]));
	printf ("\n\n");
	
	return (0);
}

//----------------------------------------------------------------------------------------------------------------------------------------------

void mt_print_hash (mt_sha256_state *hs)
{
	int		i;
	
	printf ("\n\nhash : ");
	loop (i, 4)	printf (" %08X", ivec_k[i  ] + hs->a[67-i]);
	loop (i, 4)	printf (" %08X", ivec_k[i+4] + hs->b[67-i]);
}

//----------------------------------------------------------------------------------------------------------------------------------------------

void mt_print_rounds (mt_sha256_state *hs)
{
	int		i, j;
	
	printf ("\n\nRound      A        B        C        D        E        F        G        H");
	loop (i, 64) {
		printf ("\n  %2d   ", i + 1);
		
		loop (j, 4)	printf (" %08X", hs->a[i-j+3]);
		loop (j, 4)	printf (" %08X", hs->b[i-j+3]);
	}
}

//----------------------------------------------------------------------------------------------------------------------------------------------

uint32 mt_cmd_line_get_hex (const char *ptr)
{
	int		x = 0;
	uint32	r = 0;
	
	while ((*ptr) && (x < 8)) {
		r = r << 4;
		r = r + c_char_to_hex (*ptr);
		ptr++;
		x++;
	}
	return (r);
}


//----------------------------------------------------------------------------------------------------------------------------------------------