React加密密码后如何在Django后端实现解密?
Django后端解密CryptoJS AES加密的密码
前置依赖
先安装Python加密库pycryptodome,用来处理AES解密和密钥推导逻辑:
pip install pycryptodome
解密核心实现
CryptoJS的AES.encrypt传入字符串密钥时,会自动用EVP_BytesToKey算法生成AES密钥和IV,同时生成随机盐,最终加密字符串是Salted__前缀 + 8字节盐 + 密文的base64编码。后端需按此逻辑反向处理:
from Crypto.Cipher import AES from Crypto.Protocol.KDF import EVP_BytesToKey from Crypto.Util.Padding import unpad import base64 def decrypt_password(encrypted_str, key): # 解码前端传来的base64加密串 encrypted_data = base64.b64decode(encrypted_str) # 验证CryptoJS加密格式前缀 assert encrypted_data[:8] == b'Salted__', "无效的加密字符串格式" # 提取盐和密文内容 salt = encrypted_data[8:16] ciphertext = encrypted_data[16:] # 用和CryptoJS一致的逻辑生成密钥和IV aes_key, iv = EVP_BytesToKey( key_len=32, # CryptoJS默认使用AES-256 iv_len=16, password=key.encode('utf-8'), salt=salt, count=1 # CryptoJS默认迭代次数为1 ) # AES-CBC模式解密,移除PKCS7填充(CryptoJS默认填充方式) cipher = AES.new(aes_key, AES.MODE_CBC, iv) decrypted_data = unpad(cipher.decrypt(ciphertext), AES.block_size) return decrypted_data.decode('utf-8')
在Django视图中调用
假设前端POST请求将加密密码放在encrypted_password字段,后端视图处理示例:
from django.http import JsonResponse from django.contrib.auth import authenticate, login import os def login_view(request): if request.method == 'POST': encrypted_pwd = request.POST.get('encrypted_password') username = request.POST.get('username') # 从环境变量取密钥,和前端VITE_PASSWORD_KEY完全一致 secret_key = os.environ.get('VITE_PASSWORD_KEY') try: plain_pwd = decrypt_password(encrypted_pwd, secret_key) except Exception as e: return JsonResponse({'error': '密码解密失败'}, status=400) # 用明文密码验证用户身份 user = authenticate(request, username=username, password=plain_pwd) if user is not None: login(request, user) return JsonResponse({'success': '登录成功'}) else: return JsonResponse({'error': '用户名或密码错误'}, status=400) return JsonResponse({'error': '仅支持POST请求'}, status=405)
关键注意事项
- 密钥一致性:前后端的
VITE_PASSWORD_KEY必须完全匹配,包括大小写、特殊字符,否则解密必失败。 - 密钥安全:密钥不要硬编码,前后端都通过环境变量管理,避免泄露。
- 安全提示:前端加密不能替代HTTPS,HTTPS才是防止传输过程数据被窃听的核心手段;前端加密仅能降低密码在前端内存明文暴露的风险,无法防范中间人攻击。
内容的提问来源于stack exchange,提问作者Panda
相关产品推荐
相关产品推荐

