How to Encrypt Passwords in Python: MD5, SHA, HMAC and More
This article demonstrates how to implement common password‑encryption techniques in Python—including plain MD5, MD5 with salts, SHA1, SHA256, and HMAC—by wrapping them in a reusable class and showing sample code and output for each method.
Introduction
During automated testing I encountered encrypted API passwords.
The product required using the provided encryption algorithm without any special tricks.
Since the algorithm is known, encrypting the password before sending it is straightforward.
This article collects several encryption algorithms for future testing use.
Common Data
To simplify examples, a class is created to encapsulate the encryption methods:
# -*- coding:utf-8 -*-
# 作者:虫无涯
# 文件名称:test_pass.py
# 作用:常用的加密算法实现
# 联系:VX(NoamaNelson)
# 博客:https://blog.csdn.net/NoamaNelson
import hashlib
import hmac
class TestPass():
def __init__(self):
super(TestPass, self).__init__()
self.name = "admin"
self.password = "123456"
if __name__ == "__main__":
test_pass = TestPass()self.name simulates a username; self.password simulates a password.
MD5 Direct Encryption
MD5 is a common one‑way hash function producing a 128‑bit (32‑character hex) result.
Implementation uses Python's built‑in hashlib module.
def test_md5(self):
md = hashlib.md5(self.password.encode())
md5_pass = md.hexdigest()
print(f"密码{self.password}, md5直接加密后为:{md5_pass}")Output:
密码123456, md5直接加密后为:e10adc3949ba59abbe56e057f20f883eUsername and Password Combined MD5
Some systems hash the concatenation of username and password (lower‑cased) with MD5.
def test_md5_01(self):
data = (self.name + self.password).lower()
md = hashlib.md5(data.encode())
md5_pass = md.hexdigest()
print(f"密码{self.password},用户名{self.name}, md5组合加密后为:{md5_pass}")Output:
密码123456,用户名admin, md5组合加密后为:a66abb5684c45962d887564f08346e8dMD5 with Salt (Append Salt)
First generate a salt, then append it to the password before hashing.
def test_md5_02(self):
s = self.password[:5] # 设置盐
md = hashlib.md5((self.password + s).encode())
md5_pass = md.hexdigest()
print(f"密码{self.password},md5加盐后为:{md5_pass}")Output:
密码123456,md5加盐后为:e363373ddc24b34c5bb9d99abbfd8be5MD5 with Salt (Insert Salt)
Another common pattern inserts the salt into the password string.
def test_md5_03(self):
s = self.password[:6] # 设置盐
md = hashlib.md5((self.password.join(s)).encode())
md5_pass = md.hexdigest()
print(f"密码{self.password},md5加盐使用json方法为:{md5_pass}")Output:
密码123456,md5加盐使用json方法为:43ec0d3f863b4f7e635e7169ddc18606SHA1 Encryption
SHA1 produces a 160‑bit (40‑character hex) hash.
Username and password are concatenated before hashing.
def test_sha1(self):
data = self.name + self.password
sha1 = hashlib.sha1()
sha1.update(data.encode("utf-8"))
sha1_pass = sha1.hexdigest()
print(f"密码{self.password},用户名{self.name}, sha1组合加密后为:{sha1_pass}")Output:
密码123456,用户名admin, sha1组合加密后为:cd5ea73cd58f827fa78eef7197b8ee606c99b2e6SHA256 Encryption
SHA256 is more secure than SHA1 but slower, yielding a longer hash.
Username and password are concatenated before hashing.
def test_sha256(self):
data = self.name + self.password
sha256 = hashlib.sha256()
sha256.update(data.encode("utf-8"))
sha1_pass = sha256.hexdigest()
print(f"密码{self.password},用户名{self.name}, sha256组合加密后为:{sha1_pass}")Output:
密码123456,用户名admin, sha256组合加密后为:ac0e7d037817094e9e0b4441f9bae3209d67b02fa484917065f71b16109a1a78HMAC Encryption
HMAC combines a hash function with a secret key for message authentication.
Python's hmac library is used with MD5 as the hash.
def test_hmac(self):
hm = hmac.new(b'029-11111111', bytes(self.password, 'utf-8'), hashlib.md5)
hm.digest()
hmac_pass = hm.hexdigest()
print(f"密码{self.password},用户名{self.name}, hmac加密后为:{hmac_pass}")Output:
密码123456,用户名admin, hmac加密后为:4e32d965d8965df4c7f6aaaf68791e86Other Algorithms
Additional algorithms such as DES, AES, RSA, ECC are mentioned but not detailed.
They will be added later.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
