使用对称密钥进行文件加密

时间:2014-10-07 10:37:29

标签: python encryption sha256 encryption-symmetric

我正在尝试使用对称密钥加密文件。由于我无法做到这一点,我正在使用文件(.txt)内容进行一些测试,并使用对称密钥加密相同的内容,一切正常:

filename1 = raw_input("Insert file name: ")
with open(filename1,'rb') as f:
    s = f.read()

data1 = s


# insert password to create key

password1 = raw_input('Enter password (symmetric key): ')

# generate 16bytes (AES-128) key from inserted password
h1 = SHA256.new()
h1.update(password1)
key1 = h1.digest()[0:16]

# generate initialization 16bytes vector
iv1 = Random.new().read(16)

# criptogram creation (cipher data)
cipher1 = AES.new(key1, AES.MODE_CFB, iv1)
criptogram1 = iv1 + cipher1.encrypt(data1) 

但是,我需要的是使用对称密钥加密来加密密码文件,而不仅仅是像我现在这样做的内容。我需要能够选择文件,然后在其中使用对称密钥。

编辑:对于"密码文件,而不仅仅是内容"?我的意思是我可以对.txt文件中的某些内容进行加密,其中包含一些内容,但是我希望能够直接加密#39;该文件,我不想打开它并阅读里面的内容然后加密... 我发布的示例,我输入的文件名(例如xpto.txt)里面写着一些内容(例如Hello world!),因此在示例中我只是加密该内容。

我希望得到一个加密的文件,必须阅读其中的内容。因为如果我尝试加密图片,我不会像在.txt文件中那样在里面读取,我想获取整个文件并加密它。

2 个答案:

答案 0 :(得分:0)

如果我做对了 - 您可以加密当前文件中的内容,但是您不知道如何,让我们说,从#34; myfile1.py"它会加密来自" myfile2.txt"?

的行

只需使用以下命令读取第二个文件中第一个文件中的行:

with open('myfile2.txt') as myfile:
    mytext = myfile.readlines()

然后对mytext进行加密。

答案 1 :(得分:0)

经过一番研究后,我设法找到了解决方案:

#read binary file to get bytes 
    while True:
        buf = fo.read(1024) #read 1024bytes from the file on each iteration of the loop 
        if len(buf) == 0:
             break

    fo.close()


    # insert password to create key

    password1 = raw_input('Enter password (symmetric key): ')

    # generate 16bytes (AES-128) key from inserted password
    h1 = SHA256.new()
    h1.update(password1)
    key1 = h1.digest()[0:16]

    # generate initialization 16bytes vector
    iv1 = Random.new().read(16)

    # criptogram creation (cipher data)
    cipher1 = AES.new(key1, AES.MODE_CFB, iv1)
    criptogram1 = iv1 + cipher1.encrypt(buf)
相关问题