You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

NTRU密码系统代码报错:global name 'decimalmessage'未定义求助

问题分析与解决方案

问题原因

你遇到的global name 'decimalmessage' is not defined报错有两个核心原因:

  1. 全局变量未提前初始化:仅在on_message()函数内用global声明了decimalmessage,但未在全局作用域定义该变量,导致主线程访问时它还不存在。
  2. 线程时序问题:主线程启动MQTT线程后立刻执行print(decimalmessage),此时MQTT客户端还未收到消息,on_message()尚未触发,变量根本没被赋值。

具体修改步骤

1. 提前初始化全局变量

在全局作用域定义decimalmessage,给它一个初始值(比如空字符串或None):

# 全局变量初始化
msga = 0
decimalmessage = ""  # 提前定义全局变量,避免未定义报错

2. 修正on_message()中的全局变量声明

msga也是全局变量,需要在on_message()中添加global声明,否则会被当作局部变量处理:

def on_message(client, userdata, msg):
    global decimalmessage, msga  # 同时声明两个全局变量
    
    msga = json.loads(msg.payload)
    print("Received encrypted message:", msg.payload)
    encrypted_message = json.loads(msg.payload)
    decrypted_message = Bob.decrypt(encrypted_message)
    print("Decrypted message:", decrypted_message)
    # 二进制转十进制
    decimalmessage = str(int(''.join(map(str, decrypted_message)), 2))
    print(decimalmessage)

3. 避免主线程过早访问变量

主线程中的print(decimalmessage)会在MQTT线程收到消息前执行,此时变量还是初始值,建议直接删除该行,或者在需要使用该变量的地方(比如Flask路由)判断其状态:

@app.route("/")
def inde():
    global decimalmessage
    # 处理未收到消息的情况
    received_msg = decimalmessage if decimalmessage else "暂无收到加密消息"
    f1 = f
    g1 = g
    bob2 = Bob
    publkey = pub_key
    return render_template("index.html", f1=f1, g1=g1, bob2=bob2, publkey=publkey, received_msg=received_msg)

修改后的完整代码

import paho.mqtt.client as mqtt
from flask import Flask, render_template, request
from ntru1 import *
import sys
import json
import threading
import signal

# Define the NTRU parameters and generate Bob's public key
Bob = Ntru(167, 3, 128)
f = [1, 1, -1, 0, -1, 1]
g = [-1, 0, 1, 1, 0, 0, -1]
d = 2
Bob.genPublicKey(f, g, 2)
pub_key = Bob.getPublicKey()
print("Public Key:", pub_key)

# Send Bob's public key to Alice using MQTT
data_out = json.dumps(pub_key)
mqttc = mqtt.Client()
mqttc.connect("localhost", 1883, 60)
if mqttc.connect("localhost", 1883, 60) != 0:
    print('dis')
    sys.exit(-1)
mqttc.publish("test", data_out, 0)
mqttc.disconnect()

# 全局变量初始化
msga = 0
decimalmessage = ""  # 提前定义全局变量

# Define the on_message() function to handle incoming messages
def on_message(client, userdata, msg):
    global decimalmessage, msga
    
    msga = json.loads(msg.payload)
    print("Received encrypted message:", msg.payload)
    encrypted_message = json.loads(msg.payload)
    decrypted_message = Bob.decrypt(encrypted_message)
    print("Decrypted message:", decrypted_message)
    # from binary to decimal
    decimalmessage = str(int(''.join(map(str, decrypted_message)), 2))
    print(decimalmessage)

# Define the MQTT client 
def mqtt_thread():
    global client 
    client = mqtt.Client()
    client.on_message = on_message
    print("hree", msga)
    if client.connect("localhost", 1883, 60) != 0:
        print('dis')
        sys.exit(-1)
    client.subscribe("test2")
    client.loop_forever()
    
# Start the MQTT client thread
mqtt_client_thread = threading.Thread(target=mqtt_thread)
mqtt_client_thread.start()

# Run the Flask application in the main thread
app = Flask(__name__)
@app.route("/")
def inde():
    global decimalmessage
    received_msg = decimalmessage if decimalmessage else "暂无收到加密消息"
    f1 = f
    g1 = g
    bob2 = Bob
    publkey = pub_key
    return render_template("index.html", f1=f1, g1=g1, bob2=bob2, publkey=publkey, received_msg=received_msg)

if __name__ == "__main__":
    app.run(host='127.0.0.37', port=4457, debug=True)

内容的提问来源于stack exchange,提问作者mohamad alhakeem

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 18:43:14