开发者

Using RSA in Python

I am using RSA to encrypt/decrypt my session keys in Python. I am using Pycrypto library. After generating the keypair, I want to extract the private key and public key from that generated key and store them in different files. How can I do this? I can开发者_JAVA技巧 see the has Private method which can tell that the generated keypair has private component but not able to find how to extract both the keys from this generated keypair. Any Suggestion would be of great help.


If you want to get the different parts from the key, there is key attribute for that:

>>> 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

Available components are 'n', 'e', 'd', 'p', 'q', 'u'

If you just want to save it in PEM, you should use exportKey() method (available since 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/OnXSFc0reHa9V3kc3\nHLdOW8FdonAw0//Uwn8PnoXE7QzRqt2qgqJ+8goNpBWli/oUEIj8iC8LpptpAkBV\nFFlMfaaph8j+ZWtBHnGMGRSZe3S9qMi2WZerUYHn4tmfjEi+Gk5QT6o2Pyd3gOiB\nV0Uhwemfv/+7m65VybTBAkEA5H59kG+B9HHD5hJtksAtMh8dxk/MI8G0csduU0vu\n7K5ejL522XsHurVrWdqnk6KvjlRXqB4FsMWLE6RBgBNV0A==\n-----END RSA PRIVATE KEY-----'
>>> public.exportKey()
'-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDo1M0P3nryaF8ZITv8vCFVnjUJ\n1mnIsrqXZRTzjin69xepr3czKicG3EYSUqMODQAsvMj0tGMo+ElGOVOkPFLVVBHd\n8izgA/E1RqUzbUDMj4WnhlhAQq7tNaViOXNaZ7krJZHabZKxfYvLAQtm4tr+m5Nt\nXPBaWvjwhd5M9xvktwIDAQAB\n-----END PUBLIC KEY-----'
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