这是我用于生成RSA密钥的代码:
def encrypt():
prepath = os.getenv('APPDATA')
path = (prepath + '\\PythonApps')
if not os.path.exists(path):
print('Error: Must Have Valid RSA Keys')
elif not os.path.isfile(path + '\\privatekey.bin'):
print('Error: No Private RSA Key Generated')
elif not os.path.isfile(path + '\\publickey.bin'):
print('Error: No Public RSA Key Generated')
else:
with open('C:\\Python\\encrypted_data.txt', 'wb') as out_file:
file = filedialog.askopenfilename(initialdir = "C:\\",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
print(file)
openfile = open(file, 'rb')
read = openfile.read()
print(read)
recipient_key = RSA.import_key(open(path + '\\publickey.bin').read())
session_key = get_random_bytes(16)
cipher_rsa = PKCS1_OAEP.new(recipient_key)
enc_session_key = cipher_rsa.encrypt(session_key)
out_file.write(cipher_rsa.encrypt(session_key))
cipher_aes = AES.new(session_key, AES.MODE_EAX)
ciphertext, tag = cipher_aes.encrypt_and_digest(read)
out_file.write(enc_session_key)
out_file.write(cipher_aes.nonce)
out_file.write(tag)
out_file.write(ciphertext)
out_file.close()
openfile.close()
shutil.move('C:\\Python\\encrypted_data.txt', path + '\\encrypted_data.txt')
print('Encryption Complete')
return()
此功能用于加密文件:
def decrypt():
path = (os.getenv('APPDATA') + '\\PythonApps\\privatekey.bin')
print(path)
file = filedialog.askopenfilename(initialdir = "C:\\",title = "Select file",filetypes = (("text files","*.txt"),("all files","*.*")))
with open(file, 'rb') as fobj:
print('test')
private_key = RSA.import_key(open(path).read())
print('test2')
enc_session_key, nonce, tag, ciphertext = [fobj.read(x)
for x in
(private_key.size_in_bytes(),
16,16,-1)]
cipher_rsa = PKCS1_OAEP.new(private_key)
session_key = cipher_rsa.decrypt(enc_session_key)
cipher_aes = AES.new(session_key, AES.MODE_EAX, nonce)
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
print('test3')
print(data)
fobj.close()
return()
此功能是解密数据:
Traceback (most recent call last):
File
C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib
\tkinter\__init__.py line 1702, in __call__
return self.func(*args)
File "C:\Python\tkinterlogin.py", line 294, in decrypt
data = cipher_aes.decrypt_and_verify(ciphertext, tag)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-
packages\Cryptodome\Cipher\_mode_eax.py", line 341, in decrypt_and_verify
self.verify(received_mac_tag)
File "C:\Users\bsmith\AppData\Local\Programs\Python\Python36\lib\site-
packages\Cryptodome\Cipher\_mode_eax.py", line 293, in verify
raise ValueError("MAC check failed")
ValueError: MAC check failed
回溯在这里:
var promise = document.querySelector('video').play();
if (promise !== undefined) {
promise.then(_ => {
// Autoplay started!
}).catch(error => {
// Autoplay was prevented.
// Show a "Play" button so that user can start playback.
});
}
一切正常,直到运行解密功能为止,此时我按下了MAC Check Failed。以前,当我在加密中使用密码短语时,会收到不受支持的RSA密钥格式,因此我进行了切换,但是现在我无法弄清为什么它会收到当前错误。有任何想法吗?