我正在使用PyCrypto实现使用RSA进行文件加密。在Python中使用RSA加密文件
我知道这有点不对,首先因为RSA非常慢,第二,因为PyCrypto RSA只能加密128个字符,所以你必须以128个字符的块来分解文件。
这是到目前为止的代码:
from Crypto.PublicKey import RSA
file_to_encrypt = open('my_file.ext', 'rb').read()
pub_key = open('my_pub_key.pem', 'rb').read()
o = RSA.importKey(pub_key)
to_join = []
step = 0
while 1:
# Read 128 characters at a time.
s = file_to_encrypt[step*128:(step+1)*128]
if not s: break
# Encrypt with RSA and append the result to list.
# RSA encryption returns a tuple containing 1 string, so i fetch the string.
to_join.append(o.encrypt(s, 0)[0])
step += 1
# Join the results.
# I hope the \r\r\r sequence won't appear in the encrypted result,
# when i explode the string back for decryption.
encrypted = '\r\r\r'.join(to_join)
# Write the encrypted file.
open('encrypted_file.ext', 'wb').write(encrypted)
所以我的问题是:是否有使用私有/公共密钥加密的文件任何更好的方法?
我听说过Mcrypt和OpenSSL,但我不知道他们是否可以加密文件。
您应该使用像AES这样的对称密码来加密文件,然后使用RSA来加密AES密钥。 – 2011-06-10 17:28:05
@Petey B:我希望我能喜欢那个评论100次。 – vcsjones 2011-06-10 17:28:58
@Petey:谢谢,我知道这件事,但我想要实现像gpg4win这样的东西。 – 2011-06-10 17:31:32