Skip to content

Python:hashlib

MD5

Single file:

print hashlib.md5(open(full_path, 'rb').read()).hexdigest()

Multiple files:

import hashlib
[(fname, hashlib.md5(open(fname, 'rb').read()).digest()) for fname in fnamelst]

SHA256

import hashlib
hash_object = hashlib.sha256(b'Hello World')
hex_dig = hash_object.hexdigest()
print(hex_dig)

pbkdf2_hmac

함수 정의:

# -*- coding: utf-8 -*-

from hashlib import pbkdf2_hmac
from typing import Final

DEFAULT_PBKDF2_HMAC_HASH_NAME: Final[str] = "sha256"
DEFAULT_PBKDF2_HMAC_ITERATIONS: Final[int] = 100000


def encrypt_password(password: str, salt: bytes) -> bytes:
    return pbkdf2_hmac(
        DEFAULT_PBKDF2_HMAC_HASH_NAME,
        bytes.fromhex(password),
        salt,
        DEFAULT_PBKDF2_HMAC_ITERATIONS,
    )

사용:

import os

salt = os.urandom(16)
hash = encrypt_password("enter-your-password", salt)

Using OpenSSL Algorithms

import hashlib
hash_object = hashlib.new('DSA')
hash_object.update(b'Hello World')
print(hash_object.hexdigest())

Favorite site

References


  1. Hashing_Strings_with_Python-Python_Central.pdf