Parse RSA key pair from string in Python

2019-07-27 02:11发布

I'm trying to generate/read a RSA-keypair from the publicKey and the privateKey as a String.

Something like this:

priK = "-----BEGIN RSA PRIVATE KEY-----MIIBOQIBAAJAVJhUS0gLqXLOmVv2xG23oFPwim9+rVxGhLUXqKShQCvB3iRMOHn7/GNJumpwmnglcsNXuqAhN0OxqKGGJdtYdwIDAQABAkBP0VrXnSbDvvuIX+k59Xvo3sp7FDAmSoaO+H9WM9+ht5H/f/geIrSEXSIkFLnzniMwtOJ422GmkDkL1F67HuDhAiEAlNauDiq3RqoXufbauyPEOG9fMS2pvB+auT2XCHJhhKsCIQCRgIo7WIRZYnNpNRWaoppUQK3g+aM8sdeBYpbs2nwDZQIgZXIxrmxFAUAb7d+oVFdbfc/DRSTHhPbRoaKuF87GUwMCIFmzaATsLjO42TPMETSS+BfnBAtFe5hIf3Z5pFgC3h9tAiEAgYjug92fmVvE+CcRSg6at7meSEbK/Kxg7Ar4mlkXMlI=-----END RSA PRIVATE KEY-----"

pubK = "-----BEGIN PUBLIC KEY-----MFswDQYJKoZIhvcNAQEBBQADSgAwRwJAVJhUS0gLqXLOmVv2xG23oFPwim9+rVxGhLUXqKShQCvB3iRMOHn7/GNJumpwmnglcsNXuqAhN0OxqKGGJdtYdwIDAQAB-----END PUBLIC KEY-----"

keyPair = RSA.importKey(priK + pubK)

My error that I'm getting is:

in importKey
    if lines[1].startswith(b('Proc-Type:4,ENCRYPTED')):

I don't even know if it's possible like that. I didn't really find information about that.

1条回答
看我几分像从前
2楼-- · 2019-07-27 02:47

RSA.importKey(key) imports one key. It cannot import concatenated keys.

If you import a private key, then you can extract a public key from that, because common PKCS#1 and PKCS#8 format have all the necessary information to create public key. So, you don't even need to concatenate the public key to it.

Use:

privateKey = RSA.importKey(priK)
publicKey = privateKey.publickey()
查看更多
登录 后发表回答