SSL Connection Using .pem Certificate With Python

六月ゝ 毕业季﹏ 提交于 2019-12-03 21:40:47

It would seem that some of the "higher level" libraries in Python are not equipped to handle this kind of authentication connection. After many days of attempts I was finally able to come up with a solution going down to the socket level.

host = 'some.host.com'
service = '/some/api/path'
port = 443

# Build the authorization info
username = '1234'
password = '5678'
path = '/path/to/key/files/'
pem_file = '{0}WS{1}._.1.pem'.format(path, username)
key_file = '{0}WS{1}._.1.key'.format(path, username)
auth = base64.b64encode('WS{0}._.1:{1}'.format(username, password))

## Create the header
http_header = "POST {0} HTTP/1.0\nHost: {1}\nContent-Type: text/xml\nAuthorization: Basic {2}\nContent-Length: {3}\n\n"
req = http_header.format(service, host, auth, len(xml_string)) + xml_string

## Create the socket
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn = ssl.wrap_socket(sock, keyfile = key_file, certfile = pem_file)
conn.connect((host, port))
conn.send(req)

response = ''
while True:
    resp = conn.recv()
    response += resp

    if (resp == ''):
        break

I hope someone finds this useful. This particular implementation was to interface with Link Point Gateway with Python (not supported by First Data (Link Point)). Talk about a nightmare this whole project has been. haha

Anyway, for anyone having trouble using Link Point please be advised that the .key file they provide you is not sufficient for creating a connection in Python.

openssl rsa -in orig_file.key -out new_file.key

Then use the new_file.key instead.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!