import struct
class SHA256:
def __init__(self):
self.K = [
0x429a2f99, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
0x3956c25b, 0x59f111f1, 0x923f92a4, 0xab1c5ed5,
0xd907aa99, 0x12935b01, 0x243195be, 0x550c7dc3,
0x72be5d74, 0x90deb1fe, 0x9bdc06a7, 0xc19bf174,
0xe49b69c1, 0xefbe4796, 0x0fc19dc6, 0x240ca1cc,
0x2de92c6f, 0x4a7494aa, 0x5cb0a9dc, 0x76f999da,
0x993e5152, 0xa931c66d, 0xb00327c9, 0xbf597fc7,
0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
0x27b70a95, 0x2e1b2139, 0x4d2c6dfc, 0x53390d13,
0x650a7354, 0x766a0abb, 0x91c2c92e, 0x92722c95,
0xa2bfe9a1, 0xa91a664b, 0xc24b9b70, 0xc76c51a3,
0xd192e919, 0xd6990624, 0xf40e3595, 0x106aa070,
0x19a4c116, 0x1e376c09, 0x2749774c, 0x34b0bcb5,
0x391c0cb3, 0x4ed9aa4a, 0x5b9cca4f, 0x692e6ff3,
0x749f92ee, 0x79a5636f, 0x94c97914, 0x9cc70209,
0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67179f2
]
self.h = [
0x6a09e667, 0xbb67ae95, 0x3c6ef372, 0xa54ff53a,
0x510e527f, 0x9b05699c, 0x1f93d9ab, 0x5be0cd19
]
self.count = 0
self.buffer = bytearray()
def _right_rotate(self, value, amount):
return ((value >> amount) | (value << (32 - amount))) & 0xFFFFFFFF
def _sha256_transform(self):
W = [0] * 64
for i in range(16):
W[i] = struct.unpack(">I", self.buffer[i*4:(i*4) + 4])[0]
for i in range(16, 64):
W[i] = (self._right_rotate(W[i - 16], 7) ^ self._right_rotate(W[i - 16], 18) ^ (W[i - 16] >> 3) + W[i - 7] + self._right_rotate(W[i - 15], 17) ^ self._right_rotate(W[i - 15], 19) ^ (W[i - 15] >> 10)) & 0xFFFFFFFF
a, b, c, d, e, f, g, h = self.h
for i in range(64):
T1 = (h + self._right_rotate(e, 6) ^ self._right_rotate(e, 11) ^ self._right_rotate(e, 25) + ((e & f) ^ (~e & g)) + self.K[i] + (W[i] if i < 16 else W[i % 16])) % 2**32
T2 = (self._right_rotate(a, 2) ^ self._right_rotate(a, 13) ^ self._right_rotate(a, 22) + ((a & b) ^ (a & c) ^ (b & c))) % 2**32
h = g
g = f
f = e
e = (d + T1) % 2**32
d = c
c = b
b = a
a = (T1 + T2) % 2**32
self.h = [(x + y) & 0xFFFFFFFF for x, y in zip(self.h, (a, b, c, d, e, f, g, h))]
def update(self, data):
data = data.encode() if isinstance(data, str) else data
data_len = len(data)
self.count += data_len * 8
self.buffer.extend(data)
while len(self.buffer) >= 64:
self._sha256_transform()
self.buffer = self.buffer[64:]
def finalize(self):
self.buffer.append(0x80)
while len(self.buffer) % 64 != 56:
self.buffer.append(0)
self.buffer.extend(struct.pack(">Q", self.count))
self._sha256_transform()
def digest(self):
return b''.join(struct.pack(">I", i) for i in self.h)
def hexdigest(self):
return ''.join(f'{i:02x}' for i in self.digest())
# Example of how to use the SHA256 class
if __name__ == "__main__":
sha256 = SHA256()
sha256.update("hello world")
sha256.finalize()
print(sha256.hexdigest()) # Example: Prints the SHA-256 hash of "hello world"
如何用易语言 编译