Skip to content

Commit

Permalink
密码字段加密
Browse files Browse the repository at this point in the history
  • Loading branch information
welliamcao committed Apr 25, 2020
1 parent ab2769a commit 2021d42
Show file tree
Hide file tree
Showing 6 changed files with 115 additions and 34 deletions.
9 changes: 5 additions & 4 deletions apps/asset/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
from account.models import User,Structure
from datetime import datetime
from mptt.models import MPTTModel, TreeForeignKey
from dao.base import AESCharField



Expand Down Expand Up @@ -116,8 +117,8 @@ class Server_Assets(models.Model):
ip = models.CharField(max_length=100,unique=True,blank=True,null=True)
hostname = models.CharField(max_length=100,blank=True,null=True)
username = models.CharField(max_length=100,blank=True,null=True)
passwd = models.CharField(max_length=100,default='root',blank=True,null=True)
sudo_passwd = models.CharField(max_length=100,blank=True,null=True)
passwd = AESCharField(max_length=100,default='root',blank=True,null=True)
sudo_passwd = AESCharField(max_length=100,blank=True,null=True)
keyfile = models.SmallIntegerField(blank=True,null=True)#FileField(upload_to = './upload/key/',blank=True,null=True,verbose_name='密钥文件')
keyfile_path = models.CharField(max_length=100,blank=True,null=True)
port = models.DecimalField(max_digits=6,decimal_places=0,default=22)
Expand Down Expand Up @@ -192,8 +193,8 @@ class Network_Assets(models.Model):
bandwidth = models.CharField(max_length=100,blank=True,null=True,verbose_name='背板带宽')
ip = models.CharField(unique=True,max_length=100,blank=True,null=True,verbose_name='管理ip')
username = models.CharField(max_length=100,blank=True,null=True)
passwd = models.CharField(max_length=100,blank=True,null=True)
sudo_passwd = models.CharField(max_length=100,blank=True,null=True)
passwd = AESCharField(max_length=100,blank=True,null=True)
sudo_passwd = AESCharField(max_length=100,blank=True,null=True)
port = models.DecimalField(max_digits=6,decimal_places=0,default=22)
port_number = models.SmallIntegerField(blank=True,null=True,verbose_name='端口个数')
firmware = models.CharField(max_length=100,blank=True,null=True,verbose_name='固件版本')
Expand Down
3 changes: 2 additions & 1 deletion apps/databases/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
# _#_ coding:utf-8 _*_
from django.db import models
from asset.models import Business_Tree_Assets
from dao.base import AESCharField

class DataBase_Server_Config(models.Model):
env_type = (
Expand Down Expand Up @@ -45,7 +46,7 @@ class DataBase_Server_Config(models.Model):
db_business = models.IntegerField(verbose_name='业务关联')
db_mode = models.CharField(max_length=10,choices=mode,verbose_name='架构类型',default='single')
db_user = models.CharField(max_length=100,verbose_name='用户',blank=True,null=True)
db_passwd = models.CharField(max_length=100,verbose_name='密码',blank=True,null=True)
db_passwd = AESCharField(max_length=200,verbose_name='密码',blank=True,null=True)
db_port = models.IntegerField(verbose_name='端口')
db_version = models.CharField(max_length=100,verbose_name='数据库版本',blank=True,null=True)
db_mark = models.CharField(max_length=100,verbose_name='标识',blank=True,null=True)
Expand Down
4 changes: 2 additions & 2 deletions apps/orders/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -166,7 +166,7 @@ def to_json(self):
"id":self.id,
"order_type":self.order_type,
"order_sql":self.order_sql,
"order_file":str(self.order_file),
"order_file":str(self.order_file).split('/')[-1],
"order_err":self.order_err if self.order_err else '无',
"sql_backup":self.sql_backup,
"db":{}
Expand Down Expand Up @@ -295,7 +295,7 @@ class Meta:

def to_json(self):

file_path = str(self.file_path)
file_path = str(self.file_path).split('/')[-1]

json_format = {
"id":self.id,
Expand Down
73 changes: 46 additions & 27 deletions dao/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
from django.db import connection
from collections import namedtuple
from datetime import datetime,date

from utils.secret.aescipher import AESCipher
from django.db import models

class Struct:
def __init__(self, **entries):
Expand Down Expand Up @@ -342,31 +343,49 @@ def get_db_table_columns(self,dbname,table_name):
for ds in data[1]:
dataList.append({"COLUMN_NAME":ds[0],"COLUMN_TYPE":ds[1],"COLUMN_DEFAULT":ds[2],"IS_NULLABLE":ds[3],"EXTRA":ds[4],"COLUMN_KEY":ds[5],"COLUMN_COMMENT":ds[6]})
return dataList


class AESCharField(models.CharField):

def __init__(self, *args, **kwargs):
if 'prefix' in kwargs:
self.prefix = kwargs['prefix']
del kwargs['prefix']
else:
self.prefix = "aes:::"
self.cipher = AESCipher(settings.SECRET_KEY)
super(AESCharField, self).__init__(*args, **kwargs)

def deconstruct(self):
name, path, args, kwargs = super(AESCharField, self).deconstruct()
if self.prefix != "aes:::":
kwargs['prefix'] = self.prefix
return name, path, args, kwargs

def from_db_value(self, value, expression, connection, context):
if value is None:
return value
if value.startswith(self.prefix):
value = value[len(self.prefix):]
value = self.cipher.decrypt(value)
return value

def to_python(self, value):
if value is None:
return value
elif value.startswith(self.prefix):
value = value[len(self.prefix):]
value = self.cipher.decrypt(value)
return value

def get_prep_value(self, value):
if isinstance(value, str) or isinstance(value, bytes):
value = self.cipher.encrypt(value)
value = self.prefix + value.decode('utf-8')
elif value is not None:
raise TypeError(str(value) + " is not a valid value for AESCharField")
return value


if __name__=='__main__':
import Queue
rs = []
# mysql234 = MySQLThread('192.168.88.234',3306,'vmanage','root','welliam')
# print mysql234.execute(sql='show tables;', num=1000)
queue = Queue.Queue(maxsize=100)
# mysql234 = MySQLThread('192.168.88.234',3306,'vmanage','root','welliam','show tables;',1000,queue)
# mysql230 = MySQLThread('192.168.88.230',3306,'opsmanage','root','welliam','show tables;',1000,queue)
# mysql234.start()
# mysql230.start()
# while True:
# while not queue.empty():
# rs.append(queue.get())
# '''等待结果返回'''
# if 0 < len(rs) >= 2:break
# print rs

mysql234 = MySQLPool('192.168.88.234',3306,'root','welliam','vmanage','show tables;',1000,'queryMany',queue)
mysql230 = MySQLPool('192.168.88.230',3306,'root','welliam','opsmanage','show tables;',1000,'queryMany',queue)
mysql234.start()
mysql230.start()
while True:
while not queue.empty():
rs.append(queue.get())
'''等待结果返回'''
if 0 < len(rs) >= 2:break
print(rs)
pass
Empty file added utils/secret/__init__.py
Empty file.
60 changes: 60 additions & 0 deletions utils/secret/aescipher.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
#!/usr/bin/env python
# _#_ coding:utf-8 _*_
import base64
import hashlib

from Crypto import Random
from Crypto.Cipher import AES

class AESCipher(object):

def __init__(self, key):
self.key = hashlib.sha256(key.encode()).digest()

def encrypt(self, raw):
raw = self._pad(raw)
iv = Random.new().read(AES.block_size)
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return base64.b64encode(iv + cipher.encrypt(raw))

def decrypt(self, enc):
enc = base64.b64decode(enc)
iv = enc[:AES.block_size]
cipher = AES.new(self.key, AES.MODE_CBC, iv)
return self._unpad(cipher.decrypt(enc[AES.block_size:])).decode('utf-8')

def _pad(self, s):
return s + (AES.block_size - len(s) % AES.block_size) * chr(AES.block_size - len(s) % AES.block_size)

@staticmethod
def _unpad(s):
return s[:-ord(s[len(s)-1:])]


# BS = 16
#
#
# def pad(s):
# return s + (BS - len(s) % BS) * chr(BS - len(s) % BS)
#
#
# def unpad(s):
# return s[0:-s[-1]]
#
#
# class AESCipher:
#
# def __init__(self, key):
# self.key = hashlib.sha256(key.encode('utf-8')).digest()
#
# def encrypt(self, raw):
# raw = pad(raw)
# iv = Random.new().read(AES.block_size)
# cipher = AES.new(self.key, AES.MODE_CBC, iv)
# return base64.b64encode(iv + cipher.encrypt(raw))
#
# def decrypt(self, enc):
# enc = base64.b64decode(enc)
# iv = enc[:16]
# cipher = AES.new(self.key, AES.MODE_CBC, iv)
# return unpad(cipher.decrypt(enc[16:]))

0 comments on commit 2021d42

Please sign in to comment.