SHA256 encryption

SHA256 encryptionIntroductionCharacteristics of SHA256Application ScenarioCode AnalysisCode Key Points

 

Introduction

SHA256 is a commonly used hash algorithm in cryptography and belongs to the SHA-2 (Secure Hash Algorithm 2) family. It can convert input data of any length into an output of fixed length (256 bits/32 bytes), which is usually represented by a 64-bit hexadecimal number.

Characteristics of SHA256

Application Scenario

  1. Digital Signature
  2. Data integrity verification
  3. Password Storage
  4. Blockchain Technology
  5. Random Number Generation

Code Analysis

The routine code execution flow chart is as follows

image-20250401182122573

The complete code is located in [Source Code/02.Basic/11.sha256.py]

Code Key Points

  1. There are two ways to create a hash object :

    • First create an empty object, then use update()the method to add data
    • Pass data directly when creating an object
  2. Incremental hashing :

    • The first part of the code shows update()the use of the method, which can be called multiple times to add data
    • This is equivalent to computing the hash value of the data concatenated together (i.e. 130 zero bytes)
  3. Hash result acquisition :

    • digest()The method returns a hash value in binary format
    • You can also use hexdigest()to get the hexadecimal string representation
  4. Hash verification :

    • The code ensures that the algorithm is implemented correctly by comparing the generated hash value with the expected value
    • Demonstrates the deterministic nature of the SHA256 algorithm (the same input always produces the same output)
  5. Input size and hash value :

    • Regardless of the input data size (65 bytes, 130 bytes, or 1024 bytes), the output is always 32 bytes

Although SHA256 is powerful, it should be used in combination with other techniques such as salting and key stretching in certain security scenarios (such as password storage).