Skip to content
Advertisement

How to use public key to encrypt data and use base64 encode it in python?

I want to implement the following function using python, it uses public key to encrypt the password and then using base64 to encode it. I have searched many answers but I didn’t find a solution, I think probably I didn’t understand them. Would you please give me some advice?

JavaScript

I use the following code, but it raises error M2Crypto.RSA.RSAError.

JavaScript

Advertisement

Answer

The full error message is: M2Crypto.RSA.RSAError: no start line, indicating that the key is imported incorrectly.

load_key_string() requires a PEM-encoded private key in PKCS#1 or PKCS#8 format, but no public key. A PEM encoded public key in X.509/SPKI format can be imported with load_pub_key_bio().

From the posted X.509/SPKI key a PEM encoded key can be created by adding a newline after every 64 characters and adding a corresponding header and footer:

JavaScript

Another issue is that there is no encode() defined for an integer, but presumably password is supposed to be a string and this is just a copy/paste error.

With these changes the code works.

Note that a 1024 bits RSA key (like yours) is insecure nowadays, instead the length should be >= 2048 bits.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement