我现在知道RSA公钥/私钥一次只能加密非常短的输入,但是有没有人能提供一种方法,只使用公钥/私钥加密任何类型的文件(.txt、.phf、.exe等)?我不想有额外的AES密钥。
这是我的代码,在用一对公钥和私钥进行加密和解密后,我无法将原始内容取回。我不关心我的加密或解密有多安全,我只希望简单的加密-解密可以处理任何可能需要的输入,不管它有多长或多大。
from Crypto.PublicKey import RSA
from Crypto import Random
random_generator = Random.new().read
key = RSA.generate(1024, random_generator)
public_key = key.publickey()
f = open('C:\Users\Administrator\Desktop\jack.txt','r').read()
print 'original content: '+ f
enc_data = public_key.encrypt(f, 32)
print 'encrypted data: '
print enc_data
dec_data = key.decrypt(enc_data)
print 'decrypted data: '+ dec_data
输出如下:
original content: Python Cryptography Toolkit
A collection of cryptographic modules implementing various algorithms and protocols.
Subpackages:
Crypto.Cipher
Secret-key (AES, DES, ARC4) and public-key encryption (RSA PKCS#1) algorithms
Crypto.Hash
Hashing algorithms (MD5, SHA, HMAC)
Crypto.Protocol
Cryptographic protocols (Chaffing, all-or-nothing transform, key derivation functions). This package does not contain any network protocols.
Crypto.PublicKey
Public-key encryption and signature algorithms (RSA, DSA)
Crypto.Signature
Public-key signature algorithms (RSA PKCS#1)
Crypto.Util
Various useful modules and functions (long-to-string conversion, random number generation, number theoretic functions)
encrypted data:
('\x08\xe3\x9d\x03\x1e\xe9(\xe2\xc7\xc6e\x0b5\x02\xc0\xd8G\x1f\xf5\xb8\x9cMC\x93Z\x982\xa5\x97\xec\xab4\x18\xc2\xc8\xd9\xd3\x99aX\xd96b\x19\x96\xdc\x1d|F\xe0\xa9\xa9\xea\x03\x10>0g\x83\xdb\xeb\xdb\x13\x91\xc6\xd8\xf6\x95\xedE@A\x0bc\xae\xbe\xbe\xf0\xde\xcc\xcexk\x10\xb3\x86\xd3\xdd\xd0\xca@T2\x9a\x8a6ut\xb1\xaf\x07\x1f\xa2M\r\xf0D\xa2`h\xc3\x89\x18\x0e\xd4\xca\xee\xf5\xfc\x01\xed\x95}X\x1f\x13 1',)
decrypted data: ���J�rPX �����ju�a,�xm�'�]��ٟ�?y;�)��tĹ�,�D4^�ba�8����9q
+�i��l �q]Kd�Y���u��S�B���Ϲ�^�A3
.7��j��m�
�6�dl� qU
RSA只能对有限的输入进行加密。这在多大程度上取决于RSA的密钥大小(在您的情况下是1024位)和使用的填充。大于该值的所有内容(不使用填充时为128字节,使用填充时为较少),并且您无法再恢复它。
解决方案是使用混合加密。
AES加密:
RSA加密(使用适当的填充,如OAEP,因为RSA教科书已经严重损坏):
只发送
msg
和ciphertext
。解密是类似的,但是是向后的,因为首先必须从RSA密文中恢复AES密钥。用AES解密时别忘了切掉IV。RSA非常慢,所以它不适合加密/解密大数据块。它通常用于加密/解密更快的对称密码(如AES)的密钥。
乍一看,你的加密数据看起来有点小,与你的输入数据相对应,但我不太熟悉加密(我几天前才自己安装),所以我无法解释它对你的数据做了什么。
但这个密码对我有效:
典型输出
FWIW,这是上面的一个稍微修改的版本,它同时运行在Python 2和Python 3上,尽管这两个版本的输出会有微小的差异。
在Python 3中,我们不能将字符串传递给加密或解密函数,必须传递字节。另外,Python 3不支持backticks语法来获取Python 2中对象的
repr
。这段代码调用string
.encode()
和bytes.decode()
方法来执行转换。我们可以指定一个编码编解码器,例如但这不是必需的,因为UTF-8是默认的编解码器。
典型的Python 3输出
我们不需要在这里使用UTF-8编码。由于
src_data
是一个纯7位ASCII字符串,并且我们将其作为文本嵌入到脚本中,因此我们可以将其作为文本字节字符串提供:相关问题 更多 >
编程相关推荐