【发布时间】:2011-09-12 16:33:14
【问题描述】:
我正在使用 PyCrypto 使用 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 密钥。
-
@Petey B:我希望我能喜欢该评论 100 次。
-
Gpg4win 做了@Petey B 说你应该做的事情。
-
1.可以加密的数量是 RSA 模数大小的函数。 2.您要加密的块必须小于整数模数,因此如果一次加密 128 字节的块,则不能保证 1024 位模数的正确操作。 3. 你问是否有更好的方法,但你拒绝了这些建议。那么,你对“更好”的定义是什么?
-
@GregS:非常感谢您的建议!我知道我有点固执,但我听专家的意见。
标签: python encryption public-key-encryption