Skip to content

Instantly share code, notes, and snippets.

@lightless233
Last active December 29, 2019 13:58
Show Gist options
  • Select an option

  • Save lightless233/33089f38cd6c0040f9cbcf56414295fd to your computer and use it in GitHub Desktop.

Select an option

Save lightless233/33089f38cd6c0040f9cbcf56414295fd to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3.8
# -*- coding: UTF-8 -*-
import binascii
from flask import Flask
from flask import request
from Crypto.Cipher import DES
webapp = Flask(__name__)
KEY = "qwerasdf"
IV = "AAAABBBB"
BLOCK_SIZE = DES.block_size
U8 = "utf-8"
U8 = "ASCII"
def PAD(s): return s + (BLOCK_SIZE - len(s) %
BLOCK_SIZE) * chr(BLOCK_SIZE - len(s) % BLOCK_SIZE)
def UNPAD(s): return s[0:-ord(s[-1])]
def UNPAD_BYTES(s): return s[0:-s[-1]]
TO_BYTES = lambda s: s.encode(U8)
TO_STR = lambda s: s.decode(U8)
STR2HEX = lambda s: binascii.hexlify(TO_BYTES(s))
def check_pad(plain: bytes):
if len(plain) > 8:
plain = plain[-8:]
p = plain[-1]
if (p > 8) or p == 0:
return False
for i in range(1, p+1):
if plain[8 - i] != p:
return False
return True
@webapp.route("/")
def hello_world():
return "Hello World!"
@webapp.route("/encrypt")
def encrypt():
cipher_handler = DES.new(key=KEY, mode=DES.MODE_CBC, IV=IV)
plain_text: str = request.args.get("plain_text")
print("Plain text:", plain_text)
padded_plain_text: str = PAD(plain_text)
print("After pad:", padded_plain_text, " => ", STR2HEX(padded_plain_text))
cipher: bytes = cipher_handler.encrypt(padded_plain_text)
hex_cipher = binascii.hexlify(cipher)
print("Hex cipher:", hex_cipher)
return binascii.hexlify(TO_BYTES(IV)) + hex_cipher
@webapp.route("/decrypt")
def decrypt():
cipher_text: str = request.args.get("cipher_text")
print("IV + cipher:", cipher_text)
cipher: bytes = binascii.unhexlify(cipher_text)
iv = cipher[:8]
cipher = cipher[8:]
print("iv:", binascii.hexlify(iv), " ,cipher:", binascii.hexlify(cipher))
handler = DES.new(key=KEY, mode=DES.MODE_CBC, IV=iv)
plain = handler.decrypt(cipher)
print("plain with pad:", binascii.hexlify(plain))
if not check_pad(plain):
return "Error pad!"
plain_text = UNPAD_BYTES(plain)
print("plain after unpad:", binascii.hexlify(plain_text))
# 第一次使用的
# if plain_text != b"nnnn":
# return "Error key!"
# 第二次使用的
if plain_text != b"lightless_233":
return "Error key!"
else:
return b"Corrent key! " + plain_text
return plain_text
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment