How can I encrypt with a RSA private key in python?

后端 未结 3 1931
耶瑟儿~
耶瑟儿~ 2021-01-01 01:09

Is it possible to encrypt a message with a private key in python using pycryptodome or any other library? I know that you are not supposed to encrypt with the private key an

3条回答
  •  清歌不尽
    2021-01-01 02:02

    Looks like pycrypto has not been under active development since 2014 and support ended at python 3.3. cryptography seems like the standard now.

    Using cryptography:

    from cryptography.hazmat.primitives import serialization
    from cryptography.hazmat.primitives.asymmetric import rsa
    from cryptography.hazmat.backends import default_backend
    
    password = b'thepassword'
    
    key = rsa.generate_private_key(
        backend=default_backend(),
        public_exponent=65537,
        key_size=2048
    )
    
    private_key = key.private_bytes(
        serialization.Encoding.PEM,
        serialization.PrivateFormat.PKCS8,
        serialization.BestAvailableEncryption(password)
    )
    
    public_key = key.public_key().public_bytes(
        serialization.Encoding.OpenSSH,
        serialization.PublicFormat.OpenSSH
    )
    

提交回复
热议问题