ในบทช่วยสอนนี้ เราจะเรียนรู้เกี่ยวกับ hashlib โมดูลที่ทำให้เรามี SHA.(Secure Hash Algorithms) . ที่แตกต่างกัน คือชุดของฟังก์ชันแฮชเข้ารหัส
มาติดตั้งโมดูลโดยพิมพ์คำสั่งต่อไปนี้
pip install hashlib
เราสามารถดูอัลกอริธึมที่มีอยู่ใน hashlib โมดูลโดยใช้ algorithms_guaranteed ชุด. มาดูกันโดยรันโค้ดต่อไปนี้
ตัวอย่าง
# importing the hashlib module import hashlib # printing available algorithms print(hashlib.algorithms_guaranteed)
ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
{'sha256', 'sha512', 'sha224', 'shake_256', 'blake2s', 'shake_128', 'sha384', 'sha3_384', 'sha3_512', 'sha3_224', 'md5', 'sha3_256', 'sha1', 'blake2b'} ตัวอย่าง
มาดูตัวอย่างวิธีการใช้อัลกอริธึม sha256 กัน
# importing the hashlib module
import hashlib
# initialinzing a string
# the string will be hashed using the 'sha256'
name = 'Tutorialspoint'
# convert the string to bytes using 'encode'
# hash functions only accepts encoded strings
encoded_name = name.encode()
# Now, pass the encoded_name to the **sha256** function
hashed_name = hashlib.sha256(encoded_name)
# we have hashed object
# we can't understand it
# print the hexadecimal version using 'hexdigest()' method
print("Object:", hashed_name)
print("Hexadecimal format:", hashed_name.hexdigest()) ผลลัพธ์
หากคุณเรียกใช้โค้ดด้านบน คุณจะได้ผลลัพธ์ดังต่อไปนี้
Object: <sha256 HASH object @ 0x000002A416E1BAE0> Hexadecimal format: 447c2329228a452aa77102dc7d4eca0ee4c6d52a17e9c17408f8917e51e 3
บทสรุป
คุณสามารถใช้อัลกอริทึมที่เหลือที่คล้ายกับ sha256 . หากคุณมีคำถามใดๆ ในบทช่วยสอน โปรดระบุในส่วนความคิดเห็น