public static string SHA256(string Input, ref string LogText, bool DEBUG = false) { SHA256Context CTX = new SHA256Context(); CTX.W = new uint[64]; CTX.H = new uint[8]; if (DEBUG) { LogText = LogText + $"p={Input}\n"; } string[] Blocks = GetBlocks(Input); SHA256Init(ref CTX, DefaultHValue); foreach (string Block in Blocks) { byte[] InputBytes = StringToByteArray(Block); uint[] InputBlock = ByteArrayToUintArray(InputBytes); if (DEBUG) { LogText = LogText + "# begin of next block\n"; LogText = LogText + $"H \t=+0x{SHA256ToString(CTX)}\n"; LogText = LogText + $"W \t=+0x{Block}\n"; } SHA256ProcessBlock(ref CTX, InputBlock, ref LogText, DEBUG); } return(SHA256ToString(CTX)); }
private static void SHA256Init(ref SHA256Context CTX, string H) { if (H != DefaultHValue) { int xPos = H.IndexOf('x'); if (xPos != -1) { string HCopy = H.Substring(xPos + 1, (H.Length - xPos - 1)); if (HCopy.Length == 64) { CTX.H[0] = Convert.ToUInt32(HCopy.Substring(0, 8), 16); CTX.H[1] = Convert.ToUInt32(HCopy.Substring(8, 8), 16); CTX.H[2] = Convert.ToUInt32(HCopy.Substring(16, 8), 16); CTX.H[3] = Convert.ToUInt32(HCopy.Substring(24, 8), 16); CTX.H[4] = Convert.ToUInt32(HCopy.Substring(32, 8), 16); CTX.H[5] = Convert.ToUInt32(HCopy.Substring(40, 8), 16); CTX.H[6] = Convert.ToUInt32(HCopy.Substring(48, 8), 16); CTX.H[7] = Convert.ToUInt32(HCopy.Substring(56, 8), 16); } } } else { CTX.H[0] = 0x6a09e667; CTX.H[1] = 0xbb67ae85; CTX.H[2] = 0x3c6ef372; CTX.H[3] = 0xa54ff53a; CTX.H[4] = 0x510e527f; CTX.H[5] = 0x9b05688c; CTX.H[6] = 0x1f83d9ab; CTX.H[7] = 0x5be0cd19; } }
private static string SHA256ToString(SHA256Context CTX) { string H0 = CTX.H[0].ToString("x8"); string H1 = CTX.H[1].ToString("x8"); string H2 = CTX.H[2].ToString("x8"); string H3 = CTX.H[3].ToString("x8"); string H4 = CTX.H[4].ToString("x8"); string H5 = CTX.H[5].ToString("x8"); string H6 = CTX.H[6].ToString("x8"); string H7 = CTX.H[7].ToString("x8"); return($"{H0}{H1}{H2}{H3}{H4}{H5}{H6}{H7}"); }
private static void SHA256ProcessBlock(ref SHA256Context CTX, uint[] Value, ref string LogText, bool DEBUG = false) { uint A, B, C, D, E, F, G, H, t1, t2; for (int i = 0; i < 16; i++) { CTX.W[i] = Value[i]; } for (int i = 16; i < 64; i++) { CTX.W[i] = SSIG1(CTX.W[i - 2]) + CTX.W[i - 7] + SSIG0(CTX.W[i - 15]) + CTX.W[i - 16]; } A = CTX.H[0]; B = CTX.H[1]; C = CTX.H[2]; D = CTX.H[3]; E = CTX.H[4]; F = CTX.H[5]; G = CTX.H[6]; H = CTX.H[7]; for (int i = 0; i < 64; i++) { t1 = H + BSIG1(E) + CH(E, F, G) + K[i] + CTX.W[i]; t2 = BSIG0(A) + MAJ(A, B, C); H = G; G = F; F = E; E = D + t1; D = C; C = B; B = A; A = t1 + t2; if (DEBUG) { LogText = LogText + $"R[{i.ToString("D2")}]=+0x{A.ToString("x8")}{B.ToString("x8")}{C.ToString("x8")}{D.ToString("x8")}{E.ToString("x8")}{F.ToString("x8")}{G.ToString("x8")}{H.ToString("x8")}\n"; } } CTX.H[0] += A; CTX.H[1] += B; CTX.H[2] += C; CTX.H[3] += D; CTX.H[4] += E; CTX.H[5] += F; CTX.H[6] += G; CTX.H[7] += H; }