如何修复 Python 的 Crypto.Signature.DSS 导入错误

How to fix Python import error for Crypto.Signature.DSS

我正在尝试 运行 pycryptodome example DSA。这是示例代码:

from Crypto.PublicKey import DSA
from Crypto.Signature import DSS
from Crypto.Hash import SHA256

# Create a new DSA key
key = DSA.generate(2048)
f = open("public_key.pem", "w")
f.write(key.publickey().export_key())
f.close()

# Sign a message
message = b"Hello"
hash_obj = SHA256.new(message)
signer = DSS.new(key, 'fips-186-3')
signature = signer.sign(hash_obj)

但我面临 ImportError DSS。这是错误输出:

Traceback (most recent call last):
  File "/usr/lib/python3.6/code.py", line 91, in runcode
    exec(code, self.locals)
  File "<input>", line 1, in <module>
  File "/snap/pycharm-professional/154/helpers/pydev/_pydev_bundle/pydev_umd.py", line 197, in runfile
    pydev_imports.execfile(filename, global_vars, local_vars)  # execute the script
  File "/snap/pycharm-professional/154/helpers/pydev/_pydev_imps/_pydev_execfile.py", line 18, in execfile
    exec(compile(contents+"\n", file, 'exec'), glob, loc)
  File "/home/username/Projects/DSA_Example.py", line 2, in <module>
    from Crypto.Signature import DSS
ImportError: cannot import name 'DSS'

我的开发环境包括:

    (venv) username@myubuntu:~/Projects/MyProject/$ pip list
    DEPRECATION: The default format will switch to columns in the future. You can use --format=(legacy|columns) (or define a format=(legacy|columns) in your pip.conf under the [list] section) to disable this warning.
    asn1crypto (0.24.0)
    cryptography (2.1.4)
    decorator (4.1.2)
    enum34 (1.1.6)
    idna (2.6)
    ipaddress (1.0.17)
    keyring (10.6.0)
    keyrings.alt (3.0)
    networkx (1.11)
    numpy (1.13.3)
    pip (9.0.1)
    pycrypto (2.6.1)
    pycryptodome (3.9.0)
    pygobject (3.26.1)
    pyxdg (0.25)
    PyYAML (3.12)
    rubber (1.4)
    SecretStorage (2.3.1)
    setuptools (39.0.1)
    six (1.11.0)
    wheel (0.30.0)

现在如何修复 DSS 的导入错误?

看起来您还安装了 pycrypto (2.6.1),它还有一个名为 Crypto.Signature 的模块。发生的事情是 Python 试图导入 pycrypto.Crypto.Signature(它没有 DSS 模块)而不是 pycryptodome.Crypto.Signature。要解决此问题,您可以尝试 运行 pip uninstall pycrypto 看看是否能解决您的问题。

pycryptodome 的安装页面上注明 "One must avoid having both PyCrypto and PyCryptodome installed at the same time, as they will interfere with each other"。