How to load a public RSA key into Python-RSA from a file?

前端 未结 5 1041
南笙
南笙 2020-12-31 10:08

I generated a private and a public key using OpenSSL with the following commands:

openssl genrsa -out private_key.pem 512
openssl rsa -in private_key.pem -pu         


        
相关标签:
5条回答
  • 2020-12-31 10:16

    To load an OpenSSL generated public key file with python-rsa library, try

    with open('public_key.pub', mode='rb') as public_file:
        key_data = public_file.read()
        public_key = rsa.PublicKey.load_pkcs1_openssl_pem(key_data)
    
    0 讨论(0)
  • 2020-12-31 10:19

    Python-RSA uses the PEM RSAPublicKey format and the PEM RSAPublicKey format uses the header and footer lines: openssl NOTES

    -----BEGIN RSA PUBLIC KEY-----
    -----END RSA PUBLIC KEY-----
    

    Output the public part of a private key in RSAPublicKey format: openssl EXAMPLES

     openssl rsa -in key.pem -RSAPublicKey_out -out pubkey.pem
    
    0 讨论(0)
  • 2020-12-31 10:27

    If on Python3, You also need to open the key in binary mode, e.g:

    with open('private_key.pem', 'rb') as privatefile:
    
    0 讨论(0)
  • 2020-12-31 10:29
    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.backends import default_backend
    
    
    def load_keys():
        with open("public.pem", "rb") as f:
            public = serialization.load_pem_public_key(
                f.read(), backend=default_backend()
            )
        with open("private.pem", "rb") as f:
            private = serialization.load_pem_private_key(
                f.read(), None, backend=default_backend()
            )
        return private, public
    
    0 讨论(0)
  • 2020-12-31 10:32

    You can generate private key by ssh-keygen:

    ssh-keygen -t rsa
    

    and generate public key like this:

    ssh-keygen -e -m pem -f xxx > pubkey.pem
    

    http://blog.oddbit.com/2011/05/08/converting-openssh-public-keys/

    0 讨论(0)
提交回复
热议问题