简体   繁体   English

如何将字符串转换为“BEGIN RSA PUBLIC KEY”的格式

[英]How can I Covert a string into format of “BEGIN RSA PUBLIC KEY”

I am simulating to login a website, and the server feed back a "pubkey" for RSA Encryption. 我正在模拟登录网站,服务器反馈RSA加密的“pubkey”。 I should encrypt my password with the "pubkey". 我应该使用“pubkey”加密我的密码。 The content is: 内容是:

-----BEGIN PUBLIC KEY-----
MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDWgW3gsfqzrID7Bz+pfcHD1TMP
CFAE0/1fnJnPDumXD6p75LTCpkA1jxVFpunLqIgKtSr8M84z5dyX4QQ9Rtb4tcd6
3ptgQZkoIGqrVdwskL8pSkTjI6zkG4ebB5UmlNiRQw7TcwmufOfYfAS94PGZaDxH
wFGtMyOvP2UXBxduMwIDAQAB
-----END PUBLIC KEY-----

Now, the question is I failed to convert it into the format "RSAPublicKey" with the rsa package of python2.7.8. 现在,问题是我无法使用python2.7.8的rsa包将其转换为“RSAPublicKey”格式。

ERROR CODE: 错误代码:

key = rsa.key.PublicKey.load_pkcs1(self.publickey["pubkey"].encode("utf-8"), "PEM")

ERROR HINT: 错误提示:

ValueError: No PEM start marker "-----BEGIN RSA PUBLIC KEY-----" found

I would use the right "rsapublickey" for: 我会使用正确的“rsapublickey”:

password_rsaed = base64.b64encode(rsa.encrypt(self.password.encode("utf-8"), key))

I'va got a method to solve the problem. 我有一个解决问题的方法。 It's : 它的 :

rsa.PublicKey.load_pkcs1_openssl_pem(cls, keyfile)

It loads a PKCS#1.5 PEM-encoded public key file from OpenSSL, and can recognize the content starting with "-----BEGIN PUBLIC KEY-----", and return a publickey object. 它从OpenSSL加载PKCS#1.5 PEM编码的公钥文件,并且可以识别以“----- BEGIN PUBLIC KEY -----”开头的内容,并返回一个publickey对象。

print(type(self.publickey["pubkey"].encode("utf-8")))
key = rsa.PublicKey.load_pkcs1_openssl_pem(self.publickey["pubkey"].encode("utf-8"))
print(type(key))

RESULTS: 结果:

<class 'bytes'>
<class 'rsa.key.PublicKey'>

TIPS: The method are from python3. 提示:该方法来自python3。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM