提交 fa98ac83847a3729a552900144d988c8d75e83ee

作者 qianyingz
1 个父辈 aa439354

账号密码加密;加密传输python部分

@@ -4,20 +4,40 @@ import os @@ -4,20 +4,40 @@ import os
4 from flask_sqlalchemy import SQLAlchemy 4 from flask_sqlalchemy import SQLAlchemy
5 import glob 5 import glob
6 import traceback 6 import traceback
7 -from pyDes import des,PAD_PKCS5,ECB 7 +from pyDes import des, PAD_PKCS5, ECB
8 8
9 import base64 9 import base64
  10 +from gmssl import sm3, func, sm2
  11 +
  12 +
  13 +class SM3():
  14 + @classmethod
  15 + def encode(self, data=""):
  16 + by_str = bytes(data, 'utf-8')
  17 + result = (sm3.sm3_hash(func.bytes_to_list(by_str)))
  18 + return result
  19 +
  20 +
  21 +class SM2():
  22 + privatekey = "EOpBYj1pH54b8BsAlkON71Q2c2FXEm+VTPNCgxz4+gVZ2C/pF/Bv152Qj3QH7cBRCUlNeO5SkI02DcwTASmVwESzR4F9IbMvUNxkDngINdcwaSWCTaaRTstNd4FIlJ0CqhDl/TPHFuBoRNBgUDfPJFfl7XYHs4VmOcrp02aXv8Q="
  23 + publickey = "MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEsENe/8Sft6rK0h59t2a/6Pf4nzvxvJzc1SzalZe1xSDtUqW/10E/e+RjRbvykyjKzu3vAY1lwv9aU2Tnp6+isw=="
  24 + sm2_crypt = sm2.CryptSM2(public_key=publickey, private_key=privatekey)
  25 +
  26 + def decode(self, ciphertxt):
  27 + return self.sm2_crypt.decrypt(ciphertxt)
  28 +
  29 +
10 class DES(): 30 class DES():
11 ''' 31 '''
12 DES密码加解密 32 DES密码加解密
13 ''' 33 '''
14 - Des: des = des("Chinadci", ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=PAD_PKCS5) 34 + Des: des = des("Chinadci", ECB, "\0\0\0\0\0\0\0\0",
  35 + pad=None, padmode=PAD_PKCS5)
15 36
16 @classmethod 37 @classmethod
17 def encode(cls, data): 38 def encode(cls, data):
18 return str(base64.b64encode(cls.Des.encrypt(data)), encoding="utf8") 39 return str(base64.b64encode(cls.Des.encrypt(data)), encoding="utf8")
19 40
20 -  
21 @classmethod 41 @classmethod
22 def decode(cls, data): 42 def decode(cls, data):
23 if data: 43 if data:
@@ -26,6 +46,7 @@ class DES(): @@ -26,6 +46,7 @@ class DES():
26 else: 46 else:
27 return data 47 return data
28 48
  49 +
29 db = SQLAlchemy() 50 db = SQLAlchemy()
30 51
31 # 动态加载Model 52 # 动态加载Model
@@ -33,13 +54,14 @@ current_dir = os.path.abspath(os.path.dirname(__file__)) @@ -33,13 +54,14 @@ current_dir = os.path.abspath(os.path.dirname(__file__))
33 pkgs = list(glob.glob('%s/modules/*/models' % (current_dir))) 54 pkgs = list(glob.glob('%s/modules/*/models' % (current_dir)))
34 pkgs.extend(list(glob.glob('%s/modules/*/*/models' % (current_dir)))) 55 pkgs.extend(list(glob.glob('%s/modules/*/*/models' % (current_dir))))
35 56
36 -for pkg in pkgs : 57 +for pkg in pkgs:
37 pkg = os.path.normpath(pkg) 58 pkg = os.path.normpath(pkg)
38 node_list = pkg.split(os.path.sep) 59 node_list = pkg.split(os.path.sep)
39 - pkg_name = "app.{}".format(".".join(node_list[node_list.index("modules"):])) 60 + pkg_name = "app.{}".format(
  61 + ".".join(node_list[node_list.index("modules"):]))
40 try: 62 try:
41 if pkg_name.__contains__("models"): 63 if pkg_name.__contains__("models"):
42 __import__(pkg_name) 64 __import__(pkg_name)
43 except Exception as e: 65 except Exception as e:
44 print(traceback.format_exc()) 66 print(traceback.format_exc())
45 - pass  
  67 + pass
