gethash.py
파일의 원본해시를 알려줌
import hashlib
filename = "Game.cfg"
sha256_hash = hashlib.sha256()
try:
with open(filename, "rb") as f:
# Read and update hash string value in blocks of 4K
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
original_hash = sha256_hash.hexdigest()
print(f"'{filename}' 파일의 원본 SHA-256 해시: : {original_hash}")
except FileNotFoundError:
print(f"'{filename}' 파일을 찾을 수 없습니다.")

해시값 확인
integrity_check.py
기존값과 비교해서 달라진걸 확인시켜주는 코드
import hashlib
target_file = "Game.cfg"
original_hash = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855"
def do_current_hash(filename):
sha256_hash = hashlib.sha256()
try:
with open(filename, "rb") as f:
for byte_block in iter(lambda: f.read(4096), b""):
sha256_hash.update(byte_block)
return sha256_hash.hexdigest()
except FileNotFoundError:
return None
print(f"{target_file} 파일의 무결성 검사를 시작합니다.")
current_hash = do_current_hash(target_file)
if current_hash is None:
print(f"'{target_file}' 파일을 찾을 수 없습니다.")
else:
print(f" - 원본 해시값 : {original_hash}")
print(f" - 현재 해시값 : {current_hash}")
if original_hash == current_hash:
print(f"'{target_file}' 파일에 이상이 없습니다.")
else:
print(f"'{target_file}' 파일이 변조되었습니다!")

그냥 실행하면 이상없음이 나온다.
Game.cfg에 hihi를 적고 다시 실행해보면

변조되었다고 알려주는걸 확인할 수 있다.
'python study' 카테고리의 다른 글
| 파이썬 turtle로 거북이 경주시키기 (0) | 2024.09.29 |
|---|---|
| 파이썬으로 블랙잭 만들기 (2) | 2024.09.08 |
| 파이썬으로 계산기 만들기 (0) | 2024.09.07 |
| Python으로 행맨게임 만들기 (0) | 2024.09.05 |
| 파이썬 공부 1 (0) | 2024.05.21 |