Django对接Lightning LND Rest API处理POST请求时遇Incorrect Padding错误
解决LND修改密码接口的"Incorrect Padding"错误
问题根源
"Incorrect Padding"错误是因为base64解码时输入字符串格式不合法——base64编码后的字符串长度必须是4的倍数,缺少填充字符=会导致解码失败。前端传入的密码参数可能未正确添加填充,或传输过程中丢失了填充字符。
修复方案
- 先补全base64字符串的填充字符,确保格式合法后再解码
- 优化请求参数传递方式,避免手动JSON编码的潜在问题
修改后的views.py代码:
from rest_framework.views import APIView from rest_framework.response import Response from rest_framework import status import base64, json, requests class ChangePassword(APIView): def post(self, request): url = "https://localhost:8080/v1/changepassword" cert_path = "/Users/user1/Library/Application Support/Lnd/tls.cert" def fix_base64_padding(b64_str): # 补全base64字符串的填充字符,保证长度为4的倍数 padding = 4 - len(b64_str) % 4 if padding != 4: b64_str += '=' * padding return b64_str try: # 修复填充后再解码密码 current_pw = base64.b64decode(fix_base64_padding(request.data["current_password"])).decode("utf-8") new_pw = base64.b64decode(fix_base64_padding(request.data["new_password"])).decode("utf-8") except (UnicodeDecodeError, ValueError) as e: return Response({"error": f"密码解码失败: {str(e)}"}, status=status.HTTP_400_BAD_REQUEST) data = { "current_password": current_pw, "new_password": new_pw, } try: # 用json参数自动处理编码,无需手动dumps r = requests.post(url, verify=cert_path, json=data) r.raise_for_status() return Response(r.json(), status=status.HTTP_200_OK) except requests.exceptions.RequestException as e: error_status = r.status_code if 'r' in locals() else status.HTTP_500_INTERNAL_SERVER_ERROR return Response({"error": f"请求失败: {str(e)}"}, status=error_status)
关键改动说明
fix_base64_padding函数:自动补充缺失的=,确保base64字符串符合解码要求- 异常捕获:捕获解码和请求阶段的错误,返回更清晰的错误提示
- 请求优化:使用
json=data替代手动json.dumps,requests会自动设置正确的Content-Type头,避免格式不匹配问题
内容的提问来源于stack exchange,提问作者Pau1aAm7
相关产品推荐
相关产品推荐

