0

I created a private and pulic key key using command :

 .....
 openssl genrsa -aes256 -passout pass:password -out key.pem
 4096 &&
openssl rsa -in key.pem -passin pass:password -pubout -out 
 pukey.pub

and then created cert file using this command:

 openssl req -new -key key.pem -passin pass:password -x509 -out 
 keycert.pem -days 365000 -subj '/CN=localhost'

so I have protected the key.pem with a password and I want to open it in my python program, how can I specify the password to open key.pem file and keycert.pem file?

with open('../key.pem', 'rb') as f:
   private_key = f.read()
with open('../keycert.pem', 'rb') as f:
   certificate_chain = f.read()
   

when I run this I get error :

E1117 13:57:03.515461744   70812 ssl_transport_security.cc:854] 
Invalid private key.

which shows it could not open the key.pem file as it is protected by a password

sama
  • 333
  • 2
  • 11
  • How are you using the key? Just opening and reading a file shouldn't throw an error. You can decode the key using a `cryptography` package. – mx0 Nov 17 '22 at 13:31
  • Does this answer your question? [read certificate(.crt) and key(.key) file in python](https://stackoverflow.com/questions/38782787/read-certificate-crt-and-key-key-file-in-python) – tevemadar Nov 17 '22 at 14:13
  • actually now I think it will be work: with open('key.pem', 'rb') as f: private_key=serilalization.load_pem_private_key(f.read(), password="1".encode(), backend=default_backend()) but I need that the return value be in Byte and it seems the return value of this method is _RSAPrivateKey – sama Nov 17 '22 at 14:15
  • Do you know how can I convert _RSAPrivateKey to byte in python? – sama Nov 17 '22 at 14:16

1 Answers1

2

use this line :

with open('key.pem', 'rb') as f:
    private_key=load_pem_private_key(f.read(), password="1".encode(),
                                              backend=default_backend())
    pem =private_key.private_bytes(
    encoding=serialization.Encoding.PEM,
    format=serialization.PrivateFormat.TraditionalOpenSSL,
    encryption_algorithm=serialization.NoEncryption()
    )

solved the problem , first the private key is loaded second it is converted to the bytes.

sama
  • 333
  • 2
  • 11