python - PyCrypto:使用 RSA 非对称 key 对中文字符进行编码

标签 python encryption unicode rsa pycrypto

我正在尝试使用 PyCrypto 加密/解密一些字符串,但在处理中文字符时遇到问题。

当我尝试加密“ni-hao”(hello)时...

pemFile = open("/home/borrajax/keys/myKey.pem", "r")
encryptor = RSA.importKey(pemFile, passphrase="f00")
return encryptor.encrypt("你好", 0)[0]

...我不断收到错误:

Module Crypto.PublicKey.pubkey:64 in encrypt         
>>  ciphertext=self._encrypt(plaintext, K)
Module Crypto.PublicKey.RSA:92 in _encrypt         
>>  return (self.key._encrypt(c),)
ValueError: Plaintext too large

我尝试了很多组合,

encryptor.encrypt(u"你好"...
encryptor.encrypt(u"你好".encode("utf-8")...

没有任何运气。

我想我总是可以在编码之前尝试使用base64,但我想将其保留为“最后的资源”......我希望有一种更“优雅”的方式来做到这一点。

有人遇到过同样的问题吗?任何提示将不胜感激。预先感谢您。

最佳答案

首先,您应该仅加密二进制数据,而不是 Unicode 文本。这意味着 str 类型(在 Python 2.x 中)或 bytes (在 Python 3.x 和最新的 Python 2.x 中)。您必须在加密文本之前对其进行编码,并且必须在解密之后对其进行解码。

其次,您要加密的字节字符串必须小于 RSA 模数(例如 RSA2048 小于 256 字节)。如果您的数据较长,请考虑使用中间 AES session key 。

第三,如果您使用 PyCrypto 2.5,则没有充分的理由使用 RSA key 对象的 .encrypt/.decrypt 方法。使用 PKCS#1 方法之一更好、更安全:OAEPv1.5 。有了它们,明文一定会更短。

关于python - PyCrypto:使用 RSA 非对称 key 对中文字符进行编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10098170/

相关文章:

python - 如何获取 @property getter/setter 的类型?

python - 我需要帮助将 Python 3.4.3 中的整数更改为单词

ios - 没有der文件的RSA加密

regex - 检查 Python 3 字符串中的非法代理

r - 在 R 中用变音符号制表字符

html - 使用 attr(data-icon) 属性在元素之前显示 unicode

python - 为什么对 rand() 生成的列进行操作的 PySpark UDF 会失败?

python - Django 迁移 : django. db.utils.OperationalError : (1824, "Failed to open the referenced table ' classroom_user'")

python - 自定义字段的 to_python 不工作? - Django

c# - 具有 AES 和 rsaEncryption(PKCS#1 v1.5 填充而不是 v2(OAEP)填充)的 EnvelopedCMS 可能吗?