@@ -4,7 +4,6 @@ from flasgger import swag_from @@ -4,7 +4,6 @@ from flasgger import swag_from
4 from app.util import BlueprintApi 4 from app.util import BlueprintApi
5 from app.util import BlueprintApi 5 from app.util import BlueprintApi
6 from flask import Blueprint, render_template, redirect, request, session, jsonify 6 from flask import Blueprint, render_template, redirect, request, session, jsonify
7 -from sqlalchemy import and_  
8 from .models import * 7 from .models import *
9 from .oauth2 import authorization, generate_user_info,require_oauth 8 from .oauth2 import authorization, generate_user_info,require_oauth
10 from authlib.oauth2 import OAuth2Error 9 from authlib.oauth2 import OAuth2Error
@@ -13,6 +12,7 @@ from . import user_create, client_create, client_query, user_query, user_update, @@ -13,6 +12,7 @@ from . import user_create, client_create, client_query, user_query, user_update,
13 import configure 12 import configure
14 from app.decorators.auth_decorator import auth_decorator 13 from app.decorators.auth_decorator import auth_decorator
15 import time 14 import time
  15 +from app.models import SM3
16 16
17 def current_user(): 17 def current_user():
18 if "id" in session: 18 if "id" in session:
@@ -54,7 +54,7 @@ class DataManager(BlueprintApi): @@ -54,7 +54,7 @@ class DataManager(BlueprintApi):
54 error = "密码不可为空" 54 error = "密码不可为空"
55 else: 55 else:
56 username = request.form.get("username") 56 username = request.form.get("username")
57 - password = request.form.get("password") 57 + password = SM3.encode(request.form.get("password"))
58 user = User.query.filter_by( 58 user = User.query.filter_by(
59 username=username, password=password).first() 59 username=username, password=password).first()
60 if not user: 60 if not user:
@@ -6,6 +6,7 @@ @@ -6,6 +6,7 @@
6 from .models import * 6 from .models import *
7 from app.util.component.ApiTemplate import ApiTemplate 7 from app.util.component.ApiTemplate import ApiTemplate
8 import time 8 import time
  9 +from app.models import SM3
9 10
10 11
11 class Api(ApiTemplate): 12 class Api(ApiTemplate):
@@ -27,7 +28,7 @@ class Api(ApiTemplate): @@ -27,7 +28,7 @@ class Api(ApiTemplate):
27 try: 28 try:
28 # 业务逻辑 29 # 业务逻辑
29 username = self.para.get("username") 30 username = self.para.get("username")
30 - password = self.para.get("pwd") 31 + password = SM3.encode(self.para.get("pwd"))
31 role = self.para.get("role") 32 role = self.para.get("role")
32 company = self.para.get("company", None) 33 company = self.para.get("company", None)
33 position = self.para.get("position", None) 34 position = self.para.get("position", None)
1 from app.util.component.ApiTemplate import ApiTemplate 1 from app.util.component.ApiTemplate import ApiTemplate
2 -import time 2 +from app.models import SM3
3 from .models import * 3 from .models import *
4 4
5 5
@@ -25,10 +25,10 @@ class Api(ApiTemplate): @@ -25,10 +25,10 @@ class Api(ApiTemplate):
25 else: 25 else:
26 # 更新密码要求同时输入pwd/newPwd/reNewPwd 26 # 更新密码要求同时输入pwd/newPwd/reNewPwd
27 if self.para.__contains__("pwd") or self.para.__contains__("newPwd") or self.para.__contains__("reNewPwd"): 27 if self.para.__contains__("pwd") or self.para.__contains__("newPwd") or self.para.__contains__("reNewPwd"):
28 - password = self.para.get("pwd")  
29 - new_password = self.para.get("newPwd")  
30 - re_new_password = self.para.get("reNewPwd")  
31 - 28 + password = SM3.encode(self.para.get("pwd"))
  29 + new_password = SM3.encode(self.para.get("newPwd"))
  30 + re_new_password = SM3.encode(self.para.get("reNewPwd"))
  31 +
32 # validate pwd 32 # validate pwd
33 if not password: 33 if not password:
34 res["result"] = False 34 res["result"] = False
@@ -42,17 +42,17 @@ class Api(ApiTemplate): @@ -42,17 +42,17 @@ class Api(ApiTemplate):
42 res["result"] = False 42 res["result"] = False
43 res["msg"] = "原密码输入错误" 43 res["msg"] = "原密码输入错误"
44 return res 44 return res
45 - 45 +
46 # 更新密码 46 # 更新密码
47 userinfo.update({"password": new_password}) 47 userinfo.update({"password": new_password})
48 -  
49 - #更新用户基本信息 48 +
  49 + # 更新用户基本信息
