' exportKey' pycrypto-2.6.1(python 2.7.6)ubuntu14.04 LTS中无法识别的函数

时间:2015-02-11 05:21:15

标签: python ubuntu-14.04 pycrypto

您好我试图运行这个简单的代码来生成私钥:

from Crypto.PublicKey import RSA
key = RSA.generate(2048)
f = open('mykey.pem','w')
f.write(RSA.exportKey('PEM'))
f.close()

但是我收到了这个错误:

Traceback (most recent call last):
  File "erase-this.py", line 5, in <module>
    f.write(RSA.exportKey('PEM'))
AttributeError: 'module' object has no attribute 'exportKey'

我检查了/pycrypto-2.6.1/lib/Crypto/PublicKey和函数

def exportKey(self, format='PEM', passphrase=None, pkcs=1):

出现在RSA.py内。

有人知道我为什么会收到错误:

AttributeError: 'module' object has no attribute 'exportKey'???

1 个答案:

答案 0 :(得分:3)

exportKey()是键的方法,而不是模块函数。所以你需要做

f.write(key.exportKey('PEM'))

这是一个简短的演示(使用较小的密钥大小)。

#!/usr/bin/env python

from Crypto.PublicKey import RSA
key = RSA.generate(1024)
print key.exportKey('PEM')

pub_key = key.publickey()
print pub_key.exportKey('PEM')

典型输出

-----BEGIN RSA PRIVATE KEY-----
MIICWwIBAAKBgQDqYiWx1bwP0aF0TJhRBXzFv+WBPUKD965CbvoU/xiMj7Eu5crD
36k6t44Po696gxVN+rGWUo2VKFVUsi1A3oqhkyFnF6JJxkt42w4sUVNd91PvBzxI
ermBnciyhPjJY8pfWWSaGwZxdqSfBDieeCfAk7NKW8aRzfP178Mz4mCwYQIDAQAB
AoGAMzhzqGNfD83uDK5YcwxR8h03mIC8sn5EFLyP5lrBEKauP+Nz5k5Qe0Z1wzEw
PgO7eikY+hLcYgZIb5Pok86OWMnkeGMY7px+Ti67Y2q9w8euJ1hQV3pmAZNB9XaQ
nuQrG3UNParBh/SaqnHGhtVoAKLX6HXV/sG6URJtQUBbaYECQQDtzl+DC0qi93ew
lsEXRIjGMJjOJ7UphKHllHUN2gfxnTyEGN3QSd6Za/AURejQ8aGK9IByo3GONYSY
/iy+j0Z5AkEA/FC8lhp8xVz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