def verifyMsgSign(self, msg, sign, fddata, th): "如果验证成功则发送成功消息,否则发送验证失败并关闭该线程" _cfg = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfg.GetKeyPath()) if _rsa.VerifyByPubkey(msg, sign, fddata.GetData("peername")) == False: msghead = self.packetMsg(MagicNum.MsgTypec.IDENTITYVERIFYFAILED, 0) fddata.SetData("outdata", msghead) th.ModifyInToOut(fddata.GetData("sockfd")) showmsg = "签名验证失败" else: #生成自己的会话密钥 from CryptoAlgorithms import HashBySha1 _hbs = HashBySha1.HashBySha1() fddata.SetData( "fddatakey", _hbs.GetHash( str(fddata.GetData("dhkey").getKey(string.atol(msg))), MagicNum.HashBySha1c.HEXADECIMAL)) if fddata.GetData("threadtype") == CommonData.ThreadType.CONNECTAP: msghead = self.packetMsg(MagicNum.MsgTypec.AUDITDHGENERATE, 0) else: msghead = self.packetMsg( MagicNum.MsgTypec.AUDITRETURNDHGENERATE, 0) fddata.SetData("outdata", msghead) th.ModifyInToOut(fddata.GetData("sockfd")) showmsg = "生成会话密钥:" + fddata.GetData("fddatakey") self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT, showmsg, True)
def HandleMsg(self,bufsize,fddata,th): if not fddata.GetData("currentbytes") and fddata.threadtype != CommonData.ThreadType.CONNECTAP: _cfg = ConfigData.ConfigData() _dir = _cfg.GetMediaPath() + "/auditserver/" recvbuffer = NetSocketFun.NetSocketRecv(fddata.GetData("sockfd"),bufsize) fddata.SetData("control.filename",_dir + NetSocketFun.NetUnPackMsgBody(recvbuffer)[0]) if not fddata.GetData("currentbytes"): self.handleFileBegin(bufsize, fddata) _filebuffer = fddata.GetData("file").read(CommonData.MsgHandlec.FILEBLOCKSIZE) fddata.SetData("currentbytes",fddata.GetData("currentbytes") + len(_filebuffer)) msgbody = NetSocketFun.NetPackMsgBody([_filebuffer]) if fddata.GetData("currentbytes") == fddata.totalbytes: msghead = self.packetMsg(MagicNum.MsgTypec.SENDFILEOVER,len(msgbody)) fddata.GetData("file").close() fddata.SetData("currentbytes",0) _filename = fddata.GetData("filename")[-fddata.GetData("filename")[::-1].index("/"):].encode("utf-8") filesize = float(fddata.GetData("totalbytes")) / (1024 * 1024) showmsg = "文件发送完毕:\n(1)文件名:" + _filename + "\n(2)文件大小(MB):" + str(filesize) self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT,showmsg,True) else: msghead = self.packetMsg(MagicNum.MsgTypec.SENDFILEBUFFER,len(msgbody)) fddata.SetData("outdata", msghead + msgbody) th.ModifyInToOut(fddata.GetData("sockfd"))
def verifyMsgSign(self, msg, sign, fddata, th): "如果验证成功则发送公钥,否则发送验证失败并关闭该线程" _cfg = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfg.GetKeyPath()) if self.verify(_rsa, msg[0], sign[0], fddata) == False or self.verify( _rsa, msg[1], sign[1], fddata) == False: msghead = self.packetMsg(MagicNum.MsgTypec.IDENTITYVERIFYFAILED, 0) fddata.SetData("outdata", msghead) th.ModifyInToOut(fddata.GetData("sockfd")) else: #生成自己的会话密钥 _dhkey = DiffieHellman.DiffieHellman(string.atol(msg[0])) from CryptoAlgorithms import HashBySha1 _hbs = HashBySha1.HashBySha1() fddata.SetData( "fddatakey", _hbs.GetHash(str(_dhkey.getKey(string.atol(msg[1]))), MagicNum.HashBySha1c.HEXADECIMAL)) _dhpubkey = str(_dhkey.getPubkey()) msglist = [_dhpubkey, _rsa.SignByPrikey(_dhpubkey)] msgbody = NetSocketFun.NetPackMsgBody(msglist) msghead = self.packetMsg(MagicNum.MsgTypec.SENDDHPUBKEY, len(msgbody)) fddata.SetData("outdata", msghead + msgbody) th.ModifyInToOut(fddata.GetData("sockfd"))
def packMsgBody(self, fddata): "将会话密钥与A组参数用公钥加密,将采样hash用私钥加密(签名)" if fddata.GetData("threadtype") == CommonData.ThreadType.CONNECTAP: _agroup = self.APgetAgroupHashAndParam(fddata) elif fddata.GetData("threadtype") == CommonData.ThreadType.ACCETPNO: _agroup = self.NOgetAgroupHashAndParam(fddata) self.deltempFile(fddata) _cfd = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfd.GetKeyPath()) msglist = (str(fddata.GetData("fddatakey")), ) + _agroup[0] _plaintext = NetSocketFun.NetPackMsgBody(msglist) _pubkeyMsg = _rsa.EncryptByPubkey(_plaintext.encode("ascii"), fddata.GetData("peername")) _hbs = HashBySha1.HashBySha1() _sign = _rsa.SignByPrikey( _hbs.GetHash(_agroup[1].encode("ascii"), MagicNum.HashBySha1c.HEXADECIMAL)) msglist = [_pubkeyMsg, _sign, _agroup[1].encode("ascii")] _msgbody = NetSocketFun.NetPackMsgBody(msglist) showmsg = "发送采样结果:\n(1)A组参数:\n(帧总数,分组参数,帧间隔位数,混沌初值,分支参数)\n(".decode("utf8") + \ ",".join(_agroup[0]) + ")\n(2)A组采样:".decode("utf8") + \ CommonData.MsgHandlec.SHOWPADDING.join(NetSocketFun.NetUnPackMsgBody(_agroup[1])) \ + "\n(3)A组采样签名:".decode("utf8") + _sign showmsg += "\nCP用AP的公钥加密采样参数A" showmsg += "\nCP用其私钥加密比特串承诺值" showmsg += "\nCP发送加密的A组参数和加密的比特串承诺值,以及公钥加密TID发送给AP" showmsg += "\n等待文件验证..." self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT, showmsg, True) return _msgbody
def verifyMsgSign(self, msg, sign, session): "如果验证成功则发送成功消息,否则发送验证失败并关闭该线程" _cfg = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfg.GetKeyPath()) if _rsa.VerifyByPubkey(msg, sign, session.peername) == False: msghead = self.packetMsg(MagicNum.MsgTypec.IDENTITYVERIFYFAILED, 0) NetSocketFun.NetSocketSend(session.sockfd, msghead) session.stop() showmsg = "签名验证失败" else: #生成自己的会话密钥 from CryptoAlgorithms import HashBySha1 _hbs = HashBySha1.HashBySha1() session.sessionkey = _hbs.GetHash( str(session.dhkey.getKey(string.atol(msg))), MagicNum.HashBySha1c.HEXADECIMAL) if session.threadtype == CommonData.ThreadType.CONNECTAP: msghead = self.packetMsg(MagicNum.MsgTypec.AUDITDHGENERATE, 0) else: msghead = self.packetMsg( MagicNum.MsgTypec.AUDITRETURNDHGENERATE, 0) NetSocketFun.NetSocketSend(session.sockfd, msghead) showmsg = "生成会话密钥:" + session.sessionkey self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT, showmsg, True)
def __init__(self, view, aparams, bparams): super(DataHandleCmd, self).__init__(view) _cfg = ConfigData.ConfigData() self.__mediapath = _cfg.GetYVectorFilePath() self.__aparams = aparams self.__bparams = bparams
def getFrameNumAndFileSize(self): "获取目录下文件数即帧的数目" _cfg = ConfigData.ConfigData() _fullpath = self.view.filename _filename = _fullpath[-_fullpath[::-1].index("/"):_fullpath.index(".")] _dirname = _cfg.GetYVectorFilePath() + _filename self.__framenum = sum([len(files) for root,dirs,files in os.walk(_dirname)]) self.__filesize = os.path.getsize(self.view.filename)
def getDhpAndga(self,session): "获取迪菲赫尔慢公钥和大素数" p = DiffieHellman.GetBigPrime() session.dhkey = DiffieHellman.DiffieHellman(p) _cfg = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfg.GetKeyPath()) _dhpubkey = str(session.dhkey.getPubkey()) return str(p) , _dhpubkey ,_rsa.SignByPrikey(str(p)),_rsa.SignByPrikey(_dhpubkey)
def getFrameNum(self, filename): "获取目录下文件数即帧的数目" import os _cfg = ConfigData.ConfigData() _dirname = _cfg.GetYVectorFilePath() + filename[:filename.index(".")] _framenum = sum( [len(files) for root, dirs, files in os.walk(_dirname)]) return str(_framenum)
def getDhpAndga(self, fddata): "获取迪菲赫尔慢公钥和大素数" p = DiffieHellman.GetBigPrime() fddata.SetData("dhkey", DiffieHellman.DiffieHellman(p)) _cfg = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfg.GetKeyPath()) _dhpubkey = str(fddata.GetData("dhkey").getPubkey()) return str(p), _dhpubkey, _rsa.SignByPrikey( str(p)), _rsa.SignByPrikey(_dhpubkey)
def createHeaderButton(self): "创建头部按钮" from GlobalData import ConfigData _config = ConfigData.ConfigData() jpg = wx.Image(_config.GetIcoPath(), wx.BITMAP_TYPE_JPEG).ConvertToBitmap() fileButton = wx.BitmapButton(self, -1, jpg) self.Bind(wx.EVT_BUTTON, self.registerButtonFun, fileButton) self.sizer.Add(fileButton, 0, wx.EXPAND, 5) self.sizer.Add(wx.StaticLine(self), 0, wx.EXPAND | wx.ALL, 5)
def verifySignleSign(self, sampling, sign, session): "验证C组特征提取是否符合收到的C组签名" _cfd = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfd.GetKeyPath()) _hbs = HashBySha1.HashBySha1() return _rsa.VerifyByPubkey( _hbs.GetHash(sampling.encode("ascii"), MagicNum.HashBySha1c.HEXADECIMAL), sign, session.peername)
def registerListen(self): self.listenfd = socket.socket() self.listenfd.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) config = ConfigData.ConfigData() _listenAddress = config.GetLocalServerAddress() try: self.listenfd.bind((_listenAddress[0], int(_listenAddress[1]))) except Exception, e: self.listenfd.close() print e return MagicNum.NetAcceptc.BINDERROR
def deltempFile(self, session): import os _cfg = ConfigData.ConfigData() _mediapath = _cfg.GetYVectorFilePath() _media = _mediapath + "out.ts" os.remove(_media) _dir = _mediapath + session.filename[:session.filename.index(".")] for root, dirs, files in os.walk(_dir, topdown=False): for name in files: os.remove(os.path.join(root, name)) os.rmdir(root)
def StartNetConnect(self): "连接服务器并开启网络线程" config = ConfigData.ConfigData() _auditAddress = config.GetAuditServerAddress() try: self.__Sockfd.connect((_auditAddress[0], int(_auditAddress[1]))) except: return MagicNum.NetConnectc.NOTCONNECT self.__netThread = NetThread.NetThread(self.__Sockfd.dup(), self, CommonData.ThreadType.CONNECTAP) self.__netThread.setDaemon(True) self.__netThread.start()
def getFrameFileData(self, frame, filename): "获取文件数据" self.__frameData = [] _cfg = ConfigData.ConfigData() _path = _cfg.GetYVectorFilePath() + filename + "/" + str( frame) + ".yvector" with open(_path) as f: for line in f.xreadlines(): self.__frameData.append(line[:-1].split(",")) _len = len(self.__frameData) del self.__frameData[_len - 1] del self.__frameData[_len - 2]
def createHeaderButton(self): "创建头部按钮" from GlobalData import ConfigData try: _config = ConfigData.ConfigData() jpg = wx.Image(_config.GetIcoPath(),wx.BITMAP_TYPE_JPEG).ConvertToBitmap() fileButton=wx.BitmapButton(self,-1,jpg) self.Bind(wx.EVT_BUTTON,self.registerButtonFun,fileButton) self.sizer.Add(fileButton, 0, wx.EXPAND, 5) self.sizer.Add(wx.StaticLine(self), 0, wx.EXPAND|wx.ALL, 5) except: wx.MessageBox("配置文件不存在或路径错误","错误",wx.ICON_ERROR|wx.YES_DEFAULT)
def StartNetConnect(self): "连接服务器并开启网络线程" config = ConfigData.ConfigData() _auditAddress = config.GetAuditServerAddress() try: self.__Sockfd.connect((_auditAddress[0], int(_auditAddress[1]))) print self.__Sockfd.fileno(), "confd" self.__netManage = ComThreadManage.ComThreadManage() self.__netManage.run(4) CommunicationThread.CommunicationThread.epManage.AddNewSockfd( self.__Sockfd, CommonData.ThreadType.CONNECTAP) except: return MagicNum.NetConnectc.NOTCONNECT
def getFrameNum(self): "获取目录下文件数即帧的数目" try: _dir = self.filename except: return _cfg = ConfigData.ConfigData() _filename = _dir[-_dir[::-1].index("/"):_dir.index(".")] _mediadir = _cfg.GetYVectorFilePath() + _filename self.__framenum = sum([len(files) for root, dirs, files in os.walk(_mediadir)]) for _sc in [self.__AgroupSpin, self.__AgapSpin, self.__BgroupSpin, self.__BgapSpin]: _sc.SetRange(1, self.__framenum) _sc.SetValue(1)
def handleDhkeyAndCgroupParam(self, msglist, session): "验证接收到的会话密钥是否相同,如果相同则获取C组参数和hash" _cfd = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfd.GetKeyPath()) _plaintext = _rsa.DecryptByPrikey(msglist[0]) _plist = NetSocketFun.NetUnPackMsgBody(_plaintext) if session.sessionkey == _plist[0]: self.__cparam = _plist[1:] self.__csign = msglist[1] self.__chash = msglist[2] return True else: showmsg = "会话密钥验证失败:会话密钥:" + session.sessionkey self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT, showmsg, True) return False
def packMsgBody(self, session): "将会话密钥与A组参数用公钥加密,将特征提取hash用私钥加密(签名)" if session.threadtype == CommonData.ThreadType.CONNECTAP: _agroup = self.APgetAgroupHashAndParam(session) elif session.threadtype == CommonData.ThreadType.ACCETPNO: _agroup = self.NOgetAgroupHashAndParam(session) import os _dir = session.filename _meidaPath = self.__mediapath + "/auditserver/" + _dir[-_dir[::-1]. index("/"):] filesize = float(os.path.getsize(_meidaPath)) / (1024 * 1024) showmsg = "特征提取完成:\n(1)I帧总数:" + self.getFrameNum(_dir[-_dir[::-1].index("/"):]) + \ "\n(2)文件大小(MB):" + str(filesize) self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT, showmsg, True) self.deltempFile(session) _cfd = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfd.GetKeyPath()) msglist = (str(session.sessionkey), ) + _agroup[0] _plaintext = NetSocketFun.NetPackMsgBody(msglist) _pubkeyMsg = _rsa.EncryptByPubkey(_plaintext.encode("ascii"), session.peername) _hbs = HashBySha1.HashBySha1() _sign = _rsa.SignByPrikey( _hbs.GetHash(_agroup[1].encode("ascii"), MagicNum.HashBySha1c.HEXADECIMAL)) msglist = [_pubkeyMsg, _sign, _agroup[1].encode("ascii")] _msgbody = NetSocketFun.NetPackMsgBody(msglist) showmsg = "发送特征提取结果:\n(1)A组参数:\n(帧总数,分组参数,帧间隔位数,混沌初值,分支参数)\n(".decode("utf8") + \ ",".join(_agroup[0]) + ")\n(2)A组特征提取:".decode("utf8") + \ CommonData.MsgHandlec.SHOWPADDING.join(NetSocketFun.NetUnPackMsgBody(_agroup[1])) \ + "\n(3)A组特征提取签名:".decode("utf8") + _sign showmsg += "\nCP用AP的公钥加密特征提取参数A" showmsg += "\nCP用其私钥加密比特串承诺值" showmsg += "\nCP发送加密的A组参数和加密的比特串承诺值,以及公钥加密TID发送给AP" showmsg += "\n等待文件验证..." self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT, showmsg, True) return _msgbody
def getFileList(self): "获取文件列表" _filelist = [] _cfg = ConfigData.ConfigData() _mediaPath = _cfg.GetMediaPath() if not os.path.exists(_mediaPath): os.mkdir(_mediaPath) _db = MediaTable.MediaTable() _db.Connect() _res = _db.Search("select * from MediaTable") _db.CloseCon() for index in range(len(_res)): status = "未审核" if _res == []: return [] if _res[index][6] == MagicNum.MediaTablec.AUDIT: status = "已审核" _singleFile = [_res[index][0], _res[index][5], status] _filelist.append(_singleFile) return _filelist
def evtBtnDelClick(self, evt): "删除按钮触发事件" if self.__gridCurPos == -1: return _filename = self.__grid.GetCellValue(self.__gridCurPos, 0) _owner = self.__grid.GetCellValue(self.__gridCurPos, 1) _cfg = ConfigData.ConfigData() _path = _cfg.GetMediaPath() + "/auditserver/" + _filename _db = MediaTable.MediaTable() _db.Connect() _db.deleteMedia(_filename) _db.CloseCon() try: os.remove(_path) except: pass self.__gridCurPos = -1 self.refreshStaticText([_filename, "删除"]) self.refreshFileList()
def HandleMsg(self,bufsize,session): if not session.currentbytes and session.threadtype != CommonData.ThreadType.CONNECTAP: _cfg = ConfigData.ConfigData() _dir = _cfg.GetMediaPath() + "/auditserver/" recvbuffer = NetSocketFun.NetSocketRecv(session.sockfd,bufsize) session.control.filename = _dir + NetSocketFun.NetUnPackMsgBody(recvbuffer)[0] if not session.currentbytes: self.handleFileBegin(bufsize, session) _filebuffer = session.file.read(CommonData.MsgHandlec.FILEBLOCKSIZE) session.currentbytes += len(_filebuffer) msgbody = NetSocketFun.NetPackMsgBody([_filebuffer]) if session.currentbytes == session.totalbytes: msghead = self.packetMsg(MagicNum.MsgTypec.SENDFILEOVER,len(msgbody)) session.file.close() session.currentbytes = 0 _filename = session.filename[-session.filename[::-1].index("/"):].encode("utf-8") filesize = float(session.totalbytes) / (1024 * 1024) showmsg = "文件发送完毕:\n(1)文件名:" + _filename + "\n(2)文件大小(MB):" + str(filesize) self.sendViewMsg(CommonData.ViewPublisherc.MAINFRAME_APPENDTEXT,showmsg,True) else: msghead = self.packetMsg(MagicNum.MsgTypec.SENDFILEBUFFER,len(msgbody)) NetSocketFun.NetSocketSend(session.sockfd, msghead + msgbody)
def __init__(self): super(RecvObtainFile, self).__init__() _cfg = ConfigData.ConfigData() self.__mediapath = _cfg.GetMediaPath()
def __init__(self, filename): "获取可执行程序路径" from GlobalData import ConfigData _cfg = ConfigData.ConfigData() self.__pathAndArgs = _cfg.GetFfmpegPathAndArgs() self.__filename = filename
if not os.path.exists(_ownPath): if not os.path.exists(self.__keyPath): os.mkdir(self.__keyPath) os.mkdir(_ownPath) _rsa = Rsa.Rsa(self.__keyPath) _rsa.GenerateKeypair(CommonData.Rsac.KEYLEN) def GetPubkeyStr(self, name): _path = self.__keyPath + "/" + name + "/pubkey.pkl" with open(_path, 'r') as f: pkeystr = f.read() return pkeystr def WritePubkeyStr(self, name, pkeystr): import os _dir = self.__keyPath + "/" + name _path = _dir + "/pubkey.pkl" if not os.path.exists(_dir): os.mkdir(_dir) with open(_path, 'w') as f: f.write(pkeystr) if __name__ == "__main__": r = RsaKeyExchange() r.GenerateRsaKey() _s = r.GetPubkeyStr("own") r.WritePubkeyStr("name", _s) _cfd = ConfigData.ConfigData() _rsa = Rsa.Rsa(_cfd.GetKeyPath())
def __init__(self): super(SendAgroupSignAndParam, self).__init__() _cfg = ConfigData.ConfigData() self.__mediapath = _cfg.GetMediaPath()
def __init__(self): _cfd = ConfigData.ConfigData() self.__keyPath = _cfd.GetKeyPath()
def __init__(self, filename): "分别为文件名和分组数(参数Gt)" _cfg = ConfigData.ConfigData() self.__filename = _cfg.GetYVectorFilePath() + filename self.__gt = CommonData.Rsac.PLAINTLEN / CommonData.HashBySha1c.HEXHASH