Skip to content

Commit

Permalink
Version 1.0.6
Browse files Browse the repository at this point in the history
* Improved some security measures.
* Some Bug fixes.
  • Loading branch information
nozwock committed Feb 4, 2020
1 parent d4675f1 commit d3f8898
Show file tree
Hide file tree
Showing 7 changed files with 80 additions and 53 deletions.
2 changes: 2 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,8 @@ And, the source code is not well documented either at the moment.
## Specific Dependencies
* tabulate
* pycrypto
* tkinter
* xlsxwriter

## Usage
* Clone the repo, and then
Expand Down
4 changes: 3 additions & 1 deletion requirements.txt
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
tabulate
pycrypto
pycrypto
tkinter
xlsxwriter
23 changes: 14 additions & 9 deletions votm_edt.py
Original file line number Diff line number Diff line change
Expand Up @@ -287,7 +287,7 @@ def __init__(self, parent: Win):
def wrt(fle: int, cfg: str):
"""Writes Default config. files."""
with open(rf'{Write_Default.loc}\{Write_Default.fles[fle]}', 'w') as f:
cfg = Crypt().encrypt(str(cfg), SECRET_KEY)
cfg = Crypt().encrypt(str(cfg), Reg().get(SECRET_KEY))
f.write(cfg)
f.flush()

Expand Down Expand Up @@ -1145,7 +1145,7 @@ def crt_mrg_fle(self):
f.flush()
f.write('))')
with open(dir_fle, 'r') as f:
rd = Crypt().encrypt(str(f.read()), SECRET_KEY)
rd = Crypt().encrypt(str(f.read()), Reg().get(SECRET_KEY))
with open(dir_fle, 'w') as f:
f.write(rd)
mg.showinfo(
Expand All @@ -1160,9 +1160,14 @@ def opn_mrg_fles(self):
fdir = path.dirname(__file__)
self.fname = askopenfilenames(
parent=self, initialdir=fdir, filetypes=(('Merge Files', '*.mrg'),))
for item in range(len(self.fname)):
if self.fname[item] not in self.mrg_drctr.get(0, tk.END):
self.mrg_drctr.insert(tk.END, self.fname[item])
if len([j for j in [i.split('/')[-1].split('.')[0] for i in self.fname] if (j[0] in __import__('string').ascii_letters and all([_ in \
__import__('string').ascii_letters+__import__('string').digits for _ in j]))]) == len([i.split('/')[-1].split('.')[0] for i in self.fname]):
for item in range(len(self.fname)):
if self.fname[item] not in self.mrg_drctr.get(0, tk.END):
self.mrg_drctr.insert(tk.END, self.fname[item])
else:
mg.showerror(
'Error', 'Make sure that the Filenames start with a Letter & also that they don\'t contain any Spaces or Special Characters!', parent=self)

def rmv_item(self):
"""Removes selected merge file directory from the listbox."""
Expand All @@ -1189,7 +1194,7 @@ def do_mrg(self):
for dirc in mrg:
with open(dirc, 'r') as f:
mrg_tbl_data.append(
eval(Crypt().decrypt(str(f.read()), SECRET_KEY)))
eval(Crypt().decrypt(str(f.read()), Reg().get(SECRET_KEY))))
except FileNotFoundError:
mg.showerror(
'Error', 'No such file(s) found.', parent=self)
Expand Down Expand Up @@ -1439,7 +1444,7 @@ def chng_pswd(self, pswd: tk.Entry):
try:
cfg['passwd'] = pswd.get().strip()
self.reg = Reg()
self.reg.setx(ENV_KEY, Crypt().encrypt(str(cfg), SECRET_KEY))
self.reg.setx(ENV_KEY, Crypt().encrypt(str(cfg), self.reg.get(SECRET_KEY)))
self.reg.close()
pswd.delete(0, tk.END)
pswd.insert(0, Access_Config().bse_config['passwd'])
Expand All @@ -1462,7 +1467,7 @@ def chng_key(self, pswd: tk.Entry):
cfg['key'] = pswd.get().strip()
self.reg = Reg()
self.reg.setx(ENV_KEY, Crypt().encrypt(
str(cfg), SECRET_KEY))
str(cfg), self.reg.get(SECRET_KEY)))
self.reg.close()
pswd.delete(0, tk.END)
pswd.insert(0, Access_Config().bse_config['key'])
Expand Down Expand Up @@ -1698,7 +1703,7 @@ def __init__(self):
with open(rf'{Tokens.LOC}\{Tokens.FL}', 'r') as f:
_tkns = ''
try:
tkn_lst = eval(Crypt().decrypt(str(f.read()), SECRET_KEY))
tkn_lst = eval(Crypt().decrypt(str(f.read()), Reg().get(SECRET_KEY)))
line = len(tkn_lst)//8
if (len(tkn_lst)/8)-line > 0:
line += 1
Expand Down
3 changes: 2 additions & 1 deletion votm_vte.py
Original file line number Diff line number Diff line change
Expand Up @@ -356,7 +356,8 @@ def __init__(self, parent: Win):
for i in range(1, 3):
exec(
f"cls_txt{i} = tk.Label(p{i}, text='', font=('Segoue UI', 12, 'bold'), bg='#C39EFF', fg='#FFFFFF')")
exec(f"cls_txt{i}.pack(side='top', anchor='n', fill='x', pady=(2,0))")
exec(
f"cls_txt{i}.pack(side='top', anchor='n', fill='x', pady=(2,0))")
if sel == 1:
txt = f'{ch_clss}\' {ch_sec}'
exec(f"cls_txt{i}.config(text=txt)")
Expand Down
31 changes: 22 additions & 9 deletions votmapi/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -615,17 +615,26 @@ class Default_Config:


class Write_Default:
"""Writes Default config file which doesn't exist already, in the /roaming directory."""
"""Writes Default config file which doesn't exist already, in the /ProgramData directory."""
exist = 0
loc = os.getenv('ALLUSERSPROFILE')
loc = os.getenv('ALLUSERSPROFILE')+r'\Votm'
fles = ['cand.vcon', 'clss.vcon']

def __init__(self):
Write_Default.exist = 0
self.crypt = Crypt()
self.reg = Reg()
if not os.path.exists(Write_Default.loc):
os.mkdir(Write_Default.loc)
eval_lst = [os.path.exists(rf'{Write_Default.loc}\{f}')
== False for f in Write_Default.fles]

try:
self.reg.get(SECRET_KEY)
except FileNotFoundError:
Write_Default.exist = 1
self.reg.setx(SECRET_KEY, self.rand(16))

if any(eval_lst):
Write_Default.exist = 1
j = 0
Expand All @@ -636,24 +645,29 @@ def __init__(self):
else:
self.wrt_clss()
j += 1

try:
self.reg.get(ENV_KEY)
except FileNotFoundError:
Write_Default.exist = 1
self.reg.setx(ENV_KEY, self.crypt.encrypt(
Default_Config.base_config, SECRET_KEY))
Default_Config.base_config, self.reg.get(SECRET_KEY)))
self.reg.close()

@staticmethod
def rand(size=8, chars=__import__('string').ascii_letters + __import__('string').digits + "@#$&"):
return ''.join(__import__('random').choice(chars) for _ in range(size))

def wrt_cand(self):
"""Writes Candidate file."""
with open(rf'{Write_Default.loc}\{Write_Default.fles[0]}', 'w') as f:
f.write(self.crypt.encrypt(
Default_Config.candidate_config, SECRET_KEY))
Default_Config.candidate_config, self.reg.get(SECRET_KEY)))

def wrt_clss(self):
"""Writes Class&Sec file."""
with open(rf'{Write_Default.loc}\{Write_Default.fles[1]}', 'w') as f:
f.write(self.crypt.encrypt(Default_Config.clss_config, SECRET_KEY))
f.write(self.crypt.encrypt(Default_Config.clss_config, self.reg.get(SECRET_KEY)))


class Access_Config:
Expand All @@ -665,14 +679,13 @@ def __init__(self):
self.crypt = Crypt()
self.reg = Reg()
bse_str = self.reg.get(ENV_KEY)
self.reg.close()
bse_str = self.crypt.decrypt(bse_str, SECRET_KEY)
bse_str = self.crypt.decrypt(bse_str, self.reg.get(SECRET_KEY))
with open(rf'{loc}\{fles[0]}', 'r') as f:
cand_str = f.read()
cand_str = self.crypt.decrypt(cand_str, SECRET_KEY)
cand_str = self.crypt.decrypt(cand_str, self.reg.get(SECRET_KEY))
with open(rf'{loc}\{fles[1]}', 'r') as f:
clss_str = f.read()
clss_str = self.crypt.decrypt(clss_str, SECRET_KEY)
clss_str = self.crypt.decrypt(clss_str, self.reg.get(SECRET_KEY))

self.bse_config = eval(bse_str)
self.cand_config = eval(cand_str)
Expand Down
10 changes: 4 additions & 6 deletions votmapi/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,18 +17,16 @@
"""

"""
Version 1.0.52 changes:
> Improved Interface for Result window.
> Some exceptions handeled during merge.
> Added "Export to Excel" for tokens.
Version 1.0.6 changes:
> Improved some security measures.
> Some Bug fixes.
"""

__author__ = 'Sagar Kumar'
__version__ = '1.0.52'
__version__ = '1.0.6'

ENV_KEY = 'BASE_VCON_CONFIG'
SECRET_KEY = 'SykO@qd5ADyx7FpAzOiH2yqoeoQEg300'
SECRET_KEY = 'SEC_VCON_KEY'

__license__ = \
"""
Expand Down
60 changes: 33 additions & 27 deletions votmapi/logic.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,23 +20,26 @@
from random import choice
from string import digits
from Crypto.Cipher import AES
from Crypto.Hash import SHA256
from Crypto import Random
from collections import OrderedDict
from tkinter import messagebox as mg
from base64 import b64encode, b64decode
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from votmapi.__main__ import SECRET_KEY
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from winreg import (ConnectRegistry, OpenKey, SetValueEx, DeleteKeyEx,
QueryValueEx, CloseKey, HKEY_LOCAL_MACHINE, KEY_ALL_ACCESS, REG_EXPAND_SZ)


