MySQL 验证密码通常是指验证用户输入的密码是否与数据库中存储的加密密码匹配。MySQL 5.7 及以上版本使用 SHA-256
算法对密码进行哈希处理,并存储哈希值。以下是验证密码的基本步骤:
以下是一个简单的 Python 示例,使用 mysql-connector-python
库连接 MySQL 数据库并验证密码:
import mysql.connector
import hashlib
def get_salt_and_hash(username):
conn = mysql.connector.connect(user='your_user', password='your_password', host='your_host', database='your_database')
cursor = conn.cursor()
query = "SELECT salt, password_hash FROM users WHERE username = %s"
cursor.execute(query, (username,))
result = cursor.fetchone()
cursor.close()
conn.close()
return result
def verify_password(username, input_password):
salt_and_hash = get_salt_and_hash(username)
if salt_and_hash:
salt, stored_hash = salt_and_hash
input_password_hash = hashlib.sha256((input_password + salt).encode()).hexdigest()
return input_password_hash == stored_hash
return False
# 示例使用
username = 'example_user'
input_password = 'example_password'
if verify_password(username, input_password):
print("密码验证成功")
else:
print("密码验证失败")
通过以上步骤和示例代码,可以有效地验证 MySQL 中的用户密码。
领取专属 10元无门槛券
手把手带您无忧上云