SSLSocket passphrase/password in Python

2019-02-01 03:19发布

问题:

I've been looking into making an iOS push notification service for one of my apps lately. It has a Python 2.7 backend so I wanted to do it in Python rather than PHP (or anything else).

I've got code that sends a notification and the device receives it, however every time I run the code it asks me to manually enter a 'pass phrase' for the PEM file.

This is not ideal, as I want this to be all automated on the server, when it needs to send a notification, it should just send it. I can't find anything in the docs for Python 2.7 that allow me to automatically set the pass phrase from a variable when connecting.

If anyone knows how to do this in Python 2.7 or any other ideas I would be really grateful.

Here's a snippet of code:

certfile = 'devPEM.pem'
apns_address = ('gateway.sandbox.push.apple.com', 2195)

s = socket.socket()
sock = ssl.wrap_socket(s, ssl_version=ssl.PROTOCOL_SSLv3, certfile=certfile)
sock.connect(apns_address)

Thanks in advance.

回答1:

So the answer as BorrajaX suggested was to not set a password for the key when prompted. However this is not possible as (at least on my Mac) wants the password to be a minimum 4 characters.

The steps to fix this are:

  1. Create the certificate in the developer portal.
  2. Download and open the certificate locally in Keychain Access
  3. Export the certificate’s private key as a .p12 file from Keychain Access (I named it aps_key.p12).
  4. Run the following on the .p12 key:
    openssl pkcs12 -nocerts -out aps_key.pem -in aps_key.p12
  5. Enter a password (which we will strip in a minute).
  6. Run the following to strip the password:
    openssl rsa -in aps_key.pem -out new_aps_key.pem
  7. Convert the .cer downloaded from the Developer Center to a .pem file:
    openssl x509 -in aps.cer -inform der -out aps.pem
  8. Merge the key and certificate .pem files with the following:
    cat aps.pem new_aps_key.pem > final_aps.pem
  9. You can now delete all other files, except for final_aps.pem.

The final_aps.pem file then works with the code above without getting prompted for a password/pass phrase.

This is a useful website where I found the code for removing the password from the .pem file: http://www.sslshopper.com/article-most-common-openssl-commands.html

Edit: If you don't need the certificate and the key in the same file, you can just ignore step 8 and use the aps.pem and new_aps_key.pem files.