|
|
|
@ -0,0 +1,61 @@
|
|
|
|
|
import base64
|
|
|
|
|
import hashlib
|
|
|
|
|
|
|
|
|
|
import rsa
|
|
|
|
|
from Crypto.Cipher import AES, DES3
|
|
|
|
|
from Crypto.Hash import SHA256
|
|
|
|
|
from Crypto.PublicKey import RSA
|
|
|
|
|
from Crypto.Signature import PKCS1_v1_5
|
|
|
|
|
from pyDes import ECB, PAD_PKCS5, des
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
def createcip(path, op):
|
|
|
|
|
# 传输的文件
|
|
|
|
|
filename = path
|
|
|
|
|
# 加密对称密钥
|
|
|
|
|
with open("../server/Bpubkey.pem", mode="rb") as f:
|
|
|
|
|
pub = f.read()
|
|
|
|
|
pubkey = rsa.PublicKey.load_pkcs1(pub)
|
|
|
|
|
message = "12345678" if op == "DES" else "1234567812345678"
|
|
|
|
|
info = rsa.encrypt(message.encode("utf-8"), pubkey)
|
|
|
|
|
with open("encryptedkeyfile.bin", "wb") as key_file: # 生成加密文本encryptedkeyfile
|
|
|
|
|
key_file.write(info)
|
|
|
|
|
|
|
|
|
|
# 加密文件 DES算法加密
|
|
|
|
|
with open(filename, "r", encoding="utf-8") as f:
|
|
|
|
|
plaintext = f.read()
|
|
|
|
|
|
|
|
|
|
x = plaintext
|
|
|
|
|
while len(x) % 16 != 0: # 如果text不足16位的倍数就用空格补足为16位
|
|
|
|
|
x += "\0"
|
|
|
|
|
x = x
|
|
|
|
|
if op == "DES":
|
|
|
|
|
SECRET_KEY = message
|
|
|
|
|
print(len(message))
|
|
|
|
|
iv = SECRET_KEY
|
|
|
|
|
des_obj = des(SECRET_KEY, ECB, iv, padmode=PAD_PKCS5)
|
|
|
|
|
secret = des_obj.encrypt(x)
|
|
|
|
|
elif op == "AES_ECB":
|
|
|
|
|
SECRET_KEY = message.encode()
|
|
|
|
|
aes_obj = AES.new(SECRET_KEY, AES.MODE_ECB)
|
|
|
|
|
secret = aes_obj.encrypt(x.encode())
|
|
|
|
|
elif op == "AES_CBC":
|
|
|
|
|
iv = message.encode()
|
|
|
|
|
SECRET_KEY = message.encode()
|
|
|
|
|
aes = AES.new(SECRET_KEY, AES.MODE_CBC)
|
|
|
|
|
secret = aes.encrypt(x.encode())
|
|
|
|
|
with open("encryptedfile.txt", "wb") as cip: # encryptedfile
|
|
|
|
|
cip.write(secret)
|
|
|
|
|
# 计算摘要值以及签名
|
|
|
|
|
out1 = hashlib.sha256(plaintext.encode('"utf-8"')).hexdigest()
|
|
|
|
|
out1 = out1.encode("utf-8")
|
|
|
|
|
privkey_key_file = open("./Aprivkey.pem", "rb").read().decode("utf-8")
|
|
|
|
|
# 导入公钥,返回一个RSA秘钥对象
|
|
|
|
|
private_key = RSA.importKey(privkey_key_file)
|
|
|
|
|
h = SHA256.new(out1)
|
|
|
|
|
signer = PKCS1_v1_5.new(private_key)
|
|
|
|
|
signature = signer.sign(h)
|
|
|
|
|
# 对需要加密的消息进行PKCS#1 v1.5加密,再使用Base64对类似字节的对象进行编码。
|
|
|
|
|
sig = base64.b64encode(signature)
|
|
|
|
|
with open("sigfile.bin", "wb") as f: # 生成签名文件sigfile
|
|
|
|
|
f.write(sig)
|