Secure Document Transmission System Feature Implementation
Core Database Objects
User Profile Schema
class UserProfile(models.Model):
uid = models.CharField(max_length=8, primary_key=True)
handle = models.CharField(max_length=50)
email_addr = models.EmailField()
pass_hash = models.CharField(max_length=256)
salt_val = models.CharField(max_length=15)
permissions = models.IntegerField(default=0)
pubkey = models.CharField(max_length=128, blank=True, null=True)
prikey = models.CharField(max_length=128, blank=True, null=True)
avatar_img = models.ImageField(upload_to='avatars/', null=True, blank=True)
def __str__(self):
return self.handle
uid acts as the primary identifier. handle stores the visible username. The pass_hash column holds a salted SM3 digest. salt_val contains the randomly generated salt. permissions encodes the role; 0 for regular users, 1 for administrators. Key pairs for asymmetric operations reside in pubkey and prikey, while avatar_img stores the profile picture.
Document Record Schema
class Document(models.Model):
doc_ref = models.AutoField(primary_key=True)
owner = models.CharField(max_length=255)
title = models.CharField(max_length=255)
originator = models.CharField(max_length=255)
created = models.DateTimeField()
classification = models.CharField(max_length=50)
recipient = models.CharField(max_length=255)
format_type = models.CharField(max_length=50)
last_editor = models.CharField(max_length=50)
last_modified = models.DateTimeField()
storage_path = models.CharField(max_length=255)
dispatched = models.IntegerField(default=0)
approved = models.IntegerField(default=0)
def __str__(self):
return self.title
Each document is identified by doc_ref. owner and originator track responsibility, while recipient identifies the intended next handler. classification indicates sensitivity, and dispatched plus approved are flags controlling workflow state.
Audit Log Schema
class Log(models.Model):
actor = models.CharField(max_length=8)
doc_name = models.CharField(max_length=255)
detail = models.CharField(max_length=2000)
def __str__(self):
return self.detail
Registration and Authentication Flow
Account Creation
When a POST request arrives at the registration endpoint, the system validates uniqueness of the supplied uid. A 15-character random string is generated and preserved as the salt. The password is combined with this salt and processed through digest_credential to produce a salted SM3 hash. An ECC key pair is constructed and stored alongside the newly created UserProfile record. An audit entry is inserted before redirecting to the login screen after a brief delay.
def register_handler(request):
if request.method == 'POST':
uid = request.POST['uid']
handle = request.POST['handle']
email_addr = request.POST['email_addr']
plain_pass = request.POST['pass_hash']
if UserProfile.objects.filter(uid=uid).exists():
messages.error(request, 'Identifier already taken.')
return redirect('register')
salt_val = make_salt(15)
digested = digest_credential(plain_pass, salt_val)
secret_key = PrivateKey()
public_component = secret_key.publicKey()
profile = UserProfile.objects.create(
uid=uid,
handle=handle,
email_addr=email_addr,
pass_hash=digested,
salt_val=salt_val,
pubkey=public_component.toString(compressed=False),
prikey=secret_key.toString(),
avatar_img='avatars/default_avatar.png'
)
profile.save()
Log.objects.create(
actor=handle,
doc_name="N/A",
detail=f'{handle} registered at {timezone.now()}.'
)
messages.success(request, 'Registration complete. Please sign in.')
time.sleep(3)
return redirect('login')
return render(request, 'register.html')
Session Sign-on
During login, the supplied identifier is used to fetch the user profile. The stored salt is retrieved and combined with the provided password to compute a salted hash. If this matches the stored pass_hash, session keys (user_id and username) are populated and the login event is logged.
def login_handler(request):
if request.method == 'POST':
credential = request.POST['credential']
plain_pass = request.POST['pass_hash']
try:
profile = UserProfile.objects.get(uid=credential)
except UserProfile.DoesNotExist:
messages.error(request, 'Invalid credentials.')
return redirect('login')
challenge = digest_credential(plain_pass, profile.salt_val)
if challenge == profile.pass_hash:
request.session['user_id'] = profile.uid
request.session['username'] = profile.handle
Log.objects.create(
actor=profile.handle,
doc_name="N/A",
detail=f'{profile.handle} signed in at {timezone.now()}.'
)
time.sleep(3)
return redirect('index')
else:
messages.error(request, 'Invalid credentials.')
return redirect('login')
return render(request, 'login.html')
Password Salting Utility
def digest_credential(secret, salt):
raw_hash = sm3_hash(func.bytes_to_list(bytes(secret, encoding='utf-8')))
return raw_hash[:4] + salt + raw_hash[19:]
def make_salt(size=15):
pool = string.ascii_letters + string.digits + string.punctuation
return ''.join(random.choice(pool) for _ in range(size))
The digest_credential function embeds the salt into the SM3 hexadecimal output, preserving the total length.
Cryptographic Primitives
Elliptic Curve Definition
class CurveParams:
def __init__(self, a_coef, b_coef, prime_mod, order, gx, gy, label):
self.a_coef = a_coef
self.b_coef = b_coef
self.prime_mod = prime_mod
self.order = order
self.gx = gx
self.gy = gy
self.label = label
sm2_curve = CurveParams(
label="sm2_curve",
a_coef=0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFC,
b_coef=0x28E9FA9E9D9F5E344D5A9E4BCF6509A7F39789F515AB8F92DDBCBD414D940E93,
prime_mod=0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF00000000FFFFFFFFFFFFFFFF,
order=0xFFFFFFFEFFFFFFFFFFFFFFFFFFFFFFFF7203DF6B21C6052B53BBF40939D54123,
gx=0x32C4AE2C1F1981195F9904466A39C9948FE30BBFF2660BE1715A4589334C74C7,
gy=0xBC3736A2F4F6779C59BDCEE36B692153D0A9877CC62A474002DF32E52139F0A0
)
Key Pair Generation
class SecretExponent:
def __init__(self, curve=sm2_curve, exponent=None):
self.curve = curve
self.exponent = exponent or SystemRandom().randrange(1, curve.order)
def public_point(self):
px, py = scalar_mult((self.curve.gx, self.curve.gy), self.exponent,
A=self.curve.a_coef, P=self.curve.prime_mod, N=self.curve.order)
return ECPublicPoint(px, py, self.curve)
def hex_string(self):
return "{}".format(str(hex(self.exponent))[2:].zfill(64))
class ECPublicPoint:
def __init__(self, px, py, curve):
self.px = px
self.py = py
self.curve = curve
def serialize(self, compress=True):
if compress:
return str(hex(self.px))[2:]
return "{}{}".format(str(hex(self.px))[2:].zfill(64), str(hex(self.py))[2:].zfill(64))
Projective Coordinate Operations
def to_projective(pt):
x, y = pt
return (x, y, 1)
def from_projective(pt, mod):
x, y, z = pt
inv_z = modular_inverse(z, mod)
return ((x * inv_z ** 2) % mod, (y * inv_z ** 3) % mod)
def proj_double(pt, a_coef, mod):
x, y, z = pt
if not y:
return (0, 0, 0)
yy = (y ** 2) % mod
s_val = (4 * x * yy) % mod
m_val = (3 * x ** 2 + a_coef * z ** 4) % mod
nx = (m_val ** 2 - 2 * s_val) % mod
ny = (m_val * (s_val - nx) - 8 * yy ** 2) % mod
nz = (2 * y * z) % mod
return (nx, ny, nz)
def proj_add(p, q, a_coef, mod):
x1, y1, z1 = p
x2, y2, z2 = q
if not y1:
return q
if not y2:
return p
u1 = (x1 * z2 ** 2) % mod
u2 = (x2 * z1 ** 2) % mod
s1 = (y1 * z2 ** 3) % mod
s2 = (y2 * z1 ** 3) % mod
if u1 == u2:
if s1 != s2:
return (0, 0, 1)
return proj_double(p, a_coef, mod)
h = u2 - u1
r = s2 - s1
h2 = (h * h) % mod
h3 = (h * h2) % mod
u1h2 = (u1 * h2) % mod
nx = (r ** 2 - h3 - 2 * u1h2) % mod
ny = (r * (u1h2 - nx) - s1 * h3) % mod
nz = (h * z1 * z2) % mod
return (nx, ny, nz)
def scalar_mult(pt, k, A, P, N):
return from_projective(proj_mult(to_projective(pt), k, N, A, P), P)
def proj_mult(p, k, N, A, P):
if p[1] == 0 or k == 0:
return (0, 0, 1)
if k == 1:
return p
if k < 0 or k >= N:
return proj_mult(p, k % N, N, A, P)
if k % 2 == 0:
return proj_double(proj_mult(p, k // 2, N, A, P), A, P)
return proj_add(proj_double(proj_mult(p, k // 2, N, A, P), A, P), p, A, P)
def modular_inverse(val, mod):
if val == 0:
return 0
lm, hm = 1, 0
low, high = val % mod, mod
while low > 1:
ratio = high // low
nm, new = hm - lm * ratio, high - low * ratio
lm, low, hm, high = nm, new, lm, low
return lm % mod
SM2 Encryption and Signature Helpers
def apply_encryption(pub_hex, pri_hex, src_path, dst_path):
engine = sm2.CryptSM2(public_key=pub_hex, private_key=pri_hex)
with open(src_path, 'rb') as f:
payload = f.read()
encrypted = engine.encrypt(payload)
with open(dst_path, 'wb') as f:
f.write(encrypted)
def apply_decryption(pub_hex, pri_hex, src_path, dst_path):
engine = sm2.CryptSM2(public_key=pub_hex, private_key=pri_hex)
with open(src_path, 'rb') as f:
encrypted = f.read()
decrypted = engine.decrypt(encrypted)
with open(dst_path, 'wb') as f:
f.write(decrypted)
def produce_signature(pub_hex, pri_hex, src_path, sig_path):
engine = sm2.CryptSM2(public_key=pub_hex, private_key=pri_hex)
with open(src_path, 'rb') as f:
payload = f.read()
nonce = func.random_hex(engine.para_len)
sig = engine.sign(payload, nonce)
with open(sig_path, 'wb') as f:
f.write(binascii.unhexlify(sig))
def check_signature(pub_hex, pri_hex, src_path, sig_path):
engine = sm2.CryptSM2(public_key=pub_hex, private_key=pri_hex)
with open(src_path, 'rb') as f:
payload = f.read()
with open(sig_path, 'rb') as f:
sig = f.read()
if engine.verify(binascii.hexlify(sig).decode(), payload):
print("Valid signature")
else:
print("Invalid signature")
Document Lifecycle Management
Drafting and Securing Content
When a new document is created, a .docx is generated and saved to disk. The system derives or retrieves a 16-byte SM4 symmetric key via fetch_symmetric_key. That key encrypts the document, and a SM3 hash of the plaintext is stored for later integrity verification. Afterwards, the symmetric key is encrypted for the recipient using SM2 and then signed by the sender.
@csrf_exempt
def draft_document(request):
if request.method == 'POST':
actor = request.session['user_id']
actor_name = request.session['username']
payload = json.loads(request.body)
title = payload['title']
body = payload['body']
classification = payload['classification']
recipient = payload['recipient']
base_name = payload['storage_path']
doc = Docu()
doc.add_heading(title, level=1)
doc.add_paragraph(body)
temp_path = os.path.join(settings.BASE_DIR, 'web', 'static', 'docx', base_name + '.docx')
doc.save(temp_path)
Document.objects.create(
title=title,
owner=actor,
originator=actor,
created=timezone.now(),
classification=classification,
recipient=recipient,
format_type='docx',
last_editor=actor,
last_modified=timezone.now(),
storage_path=base_name + '.docx'
)
session_key = fetch_symmetric_key(base_name)
encrypt_with_integrity(temp_path, session_key, base_name)
os.remove(temp_path)
sender = UserProfile.objects.get(uid=actor)
sender_prikey = sm4_decrypt(sm3_hash_data(sender.pass_hash)[:16], sender.prikey)
receipt_profile = UserProfile.objects.get(handle=recipient)
receipt_prikey = sm4_decrypt(sm3_hash_data(receipt_profile.pass_hash)[:16], receipt_profile.prikey)
key_raw_path = os.path.join(settings.BASE_DIR, 'web', 'static', 'key', base_name + 'key.dat')
key_enc_path = os.path.join(settings.BASE_DIR, 'web', 'static', 'key', base_name + 'encryptkey.dat')
apply_encryption(receipt_profile.pubkey, receipt_prikey, key_raw_path, key_enc_path)
os.remove(key_raw_path)
sig_path = os.path.join(settings.BASE_DIR, 'web', 'static', 'sign', base_name + 'signkey.dat')
produce_signature(sender.pubkey, sender_prikey, key_enc_path, sig_path)
Log.objects.create(
actor=actor_name,
doc_name=title,
detail=f'{actor_name} drafted document {title} at {timezone.now()}.'
)
return JsonResponse({'status': 'draft saved'})
return JsonResponse({'error': 'method not allowed'}, status=405)
Symmetric Key Handling
def fetch_symmetric_key(label):
target = os.path.join(settings.BASE_DIR, 'web', 'static', 'key', label + 'key.dat')
if os.path.exists(target):
with open(target, 'rb') as f:
raw = f.read()
if len(raw) == 16:
return raw
fresh = secrets.token_bytes(16)
with open(target, 'wb') as f:
f.write(fresh)
return fresh
Encryption and Hash Pipelines
def encrypt_with_integrity(src, sym_key, label):
with open(src, 'rb') as f:
data = f.read()
digest = sm3_hash(list(data))
with open(os.path.join(settings.BASE_DIR, 'web', 'static', 'secure', label + 'hash_original.dat'), 'w') as f:
f.write(digest)
engine = CryptSM4()
engine.set_key(sym_key, SM4_ENCRYPT)
ciphertext = engine.crypt_ecb(data)
dest = os.path.join(settings.BASE_DIR, 'web', 'static', 'docx', label + '.enc')
with open(dest, 'wb') as f:
f.write(ciphertext)
def decrypt_with_integrity(encrypted_src, sym_key, label):
engine = CryptSM4()
engine.set_key(sym_key, SM4_DECRYPT)
with open(encrypted_src, 'rb') as f:
ciphertext = f.read()
plaintext = engine.crypt_ecb(ciphertext)
dest = os.path.join(settings.BASE_DIR, 'web', 'static', 'docxs', label + '.docx')
with open(dest, 'wb') as f:
f.write(plaintext)
new_digest = sm3_hash(list(plaintext))
with open(os.path.join(settings.BASE_DIR, 'web', 'static', 'secure', label + 'hash_decrypted.dat'), 'w') as f:
f.write(new_digest)
orig = open(os.path.join(settings.BASE_DIR, 'web', 'static', 'secure', label + 'hash_original.dat'), 'rb').read()
print("Integrity OK" if orig == new_digest else "Integrity FAIL")
return '/static/docxs/' + label + '.docx'
Document Retrieval and Deletion
def fetch_owned_documents(request):
user_id = request.session['user_id']
docs = Document.objects.filter(owner=user_id, dispatched=0)
entries = [{
'ref': d.doc_ref,
'title': d.title,
'classification': d.classification,
'owner': d.owner,
'originator': d.originator,
'created': d.created.strftime('%Y-%m-%d'),
'dispatched': d.dispatched,
'recipient': d.recipient,
'storage_path': d.storage_path
} for d in docs]
return JsonResponse(entries, safe=False)
@csrf_exempt
def remove_document(request, title):
actor = request.session['username']
if request.method == 'DELETE':
record = get_object_or_404(Document, title=title)
for sub_path in ['docx/' + title + '.enc', 'docxs/' + title + '.docx',
'key/' + title + 'key.dat', 'key/' + title + 'encryptkey.dat',
'secure/' + title + 'hash_decrypted.dat', 'secure/' + title + 'hash_original.dat',
'sign/' + title + 'signkey.dat']:
full = os.path.join(settings.BASE_DIR, 'web', 'static', sub_path)
if os.path.exists(full):
os.remove(full)
Log.objects.create(actor=actor, doc_name=record.title,
detail=f'{actor} removed {record.title} at {timezone.now()}.')
record.delete()
return JsonResponse({'status': 'removed'})
return JsonResponse({'error': 'wrong method'}, status=400)
Decryption upon Download
def download_and_decrypt(request):
actor = request.session['username']
if request.method == 'POST':
body = json.loads(request.body)
title = body['file_title']
record = Document.objects.get(title=title)
sender = UserProfile.objects.get(uid=record.originator)
receiver = UserProfile.objects.get(handle=record.recipient)
sig_path = os.path.join(settings.BASE_DIR, 'web', 'static', 'sign', title + 'signkey.dat')
enc_key_path = os.path.join(settings.BASE_DIR, 'web', 'static', 'key', title + 'encryptkey.dat')
check_signature(sender.pubkey, sender.prikey, enc_key_path, sig_path)
raw_key_path = os.path.join(settings.BASE_DIR, 'web', 'static', 'key', title + 'key.dat')
apply_decryption(receiver.pubkey, receiver.prikey, enc_key_path, raw_key_path)
sym_key = fetch_symmetric_key(title)
file_url = decrypt_with_integrity(
os.path.join(settings.BASE_DIR, 'web', 'static', 'docx', title + '.enc'),
sym_key, title
)
Log.objects.create(actor=actor, doc_name=record.title,
detail=f'{actor} downloaded {record.title} at {timezone.now()}.')
return JsonResponse({'message': 'OK', 'decrypted_file_address': file_url})
return JsonResponse({'error': 'method not allowed'}, status=405)
Approval Workflow
Listing Pending Reviews
def fetch_pending_reviews(request):
actor = request.session['username']
items = Document.objects.filter(recipient=actor, dispatched=1)
data = [{
'ref': d.doc_ref,
'title': d.title,
'classification': d.classification,
'owner': d.owner,
'originator': d.originator,
'created': d.created.strftime('%Y-%m-%d'),
'dispatched': d.dispatched,
'recipient': d.recipient,
'storage_path': d.storage_path,
'approved': d.approved
} for d in items]
return JsonResponse(data, safe=False)
Approve or Reject
@csrf_exempt
def accept_document(request):
actor = request.session['username']
if request.method == 'POST':
title = json.loads(request.body).get('documentName')
record = Document.objects.get(title=title)
record.approved = 1
record.dispatched = 1
Log.objects.create(actor=actor, doc_name=title,
detail=f'{actor} approved {title} at {timezone.now()}.')
record.save()
return JsonResponse({'status': 'approved'})
return JsonResponse({'error': 'bad request'}, status=400)
@csrf_exempt
def decline_document(request):
actor = request.session['username']
if request.method == 'POST':
payload = json.loads(request.body)
title = payload.get('documentName')
record = Document.objects.get(title=title)
record.approved = 0
record.dispatched = 0
record.owner = record.originator
Log.objects.create(actor=actor, doc_name=title,
detail=f'{actor} rejected {title} at {timezone.now()}.')
record.save()
return JsonResponse({'status': 'rejected'})
return JsonResponse({'error': 'bad request'}, status=400)
Dispatch and Notification
Sending a Document to the Next Office
@csrf_exempt
def dispatch_document(request):
actor = request.session['username']
if request.method == 'POST':
payload = json.loads(request.body)
title = payload['documentName']
next_hop = payload['ccOffice']
record = Document.objects.get(title=title)
record.dispatched = 1
record.owner = next_hop
Log.objects.create(actor=actor, doc_name=title,
detail=f'{actor} dispatched {title} to {next_hop} at {timezone.now()}.')
record.save()
return JsonResponse({'status': 'sent'})
return JsonResponse({'error': 'bad request'}, status=400)
Activity and Audit Log Retrieval
User Session Logs
def get_user_session_logs(request):
actor = request.session.get('username')
account = UserProfile.objects.get(handle=actor)
if account.permissions == 1:
entries = Log.objects.filter(doc_name="N/A")
else:
entries = Log.objects.filter(actor=actor, doc_name="N/A")
return JsonResponse(list(entries.values()), safe=False)
Document Operation Logs
def get_document_operation_logs(request):
actor = request.session.get('username')
account = UserProfile.objects.get(handle=actor)
if account.permissions == 1:
entries = Log.objects.exclude(doc_name="N/A")
else:
entries = Log.objects.filter(actor=actor).exclude(doc_name="N/A")
return JsonResponse(list(entries.values()), safe=False)
User Administration
Create and Delete Users
def add_user(request):
actor = request.session['username']
if request.method == 'POST':
form = UserForm(request.POST)
if form.is_valid():
uid = form.cleaned_data['uid']
handle = form.cleaned_data['handle']
email_addr = form.cleaned_data['email_addr']
plain_pass = form.cleaned_data['pass_hash']
salt_val = make_salt(15)
digested = digest_credential(plain_pass, salt_val)
secret = PrivateKey()
pub = secret.publicKey()
UserProfile.objects.create(
uid=uid, handle=handle, email_addr=email_addr,
pass_hash=digested, salt_val=salt_val,
pubkey=pub.toString(compressed=False), prikey=secret.toString(),
avatar_img='avatars/default_avatar.png'
)
Log.objects.create(actor=actor, doc_name="N/A",
detail=f'{actor} created user {handle} at {timezone.now()}.')
return HttpResponseRedirect(reverse('index'))
else:
form = UserForm()
return render(request, 'adduser.html', {'form': form})
@csrf_exempt
def erase_user(request, user_id):
actor = request.session['username']
if request.method == 'DELETE':
target = get_object_or_404(UserProfile, uid=user_id)
Log.objects.create(actor=actor, doc_name="N/A",
detail=f'{actor} removed user {target.handle} at {timezone.now()}.')
target.delete()
return JsonResponse({'status': 'deleted'})
return JsonResponse({'error': 'method not allowed'}, status=405)
Modify User Details and Permissions
def alter_profile(request, user_id):
actor = request.session['username']
profile = get_object_or_404(UserProfile, uid=user_id)
if request.method == 'POST':
new_handle = request.POST.get('handle')
new_email = request.POST.get('email_addr')
new_pass = request.POST.get('pass_hash')
if new_pass:
salt_val = make_salt(15)
profile.pass_hash = digest_credential(new_pass, salt_val)
profile.salt_val = salt_val
profile.handle = new_handle
profile.email_addr = new_email
Log.objects.create(actor=actor, doc_name="N/A",
detail=f'{actor} updated profile of {new_handle} at {timezone.now()}.')
profile.save()
messages.success(request, 'Profile updated.')
return redirect('index')
return render(request, 'change_userinfo.html', {'user_profile': profile})
def adjust_permissions(request, user_id):
actor = request.session['username']
profile = UserProfile.objects.get(uid=user_id)
if request.method == 'POST':
level = request.POST['permissions']
profile.permissions = level
Log.objects.create(actor=actor, doc_name="N/A",
detail=f'{actor} changed permissions of {profile.handle} to {level} at {timezone.now()}.')
profile.save()
return redirect('index')
return render(request, 'manage_permission.html', {'user': profile})
Session Termination
def end_session(request):
actor = request.session.get('username')
if 'user_id' in request.session:
Log.objects.create(actor=actor, doc_name="N/A",
detail=f'{actor} logged out at {timezone.now()}.')
del request.session['user_id']
del request.session['username']
return redirect('index')
Frontend Interface Highlights
Dashboard Layout
The main dashboard uses a top navigation bar containing a search input and user greeting. A sidebar presents navigation links to sections such as Document Management, Review, Drafting, User Management, and Logs. The user's avatar is displayed with a link to change it. The access level is embedded as a JavaScript variable to conditionally show administrative features.
Registration and Login Forms
Both forms perform client-side validation before submission. CSRF tokens are included via Django's {% csrf_token %}. Server-side messages are randered as list items to inform the user of errors or successes.
Management Pages
- Add User: Renders a
UserForm; on successful creation waits three seconds before redirecting. - Change User Info: Disabled input for the immutable student ID; editable fields for handle, email, and password.
- Manage Permission: A dropdown with options 0–3, each mapped to a specific role, followed by a delayed submit.
- Upload Avatar: Uses
multipart/form-dataand accepts image files, posting to/upload_avatar/.