class Tokens:
"""Handles Tokens generation, saving and to get a specific token."""
LOC = os.getenv('ALLUSERSPROFILE')
LOC = os.getenv('ALLUSERSPROFILE')+r'\Votm'
FL = 'tkn.vcon'

def __init__(self, master, entries=None):
self.master = master
self.crypt = Crypt()
self.reg = Reg()

if entries != None:
try:
Expand All @@ -53,7 +56,7 @@ def key_gen(size=8, chars=digits):
try:
self.tkn_read = eval(f.read())
self.tkn_read = self.crypt.decrypt(
str(self.tkn_read), SECRET_KEY)
str(self.tkn_read), self.reg.get(SECRET_KEY))
except:
self.tkn_read = []

Expand All @@ -70,7 +73,7 @@ def key_gen(size=8, chars=digits):
val = key_gen()
if val is not None:
tkn.append(val)
tkn = self.crypt.encrypt(str(tkn), SECRET_KEY)
tkn = self.crypt.encrypt(str(tkn), self.reg.get(SECRET_KEY))
f.write(f'{tkn}')
mg.showinfo(
'Voting Master', f'{self.entries} Token(s) Generated.', parent=self.master)
Expand All @@ -79,12 +82,12 @@ def key_gen(size=8, chars=digits):

def get(self, val: str):
with open(rf'{Tokens.LOC}\{Tokens.FL}', 'r') as f:
tkn_lst = eval(self.crypt.decrypt(str(f.read()), SECRET_KEY))
tkn_lst = eval(self.crypt.decrypt(str(f.read()), self.reg.get(SECRET_KEY)))
try:
ind = tkn_lst.index(val)
del tkn_lst[ind]
with open(rf'{Tokens.LOC}\{Tokens.FL}', 'w') as f:
tkn_lst = self.crypt.encrypt(str(tkn_lst), SECRET_KEY)
tkn_lst = self.crypt.encrypt(str(tkn_lst), self.reg.get(SECRET_KEY))
f.write(str(tkn_lst))
return True
except:
Expand All @@ -96,7 +99,7 @@ def check(self):
try:
with open(rf'{Tokens.LOC}\{Tokens.FL}', 'r') as f:
tkn_lst = f.read()
tkn_lst = eval(self.crypt.decrypt(str(tkn_lst), SECRET_KEY))
tkn_lst = eval(self.crypt.decrypt(str(tkn_lst), self.reg.get(SECRET_KEY)))
if len(tkn_lst) == 0:
mg.showerror('Error', 'No Tokens in the Token file.',
parent=self.master)
Expand All @@ -107,29 +110,32 @@ def check(self):
return False


#CBC method with PKCS#7 padding
class Crypt:
def __init__(self, salt='SlTKeYOpHygTYkP3'):
def __init__(self, salt=Random.new().read(AES.block_size)):
self.salt = salt
self.enc_dec_method = 'utf-8'

def encrypt(self, str_to_enc, str_key):
try:
aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
hx_enc = aes_obj.encrypt(str_to_enc)
mret = b64encode(hx_enc).decode(self.enc_dec_method)
return mret
except:
pass

def decrypt(self, enc_str, str_key):
try:
aes_obj = AES.new(str_key, AES.MODE_CFB, self.salt)
str_tmp = b64decode(enc_str.encode(self.enc_dec_method))
str_dec = aes_obj.decrypt(str_tmp)
mret = str_dec.decode(self.enc_dec_method)
return mret
except:
self.enc_dec_method = 'latin-1'

def encrypt(self, src, key, encode=True):
src = src.encode()
key = SHA256.new(key.encode()).digest()
aes_obj = AES.new(key, AES.MODE_CBC, self.salt)
padd = AES.block_size - len(src) % AES.block_size
src += bytes([padd]) * padd
hx_enc = self.salt + aes_obj.encrypt(src)
return b64encode(hx_enc).decode(self.enc_dec_method) if encode else hx_enc

def decrypt(self, src, key, decode=True):
if decode:
str_tmp = b64decode(src.encode(self.enc_dec_method))
key = SHA256.new(key.encode()).digest()
salt = str_tmp[:AES.block_size]
aes_obj = AES.new(key, AES.MODE_CBC, salt)
str_dec = aes_obj.decrypt(str_tmp[AES.block_size:])
padd = str_dec[-1]
if str_dec[-padd:] != bytes([padd]) * padd:
pass
return str_dec[:-padd].decode(self.enc_dec_method)


class Dicto:
Expand Down

0 comments on commit d3f8898

Please sign in to comment.