简体   繁体   中英

How to authenticate self signed certificate with password using Python requests

I am trying to send https request to IIS server using python request and fetch the response for parsing.Authentication is done using self signed certificates.I have generated certificate with password and key by using following commands. I am using TestPublicKey.pem and plainkey.pem as inputs to cert attribute in requests.get method. Can someone guide me how to achieve this ?

C:\OpenSSL-Win64\bin>openssl req -x509 -newkey rsa:2048 -keyout TestPrivateKey.pem -out TestPublicKey.pem -days 9999

C:\OpenSSL-Win64\bin>openssl pkcs12 -inkey TestPrivateKey.pem -in TestPublicKey.pem -export -out Test.pfx
Enter pass phrase for cTestPrivateKey.pem:
Enter Export Password:
Verifying - Enter Export Password:

C:\OpenSSL-Win64\bin>openssl rsa -in TestPrivateKey.pem -out plainkey.pem
Enter pass phrase for TestPrivateKey.pem:
writing RSA key


import requests
url = "https://10.110.20.75/REST/getxml"
r = requests.request("GET", url, verify=False,cert=('TestPublicKey.pem','plainkey.pem'))
print r.status_code

if verify is set to False , then getting 403 status_code. If verify is set to True then SSL Error exception is raised.

 raise SSLError(e, request=request)
requests.exceptions.SSLError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed (_ssl.c:661)

I got this resolved by trying with following openssl commands and python code. Note: This answer is certificate without password, if any answers or comments.I am glad to see.

Open SSL commands

Generate the self signed certificate

openssl req -x509 -nodes -days 30 -newkey rsa:2048 -keyout test_Private.key -out test_certificate.cer -subj "/CN=*.hpe.com"

Convert certificate and private key to .PFX

openssl pkcs12 -export -out test_PFX.pfx -inkey test_Private.key -in test_certificate.cer -name "*.hpe.com" -passout pass: 

Python code

import requests
url = "https://10.110.20.75/REST/getxml"
webServiceResponse=requests.request("GET",url,verify='test_certificate.cer)
print webServiceResponse.status_code
print webServiceResponse.json()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM