希望使用/etc/shadow中的哈希密码来加密文件。尝试使用Python2.7。现有代码正在使用Crypto.Cipher/散列但要求用户输入密码。从我能读到的关于spwd的内容来看,我可以验证输入的密码是否与哈希值正确匹配,但是我想使用哈希值,根本不要求用户输入密码。你知道吗
from Crypto.Hash import SHA256
from Crypto.Cipher import AES
import os, random, sys
from os import path
def encrypt(key, filename, outFile):
chunksize = 64 * 1024
filesize = str(os.path.getsize(filename)).zfill(16)
IV = ''
for i in range(16):
IV += chr(random.randint(0, 0xFF))
encryptor = AES.new(key, AES.MODE_CBC, IV)
with open(filename, "rb") as infile:
with open(outFile, "wb") as outfile:
outfile.write(filesize)
outfile.write(IV)
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
elif len(chunk) % 16 !=0:
chunk += ' ' * (16 - (len(chunk) % 16))
outfile.write(encryptor.encrypt(chunk))
def decrypt(key, filename, outFile):
chunksize = 64 * 1024
with open(filename, "rb") as infile:
filesize = infile.read(16)
IV = infile.read(16)
decryptor = AES.new(key, AES.MODE_CBC, IV)
with open(outFile, "wb") as outfile:
while True:
chunk = infile.read(chunksize)
if len(chunk) == 0:
break
outfile.write(decryptor.decrypt(chunk))
outfile.truncate(int(filesize))
BASE_PATH = path.dirname(path.abspath(__file__))
choice = raw_input("Do you want to (E)ncrypt or (D)ecrypt? ")
encFiles = os.path.join(BASE_PATH, 'your_file_name')
typed_out_file = raw_input('Enter out file_name: ')
outFile = os.path.join(BASE_PATH, typed_out_file)
password = raw_input("Enter the password: ")
if choice == "E":
if os.path.basename(encFiles).startswith("(encrypted)"):
print "%s is already encrypted" %str(Tfiles)
pass
elif encFiles == os.path.join(os.getcwd(), sys.argv[0]):
pass
else:
encrypt(SHA256.new(password).digest(), str(encFiles), outFile)
print "Done encrypting %s" %str(encFiles)
os.remove(encFiles)
elif choice == "D":
filename = raw_input("Enter the filename to decrypt: ")
out_file = raw_input("Enter the new filename: ")
decrypt(SHA256.new(password).digest(), filename, out_file)
print "Done decrypting %s" %filename
os.remove(filename)
else:
print "Please choose a valid command."
sys.exit()
目前没有回答
相关问题 更多 >
编程相关推荐