今天來嘗試用python的方法來自己算4位數字密碼
import hashlib
import random
def generate_random_password():
# 生成隨機數作為密碼
return str(random.randint(0, 9999))
def hash_password(password):
# 使用SHA-256哈希函數計算密碼的hash值
return hashlib.sha256(password.encode()).hexdigest()
def find_collision(target_hash):
attempts = 0
while True:
random_password = generate_random_password()
hashed_password = hash_password(random_password)
attempts += 1
if hashed_password == target_hash:
return random_password, attempts
if __name__ == "__main__":
target_password = generate_random_password()
target_hash = hash_password(target_password)
collision_password, attempts = find_collision(target_hash)
print(f"目標密碼: {target_password}")
print(f"目標哈希值: {target_hash}")
print(f"碰撞密碼: {collision_password}")
print(f"經過 {attempts} 次嘗試找到碰撞密碼")
目標密碼: 4362
目標哈希值: 43c33bc8917f644809b960cca4aad47030703bdc9e1a526d90a4636627ef0038
碰撞密碼: 4362
經過 5539 次嘗試找到碰撞密碼
心得:colab 0秒就跑完,由此可見純數字短密碼真的很不安全