Q:

Generating RSA and writing to file

why do i get exception in this code:
I get output:

[*] Error creating your key
[*] Error creating your key

import os, hashlib
from Crypto.Cipher import AES
from Crypto.PublicKey import RSA

raw_key = RSA.generate(2048)
private_key = raw_key.exportKey('PEM')
try:
with open('master_private.pem', 'w+') as keyfile:
    keyfile.write(private_key)
    keyfile.close()
print ("[*] Successfully created your MASTER RSA private key")
except:
print ("[*] Error creating your key")

make_public = raw_key.publickey()
public_key = make_public.exportKey('PEM')
try:
with open("master_public.pem", "w+") as keyfile:
    keyfile.write(public_key)
    keyfile.close()
print ("[*] Successfully created your MASTER RSA public key")
except:
print ("[*] Error creating your key")

File is created successfully but it is not filled with anything. I am just starting Python.

A:

you should catch exeception and show to know the problem, but i think your problem is the write method, private_key its bytes but you must be pass a str to write method them you can try:
   keyfile.write(private_key.decode())

other problem could be your permission permissions, mabe not have permission to create a file, try catching the excaption and printing to know what happen
try:
    with open('master_private.pem', 'w+') as keyfile:
    keyfile.write(private_key)
    keyfile.close()
    print ("[*] Successfully created your MASTER RSA private key")
except Exception as e:
    print ("[*] Error creating your key", e)

also check your syntax why that code is not well tried

