K230 SHA256 Tutorial#
What is SHA256?#
SHA256 (Secure Hash Algorithm 256) is a commonly used hash algorithm with a fixed output length of 256 bits (32 bytes), commonly used for:
Data integrity verification (e.g., files, communications)
Digital signatures and identity authentication
Blockchain and cryptography-related systems
Interface Overview#
Interface Name |
Description |
|---|---|
|
Create SHA256 object |
|
Input data to the hash object (can be called multiple times) |
|
Return the computed hash value (bytes) |
Example: Using SHA256 Hash Computation#
The following example demonstrates how to perform SHA256 hash computation using K230’s uhashlib module.
Example 1: One-time Data Update#
import uhashlib
# 初始化 SHA256 对象
obj = uhashlib.sha256()
# 输入消息
msg = b'\x45\x11\x01\x25\x0e\xc6\xf2\x66\x52\x24\x9d\x59\xdc\x97\x4b\x73' \
b'\x61\xd5\x71\xa8\x10\x1c\xdf\xd3\x6a\xba\x3b\x58\x54\xd3\xae\x08' \
b'\x6b\x5f\xdd\x45\x97\x72\x1b\x66\xe3\xc0\xdc\x5d\x8c\x60\x6d\x96' \
b'\x57\xd0\xe3\x23\x28\x3a\x52\x17\xd1\xf5\x3f\x2f\x28\x4f\x57\xb8'
# 正确的参考哈希值(来自硬件加速器)
expected = b'\x1a\xaa\xf9\x28\x5a\xf9\x45\xb8\xa9\x7c\xf1\x4f\x86\x9b\x18\x90' \
b'\x14\xc3\x84\xf3\xc7\xc2\xb7\xd2\xdf\x8a\x97\x13\xbf\xfe\x0b\xf1'
# 哈希计算
obj.update(msg)
digest = obj.digest()
# 验证结果
print("SHA256 一次 update 测试成功:", digest == expected)
Example 2: Calling update() Multiple Times#
obj = uhashlib.sha256()
# 分两次输入数据
obj.update(b'hello')
obj.update(b'world')
# 正确的 SHA256 值
expected = b'\x93\x6a\x18\x5c\xaa\xa2\x66\xbb\x9c\xbe\x98\x1e\x9e\x05\xcb\x78' \
b'\xcd\x73\x2b\x0b\x32\x80\xeb\x94\x44\x12\xbb\x6f\x8f\x8f\x07\xaf'
digest = obj.digest()
print("SHA256 多次 update 测试成功:", digest == expected)
Example 3#
import uhashlib
import binascii
obj = uhashlib.sha256()
obj.update(b'helloworld')
print(binascii.hexlify(obj.digest()).decode())
Application Scenario Examples#
Scenario |
Description |
|---|---|
Communication Security Verification |
Verify whether received content has been tampered with via hash |
Firmware Integrity Verification |
Verify the hash of program image files or OTA packages |
Digital Signature |
Generate a digest for data to participate in signature operations |
Blockchain and Cryptography |
Commonly used in block hash calculations, Merkle trees, and other structures |
FAQ#
Q: Can
update()be called multiple times?
A: Yes. uhashlib.sha256() supports streaming data input and is suitable for handling large data or chunked reading scenarios.
Q: Can
update()still be called after invoking.digest()?
A: Not recommended. .digest() will end the current hash state. If you need to continue, please recreate the SHA256 object.
