在MySQL中存储加密的密码是为了确保数据的安全性,防止密码泄露带来的风险。以下是一些基础概念和相关步骤:
以下是一个使用Python和MySQL存储加密密码的示例:
import hashlib
import os
import mysql.connector
# 连接数据库
db = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
cursor = db.cursor()
def hash_password(password):
salt = os.urandom(16) # 生成16字节的随机盐值
hashed_password = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
return salt + hashed_password
def store_password(username, password):
hashed_password = hash_password(password)
cursor.execute("INSERT INTO users (username, password) VALUES (%s, %s)", (username, hashed_password))
db.commit()
def verify_password(username, password):
cursor.execute("SELECT password FROM users WHERE username = %s", (username,))
result = cursor.fetchone()
if result:
stored_password = result[0]
salt = stored_password[:16]
new_hashed_password = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 100000)
return new_hashed_password == stored_password[16:]
return False
# 示例使用
store_password("user1", "password123")
print(verify_password("user1", "password123")) # 输出: True
print(verify_password("user1", "wrongpassword")) # 输出: False
通过上述步骤和方法,可以在MySQL中安全地存储加密的密码,确保用户数据的安全性。
领取专属 10元无门槛券
手把手带您无忧上云