0

I am trying to understand hashing in python and in particular sha256.

I have a standard python function that uses the hashlib for creating a sha256 hash like this:

import hashlib

def hash_password(password):
    """Hashes a password using the SHA-256 algorithm."""
    hash_object = hashlib.sha256()
    hash_object.update(password.encode('utf-8'))
    return hash_object.hexdigest()

password = 'password123'
hashed_password = hash_password(password)
print(hashed_password)

I was expecting a function with a clear process.

So i navigate the the definition of .sha256() in the hashlib.pyi module to find this:

def sha256(string: ReadableBuffer = b"", *, usedforsecurity: bool = True) -> _Hash: ...

But i simply do not understand what this is doing ? it looks like a function that takes arguments and does nothing ....

So what does this function do please ?

D.L
  • 4,339
  • 5
  • 22
  • 45
  • 1
    Do you know what pyi files are and what they are for? See: [What does "i" represent in Python .pyi extension?](https://stackoverflow.com/q/41734836/555045) – harold May 14 '23 at 21:27

1 Answers1

0

The sha256() function in the hashlib module of Python is used to create a SHA256 hash object. It is a constructor method for the SHA256 hash algorithm. The sha256() function takes a byte-like input and returns a hashed value.

the file .pyi is a python interface.

Refer to the documentation if needed
https://docs.python.org/3/library/hashlib.html

desertnaut
  • 57,590
  • 26
  • 140
  • 166
Ali Massoud
  • 135
  • 1
  • 10
  • But the function has nothing in it, only elipses `...` which is the bit i dont understand ? – D.L May 14 '23 at 21:31
  • 1
    in Python interfaces, we write blueprints, so what you are seeing is an abstract method, which defines the infrastructure of the method. I hope this helps buddy! – Ali Massoud May 14 '23 at 21:41
  • 3
    @D.L In this case, it means that the function is actually implemented in C (at least in the most common Python implementation of CPython). You can find the Source code for the module on GitHub [here](https://github.com/python/cpython/blob/main/Modules/sha2module.c), where it just says it provides an interface to the NIST algorithms. There are various tutorials online in text and video form explaining [how SHA256 works](https://craft-crypto.com/how-does-sha-256-work/). – nigh_anxiety May 14 '23 at 22:15