Program: B.E.
Branch: ECE
Course: Cryptography & Network Security Semester/Section: 7th Sem ‘C’
Course Code: 18EC7DEECS Date:
A Report on
SECURE HASH ALGORITHM (SHA-256)
Submitted by
D SAI KUMAR 1DS18EC116
S REDDY THRINATH 1DS18EC140
S SRI HARSHA PHANI 1DS18EC151
Faculty In-charge
Prof. SAPNA P.J
Associate Prof., ECE Dept
CONTENTS
1.Introduction------------------------------------------------------------------6
2.Characteristics---------------------------------------------------------------6
3.Properties---------------------------------------------------------------------7
4.Applications------------------------------------------------------------------7
5.Algorithm---------------------------------------------------------------------8
6.Program-----------------------------------------------------------------------14
7.Simulation Results----------------------------------------------------------19
8.Conclusion-------------------------------------------------------------------20
9.References-------------------------------------------------------------------20
2
3
INTRODUCTION
A cryptographic hash function is an algorithm that takes input strings of arbitrary (typically very large)
length and maps these to short fixed length output strings. The progress in cryptanalysis of cryptographic hash
functions has been quite slow until very recently, the cryptographic community has been surprised at the progress
of cryptanalysis of hash functions, such as an attack on MD5 [23] for finding collisions and an attack with a new
strategy on SHA-0 [2, 3] and an attack for finding multi-collisions. However, these techniques are not applicable
to SHA-256 due to its more complex message schedule and round function. SHA-256 is a cryptographic hash
function which was proposed in 2000 as a new generation of SHA functions and was adopted as FIPS standard in
2002 [18]. SHA-256 is constructed from MD(Merkle-Damgard) -construction and Davis Meyer mode. The
compression function of SHA-256 has 64 rounds, two kinds of non-linear functions, cyclic rotations, and round-
dependent constants. The hash value calculated by SHA-256 is 256 bits long.
SHA-2 includes significant changes from its predecessor, SHA-1. The SHA-2 family consists of six hash
functions with digests (hash values) that are 224, 256, 384 or 512 bits:[5] SHA-224, SHA-256, SHA-384, SHA-
512, SHA-512/224, SHA-512/256. SHA-256 and SHA-512 are novel hash functions computed with eight 32-bit
and 64-bit words, respectively. They use different shift amounts and additive constants, but their structures are
otherwise virtually identical, differing only in the number of rounds. SHA-224 and SHA-384 are truncated
versions of SHA-256 and SHA-512 respectively, computed with different initial values. SHA-512/224 and SHA-
512/256 are also truncated versions of SHA-512.
CHARACTERISTICS
Message Length: The length of the cleartext should be less than 264 bits. The size needs to be in the
comparison area to keep the digest as random as possible.
Digest Length: The length of the hash digest should be 256 bits in SHA 256 algorithm, 512 bits in SHA-512,
and so on. Bigger digests usually suggest significantly more calculations at the cost of speed and space.
Irreversible: By design, all hash functions such as the SHA 256 are irreversible. You should neither get a
plaintext when you have the digest beforehand nor should the digest provide its original value when you pass
it through the hash function again.
6
PROPERTIES
APPLICATIONS
Digital Signature Verification: Digital signatures follow asymmetric encryption methodology to verify the
authenticity of a document/file. Hash algorithms like SHA 256 go a long way in ensuring the verification of the
signature.
Password Hashing: As discussed above, websites store user passwords in a hashed format for two benefits. It
helps foster a sense of privacy, and it lessens the load on the central database since all the digests are of similar
size.
SSL Handshake: The SSL handshake is a crucial segment of the web browsing sessions, and it’s done using SHA
functions. It consists of your web browsers and the web servers agreeing on encryption keys and hashing
authentication to prepare a secure connection.
Integrity Checks: As discussed above, verifying file integrity has been using variants like SHA 256 algorithm
and the MD5 algorithm. It helps maintain the full value functionality of files and makes sure they were not altered
in transit.
7
ALGORITHM
Steps in SHA-256 Algorithm
We can divide the complete process into five different segments, as mentioned below:
Padding Bits
It adds some extra bits to the message, such that the length is exactly 64 bits short of a multiple of 512. During the
addition, the first bit should be one, and the rest of it should be filled with zeroes. The message is padded so that
its length is congruent to 448 modulo 512 [length ≡ 448 (mod 512)]. Padding is always added, even if the message
is already of the desired length. Thus, the number of padding bits is in the range of 1 to 512. The padding consists
of a single 1-bit followed by the necessary number of 0-bits.
Padding Length
We can add 64 bits of data now to make the final plaintext a multiple of 512. We can calculate these 64 bits of
characters by applying the modulus to your original cleartext without the padding. A block of 64 bits is appended to
the message. This block is treated as an unsigned 64-bit integer (most significant byte first) and contains the length of the
original message (before the padding). The outcome of the first two steps yields a message that is an integer multiple of 160
bits in length.
8
Initialising the Buffers:
We need to initialize the default values for eight buffers to be used in the rounds as follows (first 32 bits of the
fractional parts of the square roots of the first 8 primes 2...19):
We also need to store 64 different keys in an array, ranging from K [0] to K [63]. They are initialized as follows
(first 32 bits of the fractional parts of the cube roots of the first 64 primes 2...311):
9
Compression Functions:
The entire message gets broken down into multiple blocks of 512 bits each. It puts each block through 64
rounds of operation, with the output of each block serving as the input for the following block. The entire process
is as follows.
While the value of K[i] in all those rounds is pre-initialized, W[i] is another input that is calculated
individually for each block, depending on the number of iterations being processed at the moment.
1
0
Illustration of each round:
The 256-bit input is loaded into 8 registers (A, B, C, D, E, F, G, H) and the 512-bit message block is divided into
16 words of 32 bits (W0 ...W15) and these words are expanded to a sequence of 64 words through the message
schedule.
Basic operations:
• Boolean operations AND, XOR and OR, denoted by ∧, ⊕ and ∨, respectively.
• Bitwise complement, denoted by ¯.
• Integer addition modulo 2^32, denoted by A + B.
Each of them operates on 32-bit words. For the last operation, binary words are interpreted as
integers written in base 2.
• RotR (A, n) denotes the circular right shift of n bits of the binary word A.
1
1
• ShR (A, n) denotes the right shift of n bits of the binary word A.
• A|| B denotes the concatenation of the binary words A and B.
Block decomposition:
For each block M ∈ {0, 1} 512, 64 words of 32 bits each are constructed as follows:
• The first 16 are obtained by splitting M in 32-bit blocks
M = W1||W2|| · · · ||W15|| W16
• The remaining 48 are obtained with the formula:
Wi = σ1(Wi−2) + Wi−7 + σ0(Wi−15) + Wi−16, 17 ≤ i ≤ 64.
Hash computation:
• First, eight variables are set to their initial values, given by the first 32 bits of the fractional part
of the square roots of the first 8 prime numbers:
H1 (0) = 0x6a09e667
H2 (0) = 0xbb67ae85
H3 (0) = 0x3c6ef372
H4 (0) = 0xa54ff53a
H5 (0) = 0x510e527f
H6 (0) = 0x9b05688c
H7 (0) = 0x1f83d9ab
H8 (0) = 0x5be0cd19
• Next, the blocks M (1), M (2), . . ., M (N) are processed one at a time:
For t = 1 to N
– construct the 64 blocks Wi from M(t), as explained above
– set (a, b, c, d, e, f, g, h) = (H(t−1) 1, H2(t−1), H3(t−1), H4(t−1), H5(t−1), H6(t−1), H 7(t−1) , H8(t−1))
– do 64 rounds consisting of:
T1 = h + Σ1 (e) + Ch (e, f, g) + Ki + Wi
T2 = Σ0(a) + Maj (a, b, c)
h=g
g=f
f=e
1
2
e= d + T1
d=c
c=b
b=a
a = T1 + T2
We assume that the length of the message can be represented by a 64-bit integer.
compute the new value of Hj(t)
H1(t) = H1(t−1) + a
H2(t) = H2(t−1) + b
H3(t) = H3(t−1) + c
H4(t) =H4(t−1) + d
H5(t)= H5(t−1) + e
H6(t) = H6(t−1) + f
H7(t) = H7(t−1) + g
H8(t) = H8(t−1) + h
The hash of the message is the concatenation of the variables HiN after the last block has been processed
H = H1(N) ||H2(N)||H3(N)||H4(N)||H5(N)||H6(N)||H7(N) ||H8(N).
Functions and constants:
The algorithm uses the functions:
Ch (X, Y, Z) = (X ∧ Y) ⊕ (~X ∧ Z),
Maj (X, Y, Z) = (X ∧ Y) ⊕ (X ∧ Z) ⊕ (Y ∧ Z),
Σ0(X) = RotR (X, 2) ⊕ RotR (X, 13) ⊕ RotR (X, 22),
Σ1(X) = RotR (X, 6) ⊕ RotR (X, 11) ⊕ RotR (X, 25),
σ0(X) = RotR (X, 7) ⊕ RotR (X, 18) ⊕ ShR (X, 3),
σ1(X) = RotR (X, 17) ⊕ RotR (X, 19) ⊕ ShR (X, 10).
1
3
With each iteration, the final output of the block serves as the input for the next block. The entire cycle keeps
repeating until we reach the last 512-bit block, and we then consider its output as the final hash digest. This digest
will be of the length 256-bit, as per the name of this algorithm.
PYTHON PROGRAM
K=[
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
]
def generate_hash(message: bytearray) -> bytearray:
"""Return a SHA-256 hash from the message passed.
The argument should be a bytes, bytearray, or
string object."""
if isinstance(message, str):
message = bytearray(message, 'ascii')
elif isinstance(message, bytes):
message = bytearray(message)
elif not isinstance(message, bytearray):
raise TypeError
# Padding
length = len(message) * 8 # len(message) is number of BYTES!!!
message.append(0x80)
while (len(message) * 8 + 64) % 512 != 0:
1
4
message.append(0x00)
message += length.to_bytes(8, 'big') # pad to 8 bytes or 64 bits
assert (len(message) * 8) % 512 == 0, "Padding did not complete properly!"
# Parsing
blocks = [] # contains 512-bit chunks of message
for i in range(0, len(message), 64): # 64 bytes is 512 bits
blocks.append(message[i:i+64])
# Setting Initial Hash Value
h0 = 0x6a09e667
h1 = 0xbb67ae85
h2 = 0x3c6ef372
h3 = 0xa54ff53a
h5 = 0x9b05688c
h4 = 0x510e527f
h6 = 0x1f83d9ab
h7 = 0x5be0cd19
# SHA-256 Hash Computation
for message_block in blocks:
# Prepare message schedule
message_schedule = []
for t in range(0, 64):
if t <= 15:
# adds the t'th 32 bit word of the block,
# starting from leftmost word
# 4 bytes at a time
1
5
message_schedule.append(bytes(message_block[t*4:(t*4)+4]))
else:
term1 = _sigma1(int.from_bytes(message_schedule[t-2], 'big'))
term2 = int.from_bytes(message_schedule[t-7], 'big')
term3 = _sigma0(int.from_bytes(message_schedule[t-15], 'big'))
term4 = int.from_bytes(message_schedule[t-16], 'big')
# append a 4-byte byte object
schedule = ((term1 + term2 + term3 + term4) % 2**32).to_bytes(4, 'big')
message_schedule.append(schedule)
assert len(message_schedule) == 64
# Initialize working variables
a = h0
b = h1
c = h2
d = h3
e = h4
f = h5
g = h6
h = h7
# Iterate for t=0 to 63
for t in range(64):
t1 = ((h + _capsigma1(e) + _ch(e, f, g) + K[t] +
int.from_bytes(message_schedule[t], 'big')) % 2**32)
t2 = (_capsigma0(a) + _maj(a, b, c)) % 2**32
1
6
h=g
g=f
f=e
e = (d + t1) % 2**32
d=c
c=b
b=a
a = (t1 + t2) % 2**32
# Compute intermediate hash value
h0 = (h0 + a) % 2**32
h1 = (h1 + b) % 2**32
h2 = (h2 + c) % 2**32
h3 = (h3 + d) % 2**32
h4 = (h4 + e) % 2**32
h5 = (h5 + f) % 2**32
h6 = (h6 + g) % 2**32
h7 = (h7 + h) % 2**32
return ((h0).to_bytes(4, 'big') + (h1).to_bytes(4, 'big') +
(h2).to_bytes(4, 'big') + (h3).to_bytes(4, 'big') +
(h4).to_bytes(4, 'big') + (h5).to_bytes(4, 'big') +
(h6).to_bytes(4, 'big') + (h7).to_bytes(4, 'big'))
def _sigma0(num: int):
"""As defined in the specification."""
num = (_rotate_right(num, 7) ^
_rotate_right(num, 18) ^
(num >> 3))
return num
def _sigma1(num: int):
1
7
"""As defined in the specification."""
num = (_rotate_right(num, 17) ^
_rotate_right(num, 19) ^
(num >> 10))
return num
def _capsigma0(num: int):
"""As defined in the specification. #sigma (A)"""
num = (_rotate_right(num, 2) ^
_rotate_right(num, 13) ^
_rotate_right(num, 22))
return num
def _capsigma1(num: int):
"""As defined in the specification. #sigma (E)"""
num = (_rotate_right(num, 6) ^
_rotate_right(num, 11) ^
_rotate_right(num, 25))
return num
def _ch(x: int, y: int, z: int):
"""As defined in the specification."""
return (x & y) ^ (~x & z)
def _maj(x: int, y: int, z: int):
"""As defined in the specification."""
return (x & y) ^ (x & z) ^ (y & z)
def _rotate_right(num: int, shift: int, size: int = 32):
"""Rotate an integer right."""
return (num >> shift) | (num << size - shift)
1
8
if __name__ == "__main__":
p=input()
print(generate_hash(p).hex()
Simulation Results
Using in-built Hashlib:
In Python by using the hash lib we can get the directly any sha output directly.
import hashlib
print ("The available algorithms are : ", end ="")
print (hashlib.algorithms_guaranteed)
data = input('Enter plaintext data: ')
str = data
result = hashlib.sha256(str.encode())
print("The hexadecimal equivalent of SHA256 is :”)
print(result.hexdigest())
OUTPUT:
CONCLUSION
In this report on SHA 256 algorithm, we learned the basics of hashing, the applications of hashing, the origin of
SHA, its working, and the places this algorithm finds use.
1
9
REFERENCES
1. https://www.researchgate.net/publication/ 221274799_Analysis_of_a_SHA-256_Variant (PDF)
2. https://www.simplilearn.com/tutorials/cyber-security-tutorial/sha-256- algorithm
3. http://www.prajval.in/edudetail/252/1923/Write-a-detailed-note-onSecure-Hash-Algorithm--
4. https://stackoverflow.com/questions/7321694/sha-256-implementationin-python
5. https://komodoplatform.com/en/academy/sha-256-algorithm/
6. https://www.slideshare.net/datacenterbob/the-sha-hashing-algorithm
2
0
2
1
2
2