在Python中使用RSA

时间:2010-08-17 16:58:39

标签: python rsa pycrypto

我正在使用RSA在Python中加密/解密我的会话密钥。我正在使用Pycrypto库。生成密钥对后,我想从生成的密钥中提取私钥和公钥,并将它们存储在不同的文件中。我怎样才能做到这一点?我可以看到有一个Private方法,可以告诉生成的密钥对有私有组件,但无法找到如何从这个生成的密钥对中提取密钥。任何建议都会有很大的帮助。

1 个答案:

答案 0 :(得分:41)

如果您想从键中获取相应的部分,则会有key属性:

>>> from Crypto.PublicKey import RSA
>>> RSAkey = RSA.generate(1024)
>>> getattr(RSAkey.key, 'n')
13773...L
>>> getattr(RSAkey.key, 'p')
11731...L
>>> getattr(RSAkey.key, 'q')
11740...L

可用组件为'n','e','d','p','q','u'

如果您只想将其保存在PEM中,则应使用exportKey()方法(自2.2起可用)

>>> private = RSA.generate(1024)
>>> public  = private.publickey()
>>> private.exportKey()
'-----BEGIN RSA PRIVATE KEY-----\nMIICXgIBAAKBgQDo1M0P3nryaF8ZITv8vCFVnjUJ1mnIsrqXZRTzjin69xepr3cz\nKicG3EYSUqMODQAsvMj0tGMo+ElGOVOkPFLVVBHd8izgA/E1RqUzbUDMj4WnhlhA\nQq7tNaViOXNaZ7krJZHabZKxfYvLAQtm4tr+m5NtXPBaWvjwhd5M9xvktwIDAQAB\nAoGBANVsS1Rikbymo5V7e2teYAgFb4THAEyyWIvyYlQnWp/r48rtRoyl9QQ64hhl\nm4WDsUdQ/bwhpkul3DT804jWqu2V71p68rQP7h5D6ldCBUr5nQc9o/uEyy4YCgxD\n/ZxNiY5Bb/lMP9nhb2NbG4184mhUMHu+06wWX6RrXQtMtjYhAkEA8DioToMZIy3s\nhPohri3CAgByV2Jxf7JPqVZ93JjlSlBz+aybSv1mOJUPRFpkMk2xiPmHtEn16hYr\nesVK11tcjwJBAPgf4QYAw9dV+DuVqdwz+kmTjnlkr0Q7fjaGfl60DWmuLWmxiRhe\nMYQ2+8iyPDmxcPFTGSpGqyvyJDjQ/wOlWVkCQQCRIuotZW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