import
hashlib
import
json
import
base64
import
time
from
Crypto.Cipher
import
AES
from
Crypto.Util.Padding
import
pad
from
cryptography.hazmat.primitives
import
padding
from
flask
import
Flask, jsonify, request
app
=
Flask(__name__)
def
aes_encrypt(data:
str
)
-
>
str
:
key
=
b
'1234567890abcdefwuaipojie0abcdef'
iv
=
b
'1234567wuaipojie'
cipher
=
AES.new(key, AES.MODE_CBC, iv)
encrypted_data
=
cipher.encrypt(pad(data.encode(
'utf-8'
), AES.block_size))
return
base64.b64encode(encrypted_data).decode(
'utf-8'
)
def
aes_decrypt(encrypted_data:
str
)
-
>
dict
:
key
=
b
'1234567890abcdefwuaipojie0abcdef'
iv
=
b
'1234567wuaipojie'
cipher
=
AES.new(key, AES.MODE_CBC, iv)
encrypted_bytes
=
base64.b64decode(encrypted_data)
decrypted_data
=
cipher.decrypt(encrypted_bytes)
unpadder
=
padding.PKCS7(AES.block_size
*
8
).unpadder()
decrypted_unpadded
=
unpadder.update(decrypted_data)
+
unpadder.finalize()
decrypted_str
=
decrypted_unpadded.decode(
'utf-8'
)
return
json.loads(decrypted_str)
with
open
(
'user_data.json'
,
'r'
) as
file
:
user_data
=
json.load(
file
)
def
write_json_file(file_path:
str
, data:
dict
):
with
open
(file_path,
'w'
) as
file
:
json.dump(data,
file
, indent
=
4
)
def
generate_signature(user_id:
str
, coin:
int
, timestamp:
int
)
-
>
str
:
message
=
f
"{user_id}&{coin}&{timestamp}"
hash_object
=
hashlib.md5(message.encode())
return
hash_object.hexdigest()
@app
.route(
'/get_coin'
, methods
=
[
'POST'
])
def
get_coin():
encrypted_data
=
request.json.get(
'user_data'
)
if
not
encrypted_data:
return
jsonify({
"error"
:
"数据有误!"
}),
400
try
:
decrypted_data
=
aes_decrypt(encrypted_data)
timestamp
=
int
(decrypted_data.get(
'timestamp'
))
current_time
=
int
(time.time()
*
1000
)
print
(timestamp)
print
(
abs
(current_time
-
timestamp))
if
abs
(current_time
-
timestamp) >
5000
:
return
jsonify({
"error"
:
"请求过期!"
}),
400
sign
=
decrypted_data.get(
'sign'
)
expected_sign
=
generate_signature(decrypted_data[
"user_id"
],
1
, timestamp)
if
sign !
=
expected_sign:
return
jsonify({
"error"
:
"签名验证失败!"
}),
401
user_id
=
decrypted_data.get(
'user_id'
)
if
user_id
in
user_data[
'user_id'
]:
user_data[
'coin_amount'
]
+
=
1
write_json_file(
'user_data.json'
, user_data)
return
jsonify({
"投币成功,当前数量为:"
: user_data[
'coin_amount'
]})
else
:
return
jsonify({
"error"
:
"用户未找到!"
}),
404
except
Exception as e:
return
jsonify({
"error"
: f
"处理请求时出错: {str(e)}"
}),
500
@app
.route(
'/get_user_data'
, methods
=
[
'GET'
])
def
get_user_data():
data_str
=
json.dumps(user_data)
return
jsonify({
"user_data"
: data_str})
if
__name__
=
=
'__main__'
:
app.run(host
=
'192.168.73.82'
, port
=
5000
)