PyCrypto:decrypt()方法返回的函数

时间:2017-11-08 07:20:48

标签: python pycrypto pkcs#1

我想在我的python网站中使用RSA,我使用了pycrypto。但我有一些问题。 这是我的代码:

fun style(): XYZValues {
    if (true) {
        return XYZValues.BIG_TEXT
    }
    return XYZValues.DEFAULT
}

enum class XYZValues(desc: String) {
    DEFAULT("DEFAULT"),
    BIG_TEXT("BIG_TEXT")
    //more }

}

fun main(args: Array<String>) {
    when (style()) {
        XYZValues.BIG_TEXT -> println("1")
        XYZValues.DEFAULT -> println("2")
    }
}

但是当我运行一个应用程序时,我会发生错误,例如:

from Crypto import Random
from Crypto.Cipher import PKCS1_v1_5
from Crypto.PublicKey import RSA
import base64

random_generator = Random.new().read


def decrypt_rsa(secret):
    with open('/home/ubuntu/project/all/all_test/all_python/util/private_rsa.pem') as file:
        private_key = RSA.importKey(file.read())
        cipher = PKCS1_v1_5.new(private_key)
        text = cipher.decrypt(base64.b64decode(secret), random_generator)
        print(str(text))
        return text.decode('utf-8')

我的服务器操作系统是ubuntu 16.04,带有python3。*,Traceback (most recent call last): File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line1982, in wsgi_app response = self.full_dispatch_request() File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line1614, in full_dispatch_request rv = self.handle_user_exception(e) File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line1517, in handle_user_exception reraise(exc_type, exc_value, tb) File "/home/ubuntu/project/all/venv/lib/python3.5/sitepackages/flask/app.py", line1612, in full_dispatch_request rv = self.dispatch_request() File "/home/ubuntu/project/all/venv/lib/python3.5/site-packages/flask/app.py", line 1598, in dispatch_request return self.view_functions[rule.endpoint](**req.view_args) File "/home/ubuntu/project/all/all_test/all_python/v3/v3_main.py", line 192, in v3_set_article_love if check_secret(secret): File "/home/ubuntu/project/all/all_test/all_python/v3/v3_main.py", line 18, in check_secret t = int(secret_util.decrypt_rsa(secret)) File "/home/ubuntu/project/all/all_test/all_python/util/secret_util.py", line14, in decrypt_rsa return text.decode('utf-8') AttributeError: 'function' object has no attribute 'decode' 由base64编码,就像secret一样 非常感谢你的帮助。

1 个答案:

答案 0 :(得分:0)

简答(TL; DR):

decrypt()方法正在返回random_generator函数。

详细信息

如果您输入

help(PKCS1_v1_5.PKCS115_Cipher.decrypt)

你可以从官方文档中读到这个:

decrypt(self, ct, sentinel) method of 
Crypto.Cipher.PKCS1_v1_5.PKCS115_Cipher instance
Decrypt a PKCS#1 v1.5 ciphertext.

[...]    

:Parameters:
[...]
 sentinel : any type
        The object to return to indicate that an error was detected  
        during decryption.

正如您可以从上面看到的,如果在解密期间出现错误,则返回sentinel对象而不是字节字符串,然后在您的代码中,decrypt()方法将返回{{1功能。

这就是为什么你的random_generator变量是一个函数,你不能把它当作字节串。

进一步说明

我认为没有必要将随机生成器作为标记对象传递给text,因为它只是用于检测错误的标记对象。请参阅PyCrypto documentation以了解有关此库的更多信息(但也请阅读thisthis,并考虑改为使用PyCryptodome