50 for key in obj_value: 50 for key in obj_value:
51 if self.para.__contains__(obj_value[key]): 51 if self.para.__contains__(obj_value[key]):
52 value = self.para.get(obj_value[key]) 52 value = self.para.get(obj_value[key])
53 value = "" if value == "None" or value == "none" else value 53 value = "" if value == "None" or value == "none" else value
54 userinfo.update({key: value}) 54 userinfo.update({key: value})
55 - 55 +
56 db.session.commit() 56 db.session.commit()
57 res["result"] = True 57 res["result"] = True
58 res["msg"] = "更新用户信息成功" 58 res["msg"] = "更新用户信息成功"
@@ -4,8 +4,8 @@ import logging @@ -4,8 +4,8 @@ import logging
4 deploy_ip_host = "172.26.40.105:8840" 4 deploy_ip_host = "172.26.40.105:8840"
5 # 系统数据库 5 # 系统数据库
6 6
7 -SQLALCHEMY_DATABASE_URI = "postgresql://postgres:chinadci@172.26.60.100:5432/dmap_manager_test"  
8 -# SQLALCHEMY_DATABASE_URI = "postgresql://postgres:postgres@localhost:5433/dmap_dms_test1" 7 +# SQLALCHEMY_DATABASE_URI = "postgresql://postgres:chinadci@172.26.60.100:5432/dmap_manager_test"
  8 +SQLALCHEMY_DATABASE_URI = "postgresql://postgres:postgres@localhost:5433/dmap_dms_test1"
9 9
10 # 指定精华表所在位置(必须为空间库),设置为None则存放在各自的实体库中 10 # 指定精华表所在位置(必须为空间库),设置为None则存放在各自的实体库中
11 #VACUATE_DB_URI = None 11 #VACUATE_DB_URI = None
1 -## https://swagger.io/docs/specification/2-0/what-is-swagger/  
2 -## 1 需求:api需要授权  
3 -Swagger(app, config=swagger_config,template=SWAGGER_TEMPLATE)的template中  
4 -### 确定当前使用swagger的标准  
5 -确定当前使用openapi2版本,需要查阅openapi2的文档  
6 -### 了解简单YAML使用方式  
7 -### 配置  
  1 +# 权限控制
  2 +## 1 接口权限控制
  3 +[swagger](https://swagger.io/docs/specification/2-0/what-is-swagger/)
  4 +
  5 +**需求:api需要授权**
  6 +
  7 +1.确定当前使用openapi2版本
  8 +2.了解简单YAML使用方式,文档使用YAML格式
  9 +3.声明Swagger,传入配置template(json或者yaml)
  10 +```python
  11 +Swagger(app, config=swagger_config,template=SWAGGER_TEMPLATE)
  12 +```
  13 +
  14 +## 2 用户密码加密
  15 +[pipy](https://pypi.org/project/gmssl/)
  16 +[github](https://github.com/guanzhi/GmSSL)
  17 +[使用gmssl demo](https://www.cnblogs.com/rocedu/p/15518988.html)
  18 +
  19 +**用户密码加密不可逆,兼容国产化,使用sm3算法,采用gmssl开源组件**
  20 +
  21 +封装好的类使用如下:
  22 +```python
  23 +from app.models import SM3
  24 +password = SM3.encode('test')
  25 +```
  26 +## 3 通过http传输的敏感信息要加密
  27 +1. 使用sm2
  28 +通过gmssl工具生成sm2的公钥、私钥。[教程](https://github.com/guanzhi/GmSSL)
  29 +
  30 +privatekey使用的pem是`zhou@123`
  31 +
  32 +```shell
  33 +gmssl sm2 -genkey -out skey.pem
  34 +gmssl sm2 -pubout -in skey.pem -out vkey.pem
  35 +```
  36 +
  37 +2. 使用公钥加密,私钥解密
  38 +```python
  39 +privatekey="EOpBYj1pH54b8BsAlkON71Q2c2FXEm+VTPNCgxz4+gVZ2C/pF/Bv152Qj3QH7cBRCUlNeO5SkI02DcwTASmVwESzR4F9IbMvUNxkDngINdcwaSWCTaaRTstNd4FIlJ0CqhDl/TPHFuBoRNBgUDfPJFfl7XYHs4VmOcrp02aXv8Q="
  40 +publickey="MFkwEwYHKoZIzj0CAQYIKoEcz1UBgi0DQgAEsENe/8Sft6rK0h59t2a/6Pf4nzvxvJzc1SzalZe1xSDtUqW/10E/e+RjRbvykyjKzu3vAY1lwv9aU2Tnp6+isw=="
  41 +```
@@ -20,4 +20,4 @@ kazoo==2.8.0 @@ -20,4 +20,4 @@ kazoo==2.8.0
20 paramiko==2.8.0 20 paramiko==2.8.0
21 requests==2.26.0 21 requests==2.26.0
22 schedule==1.1.0 22 schedule==1.1.0
23 - 23 +gmssl==3.2.1
注册登录 后发表评论