How to implement OpenSSL functionality in Python?

后端 未结 3 1776
别跟我提以往
别跟我提以往 2021-02-04 08:42

I would like to encrypt a secret text by public-key and decrypt it by private-key in Python. I can achieve that with the openssl command:



        
3条回答
  •  长情又很酷
    2021-02-04 09:05

    Encrypt

    #!/usr/bin/env python
    import fileinput
    from M2Crypto import RSA
    
    rsa = RSA.load_pub_key("public.pem")
    ctxt = rsa.public_encrypt(fileinput.input().read(), RSA.pkcs1_oaep_padding)
    print ctxt.encode('base64')
    

    Decrypt

    #!/usr/bin/env python
    import fileinput
    from M2Crypto import RSA
    
    priv = RSA.load_key("private.pem")
    ctxt = fileinput.input().read().decode('base64')
    print priv.private_decrypt(ctxt, RSA.pkcs1_oaep_padding)
    

    Dependencies:

    • M2Crypto (seems to be Python 2 only)

    See also How to encrypt a string using the key and What is the best way to encode string by public-key in python.

提交回复
热议问题