以下是基于Python的完整实现示例,包含服务器端、客户端和加密传输的全流程:
### 系统架构示意图
```
[客户端] –(HTTPS请求)–> [验证服务器] –(返回加密代码)–> [客户端动态执行]
```
—
### 1. 服务器端代码(Flask实现)
```python
# server.py
from flask import Flask, jsonify, request
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Util.Padding import pad
import base64
import os
app = Flask(__name__)
# 预先生成的RSA密钥对(实际生产环境应使用密钥管理系统)
private_key = RSA.generate(2048)
public_key = private_key.publickey()
# 存储合法的设备指纹和许可证(示例数据)
valid_licenses = {
"machine-123": "LICENSE-ABC-XYZ"
}
def encrypt_code():
"""加密核心业务逻辑代码"""
# 要加密的源代码
source_code = '''
def add_numbers(a, b):
return a + b
result = add_numbers(5, 3)
'''.strip()
# AES加密
aes_key = os.urandom(32) # 256-bit key
cipher_aes = AES.new(aes_key, AES.MODE_CBC)
ct_bytes = cipher_aes.encrypt(pad(source_code.encode(), AES.block_size))
# 用RSA公钥加密AES密钥
encrypted_aes_key = public_key.encrypt(aes_key, None)[0]
return {
'iv': base64.b64encode(cipher_aes.iv).decode(),
'ciphertext': base64.b64encode(ct_bytes).decode(),
'encrypted_aes_key': base64.b64encode(encrypted_aes_key).decode()
}
@app.route('/api/get_code', methods=['POST'])
def handle_request():
# 验证客户端身份
client_data = request.json
if not valid_licenses.get(client_data['machine_id']) == client_data['license_key']:
return jsonify({"status": "invalid"}), 403
# 加密代码
encrypted = encrypt_code()
return jsonify({
"status": "success",
"data": encrypted
})
if __name__ == '__main__':
app.run(ssl_context='adhoc', port=443) # 使用临时SSL证书
```
—
### 2. 客户端代码(Tkinter GUI)
```python
# client.py
import tkinter as tk
from tkinter import messagebox
import requests
import base64
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA
from Crypto.Util.Padding import unpad
class ClientApp:
def __init__(self):
self.window = tk.Tk()
self.window.title("远程代码执行演示")
self.setup_ui()
self.machine_id = self.get_machine_id() # 获取设备指纹
def setup_ui(self):
frame = tk.Frame(self.window, padx=20, pady=20)
frame.pack()
self.btn = tk.Button(frame,
text="执行远程加法",
command=self.execute_remote_code,
height=2,
width=20)
self.btn.pack(pady=10)
self.result_label = tk.Label(frame, text="结果将显示在这里")
self.result_label.pack()
def get_machine_id(self):
"""生成简单设备指纹(生产环境需要更复杂的方案)"""
import platform, uuid
return f"{platform.node()}-{uuid.getnode()}"
def decrypt_code(self, encrypted_data, private_key):
"""解密接收到的代码"""
# 解密AES密钥
encrypted_aes_key = base64.b64decode(encrypted_data['encrypted_aes_key'])
aes_key = private_key.decrypt(encrypted_aes_key)
# 解密代码
iv = base64.b64decode(encrypted_data['iv'])
ciphertext = base64.b64decode(encrypted_data['ciphertext'])
cipher = AES.new(aes_key, AES.MODE_CBC, iv)
plaintext = unpad(cipher.decrypt(ciphertext), AES.block_size)
return plaintext.decode()
def execute_remote_code(self):
try:
# 发送验证请求
response = requests.post(
"https://localhost/api/get_code",
json={
"machine_id": self.machine_id,
"license_key": "LICENSE-ABC-XYZ"
},
verify=False # 生产环境应使用有效证书
)
if response.status_code != 200:
raise Exception("服务器响应异常")
data = response.json()
if data['status'] != "success":
raise Exception("许可证验证失败")
# 加载客户端私钥(应与服务器公钥配对)
with open("client_private.pem", "r") as f:
private_key = RSA.import_key(f.read())
# 解密代码
decrypted_code = self.decrypt_code(data['data'], private_key)
# 创建安全执行环境
local_vars = {}
exec(decrypted_code, {"__builtins__": {}}, local_vars)
# 显示结果
self.result_label.config(text=f"计算结果: {local_vars['result']}")
except Exception as e:
messagebox.showerror("错误", f"执行失败: {str(e)}")
if __name__ == "__main__":
# 生成客户端密钥(预先执行)
# key = RSA.generate(2048)
# with open("client_private.pem", "wb") as f:
# f.write(key.export_key())
# with open("client_public.pem", "wb") as f:
# f.write(key.publickey().export_key())
app = ClientApp()
app.window.mainloop()
```
—
### 3. 密钥生成步骤(预先执行)
```bash
# 生成客户端RSA密钥对
openssl genrsa -out client_private.pem 2048
openssl rsa -in client_private.pem -pubout -out client_public.pem
# 将client_public.pem提供给服务器端用于加密
```
—
### 系统运行流程
1. 启动服务器端:
```bash
python server.py
```
2. 运行客户端:
```bash
python client.py
```
3. 点击按钮后的执行过程:
```
1. 获取设备指纹
2. 发送HTTPS请求到服务器
3. 服务器验证许可证有效性
4. 返回加密的代码和密钥
5. 客户端用私钥解密AES密钥
6. 用AES密钥解密代码
7. 在受限环境中执行代码
8. 显示计算结果
```
—
### 关键安全措施说明
1. **双重加密传输**:
– AES-256加密实际代码
– RSA-2048加密AES密钥
– 使用Base64编码进行网络传输
2. **代码执行沙箱**:
```python
exec(decrypted_code, {"__builtins__": {}}, local_vars)
```
– 限制访问
评论前必须登录!
注册